text:
#include "qt/search_panel.hpp"
#include "qt/draw_widget.hpp"

#include "map/bookmark_manager.hpp"
#include "map/user_mark_container.hpp"

#include "drape/constants.hpp"

#include "platform/measurement_utils.hpp"

#include "std/bind.hpp"

#include <QtCore/QTimer>

#include <QtGui/QBitmap>

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  #include <QtGui/QHeaderView>
  #include <QtGui/QTableWidget>
  #include <QtGui/QLineEdit>
  #include <QtGui/QVBoxLayout>
  #include <QtGui/QHBoxLayout>
  #include <QtGui/QPushButton>
  #include <QtGui/QLabel>
#else
  #include <QtWidgets/QHeaderView>
  #include <QtWidgets/QTableWidget>
  #include <QtWidgets/QLineEdit>
  #include <QtWidgets/QVBoxLayout>
  #include <QtWidgets/QHBoxLayout>
  #include <QtWidgets/QPushButton>
  #include <QtWidgets/QLabel>
#endif

namespace qt
{
SearchPanel::SearchPanel(DrawWidget * drawWidget, QWidget * parent)
  : QWidget(parent), m_pDrawWidget(drawWidget), m_busyIcon(":/ui/busy.png")
{
  m_pEditor = new QLineEdit(this);
  connect(m_pEditor, SIGNAL(textChanged(QString const &)),
          this, SLOT(OnSearchTextChanged(QString const &)));

  m_pTable = new QTableWidget(0, 4 /*columns*/, this);
  m_pTable->setFocusPolicy(Qt::NoFocus);
  m_pTable->setAlternatingRowColors(true);
  m_pTable->setShowGrid(false);
  m_pTable->setSelectionBehavior(QAbstractItemView::SelectRows);
  m_pTable->verticalHeader()->setVisible(false);
  m_pTable->horizontalHeader()->setVisible(false);
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  m_pTable->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
#else
  m_pTable->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
#endif

  connect(m_pTable, SIGNAL(cellClicked(int, int)), this, SLOT(OnSearchPanelItemClicked(int,int)));

  m_pClearButton = new QPushButton(this);
  connect(m_pClearButton, SIGNAL(pressed()), this, SLOT(OnClearButton()));
  m_pClearButton->setVisible(false);
  m_pClearButton->setFocusPolicy(Qt::NoFocus);
  m_pAnimationTimer = new QTimer(this);
  connect(m_pAnimationTimer, SIGNAL(timeout()), this, SLOT(OnAnimationTimer()));

  QHBoxLayout * horizontalLayout = new QHBoxLayout();
  horizontalLayout->addWidget(m_pEditor);
  horizontalLayout->addWidget(m_pClearButton);
  QVBoxLayout * verticalLayout = new QVBoxLayout();
  verticalLayout->addLayout(horizontalLayout);
  verticalLayout->addWidget(m_pTable);
  setLayout(verticalLayout);

  // for multithreading support
  CHECK(connect(this, SIGNAL(SearchResultSignal(ResultsT *)),
                this, SLOT(OnSearchResult(ResultsT *)), Qt::QueuedConnection), ());

  m_params.m_onResults = bind(&SearchPanel::SearchResultThreadFunc, this, _1);
}

void SearchPanel::SearchResultThreadFunc(ResultsT const & result)
{
  emit SearchResultSignal(new ResultsT(result));
}

namespace
{
QTableWidgetItem * CreateItem(QString const & s)
{
  QTableWidgetItem * item = new QTableWidgetItem(s);
  item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
  return item;
}
}  // namespace

void SearchPanel::ClearResults()
{
  m_pTable->clear();
  m_pTable->setRowCount(0);
  m_results.clear();
}

void SearchPanel::OnSearchResult(ResultsT * results)
{
  unique_ptr<ResultsT> const guard(results);

  if (results->IsEndMarker())
  {
    if (results->IsEndedNormal())
    {
      // stop search busy indicator
      m_pAnimationTimer->stop();
      m_pClearButton->setIcon(QIcon(":/ui/x.png"));
    }
  }
  else
  {
    ClearResults();

    for (ResultsT::IterT i = results->Begin(); i != results->End(); ++i)
    {
      ResultT const & res = *i;

      QString const name = QString::fromStdString(res.GetString());
      QString strHigh;
      int pos = 0;
      for (size_t r = 0; r < res.GetHighlightRangesCount(); ++r)
      {
        pair<uint16_t, uint16_t> const & range = res.GetHighlightRange(r);
        strHigh.append(name.mid(pos, range.first - pos));
        strHigh.append("");
        strHigh.append(name.mid(range.first, range.second));
        strHigh.append("");

        pos = range.first + range.second;
      }
      strHigh.append(name.mid(pos));

      int const rowCount = m_pTable->rowCount();
      m_pTable->insertRow(rowCount);
      m_pTable->setCellWidget(rowCount, 1, new QLabel(strHigh));
      m_pTable->setItem(rowCount, 2, CreateItem(QString::fromStdString(res.GetAddress())));

      if (res.GetResultType() == ResultT::RESULT_FEATURE)
      {
        m_pTable->setItem(rowCount, 0, CreateItem(QString::fromStdString(res.GetFeatureType())));
        m_pTable->setItem(rowCount, 3, CreateItem(m_pDrawWidget->GetDistance(res).c_str()));
      }

      m_results.push_back(res);
    }
  }
}

// TODO: This code only for demonstration purposes and will be removed soon
bool SearchPanel::TryChangeMapStyleCmd(QString const & str)
{
  // Hook for shell command on change map style
  bool const isDark = (str == "mapstyle:dark") || (str == "?dark");
  bool const isLight = isDark ? false : (str == "mapstyle:light") || (str == "?light");
  bool const isOld = isDark || isLight ? false : (str == "?oldstyle");

  if (!isDark && !isLight && !isOld)
    return false;

  // close Search panel
  m_pEditor->setText("");
  parentWidget()->hide();

  // change color scheme for the Map activity
  MapStyle const mapStyle = isOld ? MapStyleLight : (isDark ? MapStyleDark : MapStyleClear);
  m_pDrawWidget->SetMapStyle(mapStyle);

  return true;
}

// TODO: This code only for demonstration purposes and will be removed soon
bool SearchPanel::TryChangeRouterCmd(QString const & str)
{
  routing::RouterType routerType;
  if (str == "?pedestrian")
    routerType = routing::RouterType::Pedestrian;
  else if (str == "?vehicle")
    routerType = routing::RouterType::Vehicle;
  else if (str == "?bicycle")
    routerType = routing::RouterType::Bicycle;
  else
    return false;

  m_pEditor->setText("");
  parentWidget()->hide();
  m_pDrawWidget->SetRouter(routerType);
  return true;
}

// TODO: This code only for demonstration purposes and will be removed soon
bool SearchPanel::Try3dModeCmd(QString const & str)
{
  bool const is3dModeOn = (str == "?3d");
  bool const is3dBuildingsOn = (str == "?b3d");
  bool const is3dModeOff = (str == "?2d");

  if (!is3dModeOn && !is3dBuildingsOn && !is3dModeOff)
    return false;

  m_pDrawWidget->GetFramework().Save3dMode(is3dModeOn || is3dBuildingsOn, is3dBuildingsOn);
  m_pDrawWidget->GetFramework().Allow3dMode(is3dModeOn || is3dBuildingsOn, is3dBuildingsOn);

  return true;
}

bool SearchPanel::TryMigrate(QString const & str)
{
  bool const isMigrate = (str == "?migrate");

  if (!isMigrate)
    return false;

  m_pEditor->setText("");
  parentWidget()->hide();

  auto const stateChanged = [&](storage::TCountryId const & id)
  {
    storage::Status const nextStatus = m_pDrawWidget->GetFramework().Storage().GetPrefetchStorage()->CountryStatusEx(id);
    LOG_SHORT(LINFO, (id, "status :", nextStatus));
    if (nextStatus == storage::Status::EOnDisk)
    {
      LOG_SHORT(LINFO, ("Prefetch done. Ready to migrate."));
      m_pDrawWidget->GetFramework().Migrate();
    }
  };

  auto const progressChanged = [](storage::TCountryId const & id, storage::MapFilesDownloader::TProgress const & sz)
  {
    LOG(LINFO, (id, "downloading progress:", sz));
  };

  ms::LatLon curPos(55.7, 37.7);

  m_pDrawWidget->GetFramework().PreMigrate(curPos, stateChanged, progressChanged);
  return true;

}

bool SearchPanel::TryDisplacementModeCmd(QString const & str)
{
  bool const isDefaultDisplacementMode = (str == "?dm:default");
  bool const isHotelDisplacementMode = (str == "?dm:hotel");

  if (!isDefaultDisplacementMode && !isHotelDisplacementMode)
    return false;

  if (isDefaultDisplacementMode)
    m_pDrawWidget->GetFramework().SetDisplacementMode(dp::displacement::kDefaultMode);
  else if (isHotelDisplacementMode)
    m_pDrawWidget->GetFramework().SetDisplacementMode(dp::displacement::kHotelMode);

  return true;
}

void SearchPanel::OnSearchTextChanged(QString const & str)
{
  QString const normalized = str.normalized(QString::NormalizationForm_KC);

  // TODO: This code only for demonstration purposes and will be removed soon
  if (TryChangeMapStyleCmd(normalized))
    return;
  if (TryChangeRouterCmd(normalized))
    return;
  if (Try3dModeCmd(normalized))
    return;
  if (TryMigrate(normalized))
    return;
  if (TryDisplacementModeCmd(normalized))
    return;

  // search even with empty query
  if (!normalized.isEmpty())
  {
    m_params.m_query = normalized.toUtf8().constData();
    if (m_pDrawWidget->Search(m_params))
    {
      // show busy indicator
      if (!m_pAnimationTimer->isActive())
        m_pAnimationTimer->start(200);

      m_pClearButton->setFlat(true);
      m_pClearButton->setVisible(true);
    }
  }
  else
  {
    ClearResults();

    m_pDrawWidget->GetFramework().CancelInteractiveSearch();

    // hide X button
    m_pClearButton->setVisible(false);
  }
}

void SearchPanel::OnSearchPanelItemClicked(int row, int)
{
  ASSERT_EQUAL(m_results.size(), static_cast<size_t>(m_pTable->rowCount()), ());

  if (m_results[row].IsSuggest())
  {
    // insert suggestion into the search bar
    string const suggestion = m_results[row].GetSuggestionString();
    m_pEditor->setText(QString::fromUtf8(suggestion.c_str()));
  }
  else
  {
    // center viewport on clicked item
    m_pDrawWidget->ShowSearchResult(m_results[row]);
  }
}

void SearchPanel::hideEvent(QHideEvent *)
{
  m_pDrawWidget->GetFramework().CancelInteractiveSearch();
}

void SearchPanel::OnAnimationTimer()
{
  static int angle = 0;

  QMatrix rm;
  angle += 15;
  if (angle >= 360)
    angle = 0;
  rm.rotate(angle);

  m_pClearButton->setIcon(QIcon(m_busyIcon.transformed(rm)));
}

void SearchPanel::OnClearButton()
{
  m_pEditor->setText("");
}
}  // namespace qt


text:
package com.impetus.client.hbase.schema;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.NamespaceNotFoundException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.impetus.client.hbase.testingutil.HBaseTestingUtils;
import com.impetus.client.hbase.utils.HBaseUtils;
import com.impetus.kundera.PersistenceProperties;
import com.impetus.kundera.configure.schema.SchemaGenerationException;

/**
 * The Class HBaseSchemaGenerationTest.
 *
 * @author Pragalbh Garg
 */
public class HBaseSchemaGenerationTest
{

    /** The Constant HBASE_PU. */
    private static final String HBASE_PU = "schemaTest";

    /** The Constant SCHEMA. */
    private static final String SCHEMA = "HBaseNew";

    /** The TABL e_1. */
    private String TABLE_1 = HBaseUtils.getHTableName(SCHEMA, "USER_HBASE");

    /** The TABL e_2. */
    private String TABLE_2 = HBaseUtils.getHTableName(SCHEMA, "PRODUCT_HBASE");

    /** The admin. */
    private static HBaseAdmin admin;

    /** The property map. */
    private Map propertyMap = new HashMap();

    /** The connection. */
    private static Connection connection;

    /**
     * Sets the up before class.
     *
     * @throws Exception
     *             the exception
     */
    @BeforeClass
    public static void setUpBeforeClass() throws Exception
    {
        connection = ConnectionFactory.createConnection();
        admin = (HBaseAdmin) connection.getAdmin();
    }

    /**
     * Tear down after class.
     *
     * @throws Exception
     *             the exception
     */
    @AfterClass
    public static void tearDownAfterClass() throws Exception
    {
        admin.close();
        connection.close();
        HBaseTestingUtils.dropSchema(SCHEMA);
    }

    /**
     * Test operations.
     *
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    @Test
    public void testOperations() throws IOException
    {
        testCreate();
        testUpdate();
        testValidate();
        testCreateDrop();
    }

    /**
     * Test create.
     *
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public void testCreate() throws IOException
    {
        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, "create");
        assertSchema();
    }

    /**
     * Test update.
     *
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public void testUpdate() throws IOException
    {

        init();

        admin.disableTable(TABLE_2);
        admin.deleteTable(TABLE_2);
        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, "update");

        assertSchema();

        postAssert();
    }

    /**
     * Test validate.
     *
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    private void testValidate() throws IOException
    {
        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, "validate");
        assertSchema();

        assertInValidate();

    }

    /**
     * Assert in validate.
     *
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    private void assertInValidate() throws IOException
    {
        admin.disableTable(TABLE_2);
        admin.deleteTable(TABLE_2);
        try
        {
            EntityManagerFactory emf = Persistence.createEntityManagerFactory(HBASE_PU, propertyMap);
            EntityManager em = emf.createEntityManager();
            Assert.assertTrue(false);
            em.close();
            emf.close();
        }
        catch (SchemaGenerationException sge)
        {
            Assert.assertTrue(true);
        }

    }

    /**
     * Test create drop.
     *
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public void testCreateDrop() throws IOException
    {
        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, "create-drop");
        assertSchema();

        assertDrop();

    }

    /**
     * Assert drop.
     */
    private void assertDrop()
    {
        try
        {
            for (NamespaceDescriptor ns : admin.listNamespaceDescriptors())
            {
                if (ns.getName().equals(SCHEMA))
                {
                    Assert.assertTrue(false);
                    break;
                }
            }
        }
        catch (IOException ioex)
        {
            throw new SchemaGenerationException(ioex, "Hbase");
        }

    }

    /**
     * Assert schema.
     *
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    private void assertSchema() throws IOException
    {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(HBASE_PU, propertyMap);
        EntityManager em = emf.createEntityManager();

        try
        {
            admin.getNamespaceDescriptor(SCHEMA);
            Assert.assertTrue(true);
        }
        catch (NamespaceNotFoundException e)
        {
            Assert.assertTrue(false);
        }

        Assert.assertTrue(admin.isTableAvailable(TABLE_1));
        Assert.assertTrue(admin.isTableAvailable(TABLE_2));

        HTableDescriptor descriptor = admin.getTableDescriptor(TableName.valueOf(TABLE_1));
        Assert.assertTrue(descriptor.hasFamily("USER_HBASE".getBytes()));

        descriptor = admin.getTableDescriptor(TableName.valueOf(TABLE_2));
        Assert.assertTrue(descriptor.hasFamily("PRODUCT_HBASE".getBytes()));

        em.close();
        emf.close();
    }

    /**
     * Inits the.
     */
    private void init()
    {
        propertyMap.remove(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE);
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(HBASE_PU, propertyMap);
        EntityManager em = emf.createEntityManager();
        UserHBase user = new UserHBase();
        user.setUserId("1");
        user.setUserName("personHbase");
        user.setPhoneNo(88888);
        em.persist(user);
        em.close();
        emf.close();

    }

    /**
     * Post assert.
     */
    private void postAssert()
    {
        propertyMap.remove(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE);
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(HBASE_PU, propertyMap);
        EntityManager em = emf.createEntityManager();
        try
        {
            UserHBase user = em.find(UserHBase.class, "1");
            if (user != null)
            {
                Assert.assertTrue(true);
            }
            else
            {
                Assert.assertTrue(false);
            }
        }
        catch (Exception e)
        {
            Assert.assertTrue(false);
        }

        em.close();
        emf.close();

    }
}

redpajama_set_name: RedPajamaGithub


text:
if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/GitExternal.cmake" AND
    EXISTS "${CMAKE_CURRENT_LIST_DIR}/../GitExternal.cmake")

  configure_file("${CMAKE_CURRENT_LIST_DIR}/GitExternal.cmake"
    "${CMAKE_CURRENT_LIST_DIR}/../GitExternal.cmake" COPYONLY)
endif()


text:
package utils

import (
	"sync/atomic"
	"testing"
	"time"

	"github.com/sirupsen/logrus"

	"github.com/onsi/gomega"
)

func TestUsingSingleAsyncOperation(t *testing.T) {
	defer func() {
		err := recover()
		if err != nil {
			logrus.Errorf("test should not fails, err: %v", err)
			t.FailNow()
		}
	}()
	m := map[int]int{}
	op := NewSingleAsyncOperation(func() {
		m[0] = 0
		m[1] = 1
		m[2] = 2
	})
	for i := 0; i < 10000; i++ {
		op.Run() // check on concurrent modification
	}
}

func TestSingleOperationRun(t *testing.T) {
	ch := make(chan bool)
	op := NewSingleAsyncOperation(func() {
		ch <- true
	})
	op.Run()
	select {
	case <-ch:
		return
	case <-time.After(time.Second):
		t.Fatal("op did not run")
	}
}

func TestLongSingleOperationRun(t *testing.T) {
	assert := gomega.NewWithT(t)
	longOperation := make(chan struct{})
	counter := int32(0)
	testDuration := time.Second
	op := NewSingleAsyncOperation(func() {
		atomic.AddInt32(&counter, 1)
		<-longOperation
	})
	timeElapsed := false
	timeCh := time.After(testDuration / 2)
	for !timeElapsed {
		select {
		case <-timeCh:
			timeElapsed = true
		default:
			op.Run()
			<-time.After(time.Millisecond * 25)
		}
	}
	close(longOperation)
	op.Wait()
	assert.Expect(counter).Should(gomega.Equal(int32(2)))
}

func TestLongSingleOperationRerun(t *testing.T) {
	assert := gomega.NewWithT(t)
	block := make(chan struct{})
	counter := int32(0)
	op := singleAsyncOperation{
		body: func() {
			if atomic.AddInt32(&counter, 1) > 2 {
				t.FailNow()
			}
			<-block
		},
		state: notScheduled,
	}

	op.Run()
	assert.Expect(op.state).Should(gomega.Equal(running))
	op.Run()
	assert.Expect(op.state).Should(gomega.Equal(scheduledAndRunning))
	op.Run()
	assert.Expect(op.state).Should(gomega.Equal(scheduledAndRunning))
	close(block)
	op.Wait()
	assert.Expect(op.state).Should(gomega.Equal(notScheduled))
	assert.Expect(counter).Should(gomega.Equal(int32(2)))
}


text:
package net.pwendland.javacard.pki.isoapplet;

import javacard.framework.*;
import net.pwendland.javacard.pki.isoapplet.UtilTLV;

/**
 * \brief The DedicatedFile class.
 *
 * This class acts as a container for any File subclass except the IsoFileSystem class itself. It is equivalent
 * to the ISO "Dedicated File".
 * Children are stored as references. This means that if a File is being altered after it was added as child,
 * also the child is effectively altered as it is the same object.
 *
 * The size of the array storing the references to the children can be set before compilation.
 * Also, this class tries to increase the size until a maximum value. If you do not want that kind of behavior,
 * set CHILDREN_COUNT_MAX to the same value as CHILDREN_COUNT_START.
 */
public class DedicatedFile extends File {
    private static final short CHILDREN_COUNT_START = 10;
    private static final short CHILDREN_COUNT_MAX = 30; // set to max. 16383

    public static final byte SPECIFY_EF = 0x01;
    public static final byte SPECIFY_DF = 0x02;
    public static final byte SPECIFY_ANY = 0x03;

    private byte currentNumChildren;
    private File[] children;

    /**
     * \brief Instantiate a new DedicatedFile.
     *
     * \param fileID The file ID. Should be unique inside the filesystem.
     *
     * \param fileControlInformation The array of bytes containing the valid (!) File Control Information.
     *				It must contain the File ID (Tag 83). No Copy is made.
     *
     * \attention No copy of the FCI is made. Do not pass any buffer that is altered
     *				later (e.g. the apdu buffer). Max length 257 bytes as the length
     *				of the FCI Tag (6F) must be a byte.
     *
     * \attention To be safe, use IsoFilesystem.getSafeFile() to instantiate files.
     *
     * \return The DedicatedFile.
     */
    public DedicatedFile(short fileID, byte[] fileControlInformation) {
        super(fileID, fileControlInformation);
        this.currentNumChildren = 0;
        this.children = new File[CHILDREN_COUNT_START];
    }

    /**
     * \brief Check if this is the name of this DedicatedFile.
     *
     * \param name The array containing the name to compare with the file's name.
     *
     * \param offset The offset at where the name begins.
     *
     * \param length The length of the name.
     *
     * \return false if the DF has no name or the names do not match,
     *			true else.
     */
    public boolean isName(byte[] name, short offset, short length) {
        // Find the position of the DF name tag (84) in the FCI.
        short namePos = UtilTLV.findTag(fci, (short)2, fci[(short)1], (byte) 0x84);
        if(namePos < 0) {
            // This DF has no name.
            return false;
        } else {
            // This DF has a name.
            if(length != UtilTLV.decodeLengthField(fci, (short)(namePos+1))) {
                // The names do not have equal length.
                return false;
            } else {
                return ( (byte)0 == Util.arrayCompare(name, offset, fci,
                                                      (short)(namePos+1+UtilTLV.getLengthFieldLength(length)), length) );
            }
        }
    }

    /**
     * \brief Get the amount of children under this Dedicated File.
     *
     * \return The amount of children under this DF.
     */
    public byte getChildrenCount() {
        return this.currentNumChildren;
    }

    /**
     * \brief Get a children of this Dedicated File.
     *
     * This method returns the specified children of this DF. Can be used in conjunction with getChildrenCount()
     * to iterate over all children.
     *
     * \param num The number of the children, starting at 0 to getChildrenCount(). The references can change when
     *				children had been deleted.
     *
     * \throw FileNotFoundException If the specified file was not found unter this DF.
     *
     * \return The children file if present. May be a DedicatedFile or any non-abstract ElementaryFile subclass.
     */
    public File getChildren(byte num) throws FileNotFoundException {
        if(num >= this.currentNumChildren) {
            throw FileNotFoundException.getInstance();
        }
        return children[num];
    }

    /**
     * \brief Delete a direct children of this DF.
     *
     * This method requests garbage collection.
     *
     * \param fileID The file ID of the children to delete.
     *
     * \throw FileNotFoundException It no children has the given fileID.
     */
    public void deleteChildren(short fileID) throws FileNotFoundException {
        short childNum = -1;
        short i;

        for(i = 0; i < currentNumChildren; i++) {
            if(fileID == children[i].getFileID()) {
                childNum = i;
                break;
            }
        }

        if(childNum == -1) {
            throw FileNotFoundException.getInstance();
        }

        children[childNum] = null;
        currentNumChildren--; // We have one less children now.

        // Fill up empty field in children array.
        // The last children is one ahead, so it is at currentNumChildren.
        if(childNum < currentNumChildren) {
            children[childNum] = children[currentNumChildren];
        }

        // Clean up the old file object.
        JCSystem.requestObjectDeletion();
    }

    /**
     * \brief Add a children to this DF.
     *
     * \param children The children to add. May be a DedicatedFile or any non-abstract ElemetaryFile subclass.
     *
     * \throw NotEnoughSpaceException If CHILDREN_COUNT_MAX is reached.
     */
    public void addChildren(File childFile) throws NotEnoughSpaceException {
        // First we have to check for enough space.
        if(currentNumChildren >= (short)children.length) {
            File[] newChildren = null;
            // The array is full - we try to increase the size.
            if((short)(children.length * 2) <= CHILDREN_COUNT_MAX) {
                // Doubling the size is possible.
                newChildren = new File[(short)(children.length * 2)];
                copyFileArrayRefs(children, newChildren);
            } else {
                // Doubling not possible - try to at least increase to CHILDREN_COUNT_MAX.
                if(currentNumChildren < CHILDREN_COUNT_MAX) {
                    newChildren = new File[CHILDREN_COUNT_MAX];
                    copyFileArrayRefs(children, newChildren);
                } else {
                    // CHILDREN_COUNT_MAX exceeded. No "space" left. Fail.
                    throw NotEnoughSpaceException.getInstance();
                }
            }
            children = newChildren; // Initial children array is now garbage.
            JCSystem.requestObjectDeletion();
        } // We have enough space (now).
        children[currentNumChildren++] = childFile;
        return;
    }

    /**
     * \brief Copies the references from one File array to the other.
     *
     * \attention Although only references are copied, this is probably still quite expensive because
     * writing to EEPROM is. Only use this for operations that are not called often (Creating and deleting files etc.).
     *
     * \param src The source File array to copy from.
     *
     * \param dest The destination File array to copy to. It MUST be at least of size of the src array.
     */
    private static void copyFileArrayRefs(File[] src, File[] dest) {
        short i = 0;
        short length = src.length > dest.length ? (short)dest.length : (short)src.length;

        for(i=0; i < length; i++) {
            dest[i] = src[i];
        }
        return;
    }

    /**
     * \brief Find the Elementary File directly under this DF with the specified file ID.
     *
     * \attention This is not a recursive search operation.
     *
     * \param fileID The file ID of the EF to search.
     *
     * \throw FileNotFoundException If the specified file was not found unter this DF.
     *
     * \return The file if it was found.
     */
    public ElementaryFile findChildElementaryFile (short fileID) throws FileNotFoundException {
        short i = 0;
        for(i=0; i < currentNumChildren; i++) {
            if(children[i].getFileID() == fileID) {
                // File ID is matching, perform a type check and return
                if(children[i] instanceof ElementaryFile) {
                    return (ElementaryFile) children[i];
                }
                // Should not happen: The elementary file that is being searched for is not a elementary file.
                // (i.e. the fileID points to a DF.)
                throw FileNotFoundException.getInstance();
            }
        }
        throw FileNotFoundException.getInstance();
    }

    /**
     * \brief Find the Elementary File directly under this DF using the Short EF identifer.
     *
     * \param sfi The Short EF identifier (5 least significant bits).
     *
     * \throw FileNotFoundException If the File could not be found.
     *
     * \return The file if it was found.
     */
    public ElementaryFile findChildElementaryFileBySFI (byte sfi) throws FileNotFoundException {
        if((sfi & 0xE0) > (byte) 0) {
            throw FileNotFoundException.getInstance();
        }
        short i;
        for(i=0; i < currentNumChildren; i++) {
            if(children[i] instanceof ElementaryFile &&
                    ((ElementaryFile)children[i]).getShortFileID() == sfi) {
                return (ElementaryFile) children[i];
            }
        }
        throw FileNotFoundException.getInstance();
    }

    /**
     * \brief Find the Dedicated File directly under this DF with the specified file ID.
     *
     * \attention This is not a recursive search operation.
     *
     * \param fileID The file ID of the DF to search
     *
     * \throw FileNotFoundException If the specified file was not found unter this DF.
     *
     * \return The file if it was found.
     */
    public DedicatedFile findChildDedicatedFile(short fileID) throws FileNotFoundException {
        short i;
        for(i=0; i < currentNumChildren; i++) {
            if(children[i].getFileID() == fileID) {
                // File ID is matching, perform a type check and return
                if(children[i] instanceof DedicatedFile) {
                    return (DedicatedFile) children[i];
                }
                // Should not happen: The dedicated file that is being searched for is not a dedicated file.
                // (i.e. the fileID points to a EF.)
                throw FileNotFoundException.getInstance();
            }
        }
        throw FileNotFoundException.getInstance();
    }

    /**
     * \brief Recursively search the children of this file using the DedicatedFile name.
     *
     * \param name The DF name of at most 16 bytes according to ISO.
     *
     * \param nameOffset The position in the name array at which the name beigns.
     *
     * \param nameLength The length of the name
     *
     * \throw FileNotFoundException If the specified file was not found among all (sub-)children of this file.
     *
     * \return A reference to the DedicatedFile if found.
     */
    public DedicatedFile findDedicatedFileByNameRec(byte[] name, short nameOffset, short nameLength) throws FileNotFoundException {
        short i;
        for(i=0; i < currentNumChildren; i++) {
            if(children[i] instanceof DedicatedFile) {
                if(((DedicatedFile)children[i]).isName(name, nameOffset, nameLength)) {
                    return (DedicatedFile) children[i];
                }
                try {
                    return ((DedicatedFile)children[i]).findDedicatedFileByNameRec(name, nameOffset, nameLength);
                } catch(FileNotFoundException e) {
                    // Ignore this exception until the last children has unsuccessfully been visited.
                }
            }
        }
        throw FileNotFoundException.getInstance();
    }

    /**
     * \brief Recursively search the children of this file using the file ID.
     *
     * \param fileID The file ID of the file to search for.
     *
     * \throw FileNotFoundException If the specified file was not found among all (sub-)children of this file.
     *
     * \return A reference to the File if found.
     */
    public File findChildrenRec(short fileID, byte flag) throws FileNotFoundException {
        short i;
        for(i=0; i < currentNumChildren; i++) {
            if(children[i].getFileID() == fileID) {
                if((flag == SPECIFY_ANY)
                        || (flag == SPECIFY_DF && children[i] instanceof DedicatedFile)
                        || (flag == SPECIFY_EF && children[i] instanceof ElementaryFile)) {
                    return children[i];
                } else {
                    // File with specified FID and requested file type do not match.
                    throw FileNotFoundException.getInstance();
                }
            }
            if(children[i] instanceof DedicatedFile) {
                try {
                    return ((DedicatedFile)children[i]).findChildrenRec(fileID, flag);
                } catch(FileNotFoundException e) {
                    // Ignore this exception until the last children has unsuccessfully been visited.
                }
            }
        }
        throw FileNotFoundException.getInstance();
    }

    /**
     * \brief Find the children using the specified path.
     *
     * \param path The byte array containing the path. This is a concatenation of File IDs. A fileID is 2 bytes long.
     *
     * \param pathOffset The position at which the path begins. It starts with children of this file.
     *
     * \param pathLength The length of the path in bytes. Two times the FIDs contained.
     *
     * \throw FileNotFoundException If the path does not lead to a file.
     *
     * \return The File if found.
     */
    public File findChildrenByPath(byte[] path, short pathOffset, short pathLength) throws FileNotFoundException {
        byte childPos;
        short pathPos;
        short nextFileID;

        DedicatedFile df = this;
        for(pathPos=pathOffset; pathPos < (short) ((pathLength+pathOffset)-1); pathPos+=2) {
            nextFileID = Util.getShort(path, pathPos);
            for(childPos=0; childPos < df.getChildrenCount(); childPos++) {
                if(nextFileID == df.getChildren( childPos ).getFileID()) {
                    // We found the next node in the path.
                    if(pathPos == (short) (pathOffset+pathLength-2)) {
                        // It is the last File in the path with a matching FID.
                        // We are done.
                        return df.getChildren(childPos);
                    } else if(df.getChildren( childPos ) instanceof DedicatedFile) {
                        // We still have to search for children.
                        // Luckily, the last file we found is a DF. :-)
                        df = (DedicatedFile) df.getChildren( childPos);
                        break;
                    } else {
                        // Matching file ID, has children according to path, but is no DF.
                        // Something really bad happened or the path was invalid!
                        throw FileNotFoundException.getInstance();
                    }
                }
            }
        }
        // We could not find the file with that path.
        throw FileNotFoundException.getInstance();
    }

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>{{ $title }}</title>

    @yield('head')
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="{{ asset('wpanel/css/main.css') }}">

                DevTv

        <button class="hamburger hamburger--htla">
            toggle menu
        </button>

                        <button class="dropdown-toggle" id="dd-user-menu" type="button" data-toggle="dropdown"
                                aria-haspopup="true" aria-expanded="false">
                            @if(Auth::user()->avatar_url)
                                avatar_url }}" alt="{{ Auth::user()->name }}">
                            @else

                                    {{ substr(Auth::user()->name, 0, 1) }}

                            @endif
                        </button>

                                Vist Website

                                Profile

                                Logout

                    <button type="button" class="burger-right">

                    </button>

@include('wpanel.nav')

        @yield('content')

{{--

0%

--}}
@yield('footer')


text:
package org.apache.kafka.connect.util;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public abstract class ConvertingFutureCallback<U, T> implements Callback<U>, Future<T> {

    private Callback<T> underlying;
    private CountDownLatch finishedLatch;
    private T result = null;
    private Throwable exception = null;

    public ConvertingFutureCallback(Callback<T> underlying) {
        this.underlying = underlying;
        this.finishedLatch = new CountDownLatch(1);
    }

    public abstract T convert(U result);

    @Override
    public void onCompletion(Throwable error, U result) {
        this.exception = error;
        this.result = convert(result);
        if (underlying != null)
            underlying.onCompletion(error, this.result);
        finishedLatch.countDown();
    }

    @Override
    public boolean cancel(boolean b) {
        return false;
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public boolean isDone() {
        return finishedLatch.getCount() == 0;
    }

    @Override
    public T get() throws InterruptedException, ExecutionException {
        finishedLatch.await();
        return result();
    }

    @Override
    public T get(long l, TimeUnit timeUnit)
            throws InterruptedException, ExecutionException, TimeoutException {
        if (!finishedLatch.await(l, timeUnit))
            throw new TimeoutException("Timed out waiting for future");
        return result();
    }

    private T result() throws ExecutionException {
        if (exception != null) {
            throw new ExecutionException(exception);
        }
        return result;
    }
}


text:
package server_side_policies;

import common.PSNotification;
import server.Helpers;
import server.PubSubHandler;
import server_store.ServerState;
import server_store.SidePolicy;
import common.StoreAction;
import server_store_actions.GameStartableGameAction;

public class GameStartableGameSidePolicy implements SidePolicy {
    @Override
    public void apply(ServerState state, StoreAction action) {
        GameStartableGameAction castedAction = (GameStartableGameAction) action;
        if (castedAction.isStartable()){
            PubSubHandler handler = Helpers.findPubSubHandlerByPlayerToken(castedAction.getGame().getCurrentPlayer().getPlayerToken(),castedAction.getGame());
            if (handler == null){
                return;
            }
            PSNotification notification = new PSNotification(null, null,null,
                    false,false,null, null, false,false,true,false, null);

            handler.queueNotification(notification);
        }
    }
}


text:
package uk.theretiredprogrammer.nbpcglibrary.localdatabaseaccess;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import static java.sql.Types.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import uk.theretiredprogrammer.nbpcglibrary.api.EntityFields;
import uk.theretiredprogrammer.nbpcglibrary.api.PersistenceUnitProvider;
import uk.theretiredprogrammer.nbpcglibrary.common.Event;
import uk.theretiredprogrammer.nbpcglibrary.common.Listener;
import uk.theretiredprogrammer.nbpcglibrary.common.LogBuilder;
import uk.theretiredprogrammer.nbpcglibrary.api.LogicException;
import static uk.theretiredprogrammer.nbpcglibrary.localdatabaseaccess.TransactionEventParams.TransactionRequest.BEGIN;
import static uk.theretiredprogrammer.nbpcglibrary.localdatabaseaccess.TransactionEventParams.TransactionRequest.COMMIT;
import static uk.theretiredprogrammer.nbpcglibrary.localdatabaseaccess.TransactionEventParams.TransactionRequest.ROLLBACK;

/**
 * PersistenceUnit Provider for any local SQL database.
 *
 * @author Richard Linsdale (richard at theretiredprogrammer.uk)
 */
public abstract class LocalSQLPersistenceUnitProvider implements PersistenceUnitProvider {

    private Connection conn;
    private final Event<TransactionEventParams> transactionEvent;
    private boolean inTransaction = false;
    private final String name;
    private boolean operational = false;

    /**
     * Constructor.
     *
     * @param name the PersistenceUnitProvider name
     */
    public LocalSQLPersistenceUnitProvider(String name) {
        transactionEvent = new Event<>("transactions:" + name);
        this.name = name;
    }

    /**
     * set this PUP as operational
     */
    protected void setOperational() {
        operational = true;
    }

    @Override
    public boolean isOperational() {
        return operational;
    }

    @Override
    public String getName() {
        return name;
    }

    /**
     * Set the database connection being used for this PersistenceUnitProvider.
     *
     * @param conn the JDBC connection
     * @throws SQLException if problems in accessing database
     */
    protected final void setConnection(Connection conn) throws SQLException {
        this.conn = conn;
    }

    /**
     * Add a listener for Transaction events (Begin, Commit and Rollback). The
     * listener will be called on the EventQueue.
     *
     * @param l the listener
     */
    public void addListener(Listener<TransactionEventParams> l) {
        transactionEvent.addListener(l);
    }

    /**
     * Remove a listener for Transaction events.
     *
     * @param l the listener
     */
    public void removeListener(Listener<TransactionEventParams> l) {
        transactionEvent.removeListener(l);
    }

    /**
     * Add a listener for Transaction events (Begin, Commit and Rollback).
     *
     * @param l the listener
     * @param mode the listener mode (fire on event queue or immediately;
     * priority)
     */
    public void addListener(Listener<TransactionEventParams> l, Event.ListenerMode mode) {
        transactionEvent.addListener(l, mode);
    }

    /**
     * Mark the start of a Transaction unit.
     */
    public void begin() {
        LogBuilder.writeLog("nbpcglib.localdatabaseaccess", this, "begin");
        if (inTransaction) {
            throw new LogicException("begin() failed - already in transaction");
        } else {
            try {
                conn.setAutoCommit(false);
            } catch (SQLException ex) {
                LogBuilder.create("nbpcglib.localdatabaseaccess", Level.SEVERE).addMethodName(this, "begin")
                        .addExceptionMessage(ex).write();
            }
            inTransaction = true;
            transactionEvent.fire(new TransactionEventParams(BEGIN));
        }
    }

    /**
     * Mark the end of a transaction unit, commit all changes.
     */
    public void commit() {
        LogBuilder.writeLog("nbpcglib.localdatabaseaccess", this, "commit");
        if (inTransaction) {
            try {
                conn.commit();
            } catch (SQLException ex) {
                LogBuilder.create("nbpcglib.localdatabaseaccess", Level.SEVERE).addMethodName(this, "commit")
                        .addExceptionMessage(ex).write();
            }
            transactionEvent.fire(new TransactionEventParams(COMMIT));
            inTransaction = false;
        } else {
            throw new LogicException("commit() failed - not in transaction");
        }
    }

    /**
     * Mark the end of a transaction unit, rollback all changes.
     */
    public void rollback() {
        LogBuilder.writeLog("nbpcglib.localdatabaseaccess", this, "rollback");
        if (inTransaction) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                LogBuilder.create("nbpcglib.localdatabaseaccess", Level.SEVERE).addMethodName(this, "rollback")
                        .addExceptionMessage(ex).write();
            }
            transactionEvent.fire(new TransactionEventParams(ROLLBACK));
            inTransaction = false;
        } else {
            throw new LogicException("rollback() failed - not in transaction");
        }
    }

    /**
     * Test if we are currently within an active transaction unit.
     *
     * @return true if in transaction
     */
    public boolean isInTransaction() {
        return inTransaction;
    }

    /**
     * Disconnect from the current database connection.
     */
    public void disconnect() {
        try {
            conn.close();
        } catch (SQLException ex) {
            LogBuilder.create("nbpcglib.localdatabaseaccess", Level.SEVERE).addMethodName(this, "disconnect")
                    .addExceptionMessage(ex).write();
        }
    }

    /**
     * Execute an Insert, Update or Delete query on the database.
     *
     * @param sql the SQL statement
     * @return the number of records changed due to the query
     * @throws SQLException if problems
     */
    public synchronized int execute(String sql) throws SQLException {
        int res;
        try (Statement stat = conn.createStatement()) {
            res = stat.executeUpdate(sql);
        }
        return res;
    }

    /**
     * Execute a query and return the columns returned as a set of EntityFields
     * @param sql the SQL statement to be executed
     * @return a list of EntityFields
     * @throws SQLException if problems
     */
    public synchronized List<EntityFields> query(String sql) throws SQLException {
        List<EntityFields> efs = new ArrayList<>();
        try (Statement stat = conn.createStatement()) {
            ResultSet rs = stat.executeQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();
            while (rs.next()) {
                efs.add(createEntityFields(rs,rsmd));
            }
        }
        return efs;
    }

    private EntityFields createEntityFields(ResultSet rs, ResultSetMetaData meta) throws SQLException {
        EntityFields ef = new EntityFields();
        int colcount = meta.getColumnCount();
        for (int i = 1; i<= colcount; i++){
            switch (meta.getColumnType(i)) {
                case CHAR:
                case VARCHAR:
                    ef.put(meta.getColumnName(i), rs.getString(i));
                    break;
                case BOOLEAN:
                case TINYINT:
                case BIT:
                    ef.put(meta.getColumnName(i), rs.getBoolean(i));
                    break;
                case BIGINT:
                    ef.put(meta.getColumnName(i), rs.getLong(i));
                    break;
                case DECIMAL:
                    ef.put(meta.getColumnName(i), rs.getBigDecimal(i));
                    break;
                default:
                    int val = rs.getInt(i);
                    if (rs.wasNull()) {
                        ef.put(meta.getColumnName(i), null);
                    } else {
                        ef.put(meta.getColumnName(i), val);
                    }
            }
        }
        return ef;
    }
}


text:
package edu.cmu.hcii.whyline.qa;

import edu.cmu.hcii.whyline.analysis.UnexecutedInstructionAnalyzer;
import edu.cmu.hcii.whyline.bytecode.Instruction;

/**
 * Explains why a particular instruction was not reached and executed, optionally on a specific instance.
 *
 * @author Andrew J. Ko
 *
 */
public final class WhyDidntInstructionExecute extends WhyDidntQuestion<Instruction> {

	public WhyDidntInstructionExecute(Asker asker, Instruction instruction, String descriptionOfEvent) {

		super(asker, instruction, descriptionOfEvent);

		assert instruction != null : "Can't send a null instruction to " + this;

	}

	protected Answer answer() {

		// This question is used for asking about why a line didn't execute, or why some text output didn't get printed by a particular line.
		// All we know is that if its in an instance method, we know to expect a particular type for "this," whoever the caller is to the
		// method that contains this instruction.

		return UnexecutedInstructionAnalyzer.explain(this, new Instruction[] {subject}, null);

	}

	public String getQuestionExplanation() {

		return "explain why <b>" + getDescriptionOfSubject() + "</b> didn't execute";

	}

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

using Amazon.AWSSupport.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;

namespace Amazon.AWSSupport.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Resolve Case Request Marshaller
    /// </summary>
    internal class ResolveCaseRequestMarshaller : IMarshaller<IRequest, ResolveCaseRequest>
    {

        public IRequest Marshall(ResolveCaseRequest resolveCaseRequest)
        {

            IRequest request = new DefaultRequest(resolveCaseRequest, "AmazonAWSSupport");
            string target = "AWSSupport_20130415.ResolveCase";
            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.1";

            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
                uriResourcePath    = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;

            using (StringWriter stringWriter = new StringWriter())
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (resolveCaseRequest != null && resolveCaseRequest.IsSetCaseId())
                {
                    writer.WritePropertyName("caseId");
                    writer.Write(resolveCaseRequest.CaseId);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }

            return request;
        }
    }
}


text:
Rekam Pegawai

			<form action="" id="pegawaiform" method="post">
			<fieldset>

					NIP:

					<input class="form-control" id="nip" type="number" name="nip" min="100000000000000000" max="999999999999999999" value="" placeholder="nip" required>

					Nama:

					<input class="form-control" id="nama" type="text" name="nama" value="" placeholder="nama" required>

					Jabatan:

					<input class="form-control" id="jabatan" type="text" name="jabatan" value="" placeholder="jabatan" required>

				<input type="hidden" name="status" value="1">
				<input type="submit" name="submit" value="Submit" class="btn btn-default btn-lg">
			</fieldset>
			</form>


text:
#include "RoundRobinRemoteWorkerSelector.h"

#include "bistro/bistro/config/Job.h"
#include "bistro/bistro/config/Node.h"
#include "bistro/bistro/monitor/Monitor.h"  // DEFINE_MONITOR_ERROR
#include "bistro/bistro/remote/RemoteWorker.h"
#include "bistro/bistro/remote/RemoteWorkers.h"

namespace facebook { namespace bistro {

namespace {
bool tryToRun(
    const Job& job,
    const cpp2::BistroWorker& worker,
    int worker_level,
    RemoteWorkerSelector::WorkerResources* worker_resources) noexcept {

  if (!RemoteWorkerSelector::jobCanRunOnWorker(job, worker, worker_level)) {
    return false;
  }

  const auto& job_resources = job.resources();
  const auto& rv_it = worker_resources->find(*worker.shard());
  // I'm not sure, but I think this can happen if a new worker was just
  // added, but updateConfig had not yet run for it.
  if (rv_it == worker_resources->end()) {
    LOG(WARNING) << "Not using worker " << *worker.shard()
                 << " since it does "
                 << "not yet have resources";
    return false;
  }

  ResourceVector new_resources(rv_it->second);
  // In Config.cpp, the default worker level resources (and the per-host
  // overrides) are created as vector with indexes from 0 to "maximum
  // resource ID used by the worker level".  Hence, it's okay that we do not
  // look at job_resources[i] for i >= new_resources.size().  Furthermore,
  // many of the indexes in the resource vector belong to non-worker level
  // resources, and are set to INT_MAX.  You can laugh, or cry, but we just
  // pray that jobs use sufficiently small quantities of these unrelated
  // resources, so that we never run out.
  for (int i = 0; i < new_resources.size(); ++i) {
    int& amount = new_resources[i];
    amount -= job_resources[i];
    if (amount < 0) {
      return false;
    }
  }
  rv_it->second.swap(new_resources);
  return true;
}
}  // anonymous namespace

TaskRunnerResponse RoundRobinRemoteWorkerSelector::findWorker(
    const Config*,
    const Job& job,
    const Node& node,
    int worker_level,
    Monitor* monitor,
    WorkerResources* worker_resources,
    RemoteWorkers* workers,
    cpp2::BistroWorker* found_worker,
    int64_t* did_not_run_sequence_num) noexcept {

  DEFINE_MONITOR_ERROR(monitor, error, "RoundRobinRemoteWorkerSelector");
  // Optionally, respect task-locality requirements
  auto hostname = job.requiredHostForTask(node);

  const auto* first_worker = hostname.empty()
    ? workers->getNextWorker()
    : workers->getNextWorkerByHost(hostname);
  if (!first_worker) {
    LOG(WARNING) << error.report(
      "No workers were available to run ", job.name(), ", ", node.name()
    );
    return DoNotRunMoreTasks;
  }

  // At least one worker is available, so search through them until we
  // come back to the beginning.
  const auto* worker = first_worker;
  bool saw_healthy_worker = false;
  do {
    if (worker->isHealthy()) {
      saw_healthy_worker = true;
      const auto& bistro_worker = worker->getBistroWorker();
      if (tryToRun(job, bistro_worker, worker_level, worker_resources)) {
        *found_worker = bistro_worker;
        *did_not_run_sequence_num =
          worker->getNotifyIfTasksNotRunningSequenceNum();
        return RanTask;
      }
    }
    // This worker didn't have enough resources, on to the next one
    worker = hostname.empty()
      ? workers->getNextWorker()
      : workers->getNextWorkerByHost(hostname);
    CHECK(worker) << "Workers cannot disappear during search";
  } while (worker != first_worker);

  if (!saw_healthy_worker) {
    LOG(WARNING) << error.report(
      "None of the workers are healthy to run ", job.name(), ", ", node.name()
    );
    return DoNotRunMoreTasks;
  }

  // We weren't able to schedule this task. But future tasks could still run
  // if they use fewer resources.
  return DidNotRunTask;
}

}}  // namespace facebook::bistro


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>18.1.9. email.utils: Miscellaneous utilities — Pythonista Documentation</title>
    <link rel="stylesheet" href="../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Pythonista Documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Pythonista Documentation" href="../index.html" />
    <link rel="up" title="18.1. email — An email and MIME handling package" href="email.html" />
    <link rel="next" title="18.1.10. email.iterators: Iterators" href="email.iterators.html" />
    <link rel="prev" title="18.1.8. email.errors: Exception and Defect classes" href="email.errors.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          modules |

          next |

          previous |

Pythonista Documentation »

The Python Standard Library »

18. Internet Data Handling »

18.1. <tt class="docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal">email</tt> — An email and MIME handling package »

18.1.9. <tt class="xref py py-mod docutils literal">email.utils</tt>: Miscellaneous utilities¶

There are several useful utilities provided in the <tt class="xref py py-mod docutils literal">email.utils</tt> module:

<tt class="descclassname">email.utils.</tt><tt class="descname">quote</tt><big>(</big>str<big>)</big>¶

Return a new string with backslashes in str replaced by two backslashes, and
double quotes replaced by backslash-double quote.

<tt class="descclassname">email.utils.</tt><tt class="descname">unquote</tt><big>(</big>str<big>)</big>¶

Return a new string which is an unquoted version of str. If str ends and
begins with double quotes, they are stripped off.  Likewise if str ends and
begins with angle brackets, they are stripped off.

<tt class="descclassname">email.utils.</tt><tt class="descname">parseaddr</tt><big>(</big>address<big>)</big>¶

Parse address – which should be the value of some address-containing field such
as To or Cc – into its constituent realname and
email address parts.  Returns a tuple of that information, unless the parse
fails, in which case a 2-tuple of <tt class="docutils literal">('', '')</tt> is returned.

<tt class="descclassname">email.utils.</tt><tt class="descname">formataddr</tt><big>(</big>pair<big>)</big>¶

The inverse of <tt class="xref py py-meth docutils literal">parseaddr()</tt>, this takes a 2-tuple of the form <tt class="docutils literal">(realname,
email_address)</tt> and returns the string value suitable for a To or
Cc header.  If the first element of pair is false, then the
second element is returned unmodified.

<tt class="descclassname">email.utils.</tt><tt class="descname">getaddresses</tt><big>(</big>fieldvalues<big>)</big>¶

This method returns a list of 2-tuples of the form returned by <tt class="docutils literal">parseaddr()</tt>.
fieldvalues is a sequence of header field values as might be returned by
<tt class="xref py py-meth docutils literal">Message.get_all()</tt>.  Here’s a simple example that gets all the recipients
of a message:

from email.utils import getaddresses

tos = msg.get_all('to', [])
ccs = msg.get_all('cc', [])
resent_tos = msg.get_all('resent-to', [])
resent_ccs = msg.get_all('resent-cc', [])
all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)

<tt class="descclassname">email.utils.</tt><tt class="descname">parsedate</tt><big>(</big>date<big>)</big>¶

Attempts to parse a date according to the rules in RFC 2822. however, some
mailers don’t follow that format as specified, so <tt class="xref py py-func docutils literal">parsedate()</tt> tries to
guess correctly in such cases.  date is a string containing an RFC 2822
date, such as  <tt class="docutils literal">"Mon, 20 Nov 1995 19:12:08 -0500"</tt>.  If it succeeds in parsing
the date, <tt class="xref py py-func docutils literal">parsedate()</tt> returns a 9-tuple that can be passed directly to
<tt class="xref py py-func docutils literal">time.mktime()</tt>; otherwise <tt class="xref docutils literal">None</tt> will be returned.  Note that indexes 6,
7, and 8 of the result tuple are not usable.

<tt class="descclassname">email.utils.</tt><tt class="descname">parsedate_tz</tt><big>(</big>date<big>)</big>¶

Performs the same function as <tt class="xref py py-func docutils literal">parsedate()</tt>, but returns either <tt class="xref docutils literal">None</tt> or
a 10-tuple; the first 9 elements make up a tuple that can be passed directly to
<tt class="xref py py-func docutils literal">time.mktime()</tt>, and the tenth is the offset of the date’s timezone from UTC
(which is the official term for Greenwich Mean Time) [1].  If the input string
has no timezone, the last element of the tuple returned is <tt class="xref docutils literal">None</tt>.  Note that
indexes 6, 7, and 8 of the result tuple are not usable.

<tt class="descclassname">email.utils.</tt><tt class="descname">mktime_tz</tt><big>(</big>tuple<big>)</big>¶

Turn a 10-tuple as returned by <tt class="xref py py-func docutils literal">parsedate_tz()</tt> into a UTC timestamp.  It
the timezone item in the tuple is <tt class="xref docutils literal">None</tt>, assume local time.  Minor
deficiency: <tt class="xref py py-func docutils literal">mktime_tz()</tt> interprets the first 8 elements of tuple as a
local time and then compensates for the timezone difference.  This may yield a
slight error around changes in daylight savings time, though not worth worrying
about for common use.

<tt class="descclassname">email.utils.</tt><tt class="descname">formatdate</tt><big>(</big>[timeval[, localtime][, usegmt]]<big>)</big>¶

Returns a date string as per RFC 2822, e.g.:

Fri, 09 Nov 2001 01:08:47 -0000

Optional timeval if given is a floating point time value as accepted by
<tt class="xref py py-func docutils literal">time.gmtime()</tt> and <tt class="xref py py-func docutils literal">time.localtime()</tt>, otherwise the current time is
used.

Optional localtime is a flag that when <tt class="xref docutils literal">True</tt>, interprets timeval, and
returns a date relative to the local timezone instead of UTC, properly taking
daylight savings time into account. The default is <tt class="xref docutils literal">False</tt> meaning UTC is
used.

Optional usegmt is a flag that when <tt class="xref docutils literal">True</tt>, outputs a  date string with the
timezone as an ascii string <tt class="docutils literal">GMT</tt>, rather than a numeric <tt class="docutils literal">-0000</tt>. This is
needed for some protocols (such as HTTP). This only applies when localtime is
<tt class="xref docutils literal">False</tt>.  The default is <tt class="xref docutils literal">False</tt>.

New in version 2.4.

<tt class="descclassname">email.utils.</tt><tt class="descname">make_msgid</tt><big>(</big>[idstring]<big>)</big>¶

Returns a string suitable for an RFC 2822-compliant
Message-ID header.  Optional idstring if given, is a string used
to strengthen the uniqueness of the message id.

<tt class="descclassname">email.utils.</tt><tt class="descname">decode_rfc2231</tt><big>(</big>s<big>)</big>¶

Decode the string s according to RFC 2231.

<tt class="descclassname">email.utils.</tt><tt class="descname">encode_rfc2231</tt><big>(</big>s[, charset[, language]]<big>)</big>¶

Encode the string s according to RFC 2231.  Optional charset and
language, if given is the character set name and language name to use.  If
neither is given, s is returned as-is.  If charset is given but language
is not, the string is encoded using the empty string for language.

<tt class="descclassname">email.utils.</tt><tt class="descname">collapse_rfc2231_value</tt><big>(</big>value[, errors[, fallback_charset]]<big>)</big>¶

When a header parameter is encoded in RFC 2231 format,
<tt class="xref py py-meth docutils literal">Message.get_param()</tt> may return a 3-tuple containing the character set,
language, and value.  <tt class="xref py py-func docutils literal">collapse_rfc2231_value()</tt> turns this into a unicode
string.  Optional errors is passed to the errors argument of the built-in
<tt class="xref py py-func docutils literal">unicode()</tt> function; it defaults to <tt class="docutils literal">replace</tt>.  Optional
fallback_charset specifies the character set to use if the one in the
RFC 2231 header is not known by Python; it defaults to <tt class="docutils literal">us-ascii</tt>.

For convenience, if the value passed to <tt class="xref py py-func docutils literal">collapse_rfc2231_value()</tt> is not
a tuple, it should be a string and it is returned unquoted.

<tt class="descclassname">email.utils.</tt><tt class="descname">decode_params</tt><big>(</big>params<big>)</big>¶

Decode parameters list according to RFC 2231.  params is a sequence of
2-tuples containing elements of the form <tt class="docutils literal">(content-type, string-value)</tt>.

Changed in version 2.4: The <tt class="xref py py-func docutils literal">dump_address_pair()</tt> function has been removed; use <tt class="xref py py-func docutils literal">formataddr()</tt>
instead.

Changed in version 2.4: The <tt class="xref py py-func docutils literal">decode()</tt> function has been removed; use the
<tt class="xref py py-meth docutils literal">Header.decode_header()</tt> method instead.

Changed in version 2.4: The <tt class="xref py py-func docutils literal">encode()</tt> function has been removed; use the <tt class="xref py py-meth docutils literal">Header.encode()</tt>
method instead.

Footnotes

<colgroup><col class="label" /><col /></colgroup>

[1]	Note that the sign of the timezone offset is the opposite of the sign of the
<tt class="docutils literal">time.timezone</tt> variable for the same timezone; the latter variable follows
the POSIX standard while this module follows RFC 2822.

    © Copyright 1990-2016, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.0.7.


text:
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { mapToCssModules, tagPropType } from './utils';

const propTypes = {
  /** Adds border to all sides of table */
  bordered: PropTypes.bool,
  /** Removes all borders */
  borderless: PropTypes.bool,
  /** Adds custom class name to component */
  className: PropTypes.string,
  /**  */
  cssModule: PropTypes.object,
  /** Makes the table dark */
  dark: PropTypes.bool,
  /** Enables a hover state on the rows within `<tbody>` */
  hover: PropTypes.bool,
  innerRef: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.string,
    PropTypes.object,
  ]),
  /** Responsive tables allow tables to be scrolled horizontally with ease */
  responsive: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
  responsiveTag: tagPropType,
  /** Make tables more compact by cutting cell padding in half when setting size as sm. */
  size: PropTypes.string,
  /** Adds zebra-striping to any table row within the `<tbody>` */
  striped: PropTypes.bool,
  /** Add custom tag to the component */
  tag: tagPropType,
};

const defaultProps = {
  tag: 'table',
  responsiveTag: 'div',
};

function Table(props) {
  const {
    className,
    cssModule,
    size,
    bordered,
    borderless,
    striped,
    dark,
    hover,
    responsive,
    tag: Tag,
    responsiveTag: ResponsiveTag,
    innerRef,
    ...attributes
  } = props;

  const classes = mapToCssModules(
    classNames(
      className,
      'table',
      size ? 'table-' + size : false,
      bordered ? 'table-bordered' : false,
      borderless ? 'table-borderless' : false,
      striped ? 'table-striped' : false,
      dark ? 'table-dark' : false,
      hover ? 'table-hover' : false,
    ),
    cssModule,
  );

  const table = <Tag {...attributes} ref={innerRef} className={classes} />;

  if (responsive) {
    const responsiveClassName = mapToCssModules(
      responsive === true
        ? 'table-responsive'
        : `table-responsive-${responsive}`,
      cssModule,
    );

    return (
      <ResponsiveTag className={responsiveClassName}>{table}</ResponsiveTag>
    );
  }

  return table;
}

Table.propTypes = propTypes;
Table.defaultProps = defaultProps;

export default Table;


text:
<?php

namespace Outspaced\ChartsiaBundle\Chart\Renderer;

use Outspaced\ChartsiaBundle\Chart\Charts;
use Outspaced\ChartsiaBundle\Chart\Config;
use Outspaced\ChartsiaBundle\Chart\Component;
use Outspaced\ChartsiaBundle\Chart\Axis;
use Outspaced\ChartsiaBundle\Chart\Type;

/**
 * This library has been deprecated by Google, although the API is still available
 */
class Image
{
    /**
     * @var string
     */
    const BASE_URL = 'http://chart.googleapis.com/chart?';

    /**
     * @param Type\Type $type
     * @return string
     */
    protected function renderType(Type\Type $type = null)
    {
        if ($type === null) {
            return '';
        }

        switch ($type->getSlug()) {
            case 'line_chart':
                $typeName = 'lc';
                break;
            case 'bar_chart':
                $typeName = 'bhs';
                break;
            case 'pie_chart':
                $typeName = 'p';
                break;
            default:
                $typeName = '';
        }

        return 'cht=' . $typeName . '&';
    }

    /**
     * @param  Config\Size $size
     * @return string
     */
    protected function renderSize(Config\Size $size = null)
    {
        if ($size === null) {
            return '';
        }

        return 'chs=' . implode('x', $size->getDimensions()) . '&';
    }

    /**
     * @param  Config\Margin $margin
     * @return string
     */
    protected function renderMargin(Config\Margin $margin = null)
    {
        if ($margin === null) {
            return '';
        }

        return 'chma=' . implode(',', $margin->getDimensions()) . '&';
    }

    /**
     * @param  array $legendLabels
     * @return string
     */
    protected function renderLegendLabels(array $legendLabels = [])
    {
        if (empty($legendLabels)) {
            return '';
        }

        return 'chdl=' . implode('|', $legendLabels) . '&';
    }

    /**
     * so LINE COLORS?  no, just colors, motherfucker!
     *
     * @param  array $lineColors
     * @return string
     */
    protected function renderLineColors(array $lineColors = [])
    {
        if (empty($lineColors)) {
            return '';
        }

        return 'chco=' . implode(',', $lineColors) . '&';
    }

    /**
     * @param  Config\Title $title
     * @return string
     */
    protected function renderTitle(Config\Title $title = null)
    {
        if ($title === null) {
            return '';
        }

        $url = 'chtt=' . urlencode($title->getTitle()) . '&';

        if ($title->getColor() !== null) {
            $url .= 'chts=' . $title->getColor()->getColor() . '&';
        }

        return $url;
    }

    /**
     * @param Config\Legend $chartLegend
     * @return string
     */
    protected function renderChartLegend(Config\Legend $chartLegend = null)
    {
        if ($chartLegend === null) {
            return '';
        }

        //chdlp=<opt_position>|<opt_label_order>
        return 'chdls=' . $this->renderColor($chartLegend->getColor()) . ',' . $chartLegend->getFontSize() . '&';
    }

    /**
     * @param  Component\Color $color
     * @return string
     *
     * This is now DUPLICATED - need to make the decision if the renderers will extend a
     * common class now
     */
    protected function renderColor(Component\Color $color = null)
    {
        if ($color === null) {
            return '';
        }

        return $color->getColor();
    }

    /**
     * @param Charts\Chart $chart
     * @return string
     */
    protected function renderAxes(Charts\Chart $chart)
    {
        $possibleAxisKeys = [
            't' => 'getTopAxis',
            'x' => 'getBottomAxis',
            'y' => 'getLeftAxis',
            'r' => 'getRightAxis'
        ];

        $actualAxes = [];
        $positions  = [];
        $labels     = [];
        $axisColors = [];
        $gridlines  = [
            'x' => [
                'step' => 0,
                'offset' => 0
            ],
            'y' => [
                'step' => 0,
                'offset' => 0
            ],
        ];

        foreach ($possibleAxisKeys as $possibleAxisKey => $method) {

            // eg getTopAxis, getLeftAxis
            if ($axis = $chart->{$method}()) {

                $actualAxes[] = $possibleAxisKey;

                // Label
                if ($labelTings = $axis->getLabels()) {

                    $labelTexts = [];
                    $positionTings = [];

                    foreach ($labelTings as $label) {
                        $labelTexts[] = urlencode($label->getLabel());
                        $positionTings[] = $label->getPosition();
                    }

                    if (array_filter($labelTexts)) {
                        $labels[$this->getCurrentKeyFromAxesArray($actualAxes)] = implode('|', $labelTexts);
                    }

                    if (array_filter($positionTings)) {
                        $positions[$this->getCurrentKeyFromAxesArray($actualAxes)] = implode(',', $positionTings);
                    }
                }

                // Title
                if ($title = $axis->getTitle()) {
                    $actualAxes[] = $possibleAxisKey;
                    $labels[$this->getCurrentKeyFromAxesArray($actualAxes)] = $title->getValue();
                    $positions[$this->getCurrentKeyFromAxesArray($actualAxes)] = $title->getPosition();
                }

                // Gridlines
                if (in_array($possibleAxisKey, ['x', 'y'])) {
                    if ($gridlinesTing = $axis->getGridlines()) {
                        $gridlines[$possibleAxisKey]['step'] = $gridlinesTing->getStepSize();
                        $gridlines[$possibleAxisKey]['offset'] = $gridlinesTing->getOffset();
                    } else {
                        $gridlines[$possibleAxisKey]['step'] = 0;
                        $gridlines[$possibleAxisKey]['offset'] = 0;
                    }
                }

                // Axis colouring
                if ($axisColor = $axis->getColor()) {
                    $axisColors[$this->getCurrentKeyFromAxesArray($actualAxes)] = $axisColor->getColor();
                }
            }
        }

        // Add the defined axes to the URL
        $urlData = 'chxt=' . implode(',', array_values($actualAxes)) . '&';

        // Add the defined labels to the URL
        if (!empty($labels)) {
            $urlData .= 'chxl=';

            foreach ($labels as $labelKey => $labelValue) {
                $urlData .= '|' . $labelKey . ':|' . $labelValue;
            }

            $urlData .= '&';
        }

        // Add the defined positions to the URL
        if (!empty($positions)) {
            $urlData .= 'chxp=';
            foreach ($positions as $positionKey => $positionValue) {
                $urlData .= $positionKey . ',' . $positionValue . '|';
            }
            $urlData = rtrim($urlData, "|");
            $urlData .= '&';
        }

        // Add the defined positions to the URL
        if (!empty($axisColors)) {
            $urlData .= 'chxs=';
            foreach ($axisColors as $axisColorKey => $axisColor) {
                $urlData .= $axisColorKey . ',' . $axisColor . '|';
            }
            $urlData = rtrim($urlData, "|");
            $urlData .= '&';
        }

        // Add gridlines
        $urlData .= 'chg=' . $gridlines['x']['step'] . ',' .
            $gridlines['y']['step'] . ',' .
            '0,0,' .
            $gridlines['x']['offset'] . ',' .
            $gridlines['y']['offset'];

        $urlData .= '&';

        return $urlData;
    }

    /**
     * Gets the current highest key from $axes array
     *
     * @param  array $axes
     * @return int
     */
    protected function getCurrentKeyFromAxesArray(array $axes)
    {
        end($axes);

        return key($axes);
    }

    /**
     * @param  Charts\BaseChart $chart
     * @return string
     */
    public function render(Charts\Chart $chart)
    {
        $url = self::BASE_URL;

        $url .= $this->renderType($chart->getType());
        $url .= $this->renderSize($chart->getSize());
        $url .= $this->renderMargin($chart->getMargin());
        $url .= $this->renderChartLegend($chart->getLegend());
        $url .= $this->renderTitle($chart->getTitle());
        $url .= $this->renderAxes($chart);

        // DATA SETS
        $data = [];
        $lineColors = [];
        $legendLabels = [];
        $colorCollections = [];

        foreach ($chart->getDataSetCollection() as $dataSet) {

            $data[] = implode(',', $dataSet->getData());

            // Line colours
            $lineColors[] = $this->renderColor($dataSet->getColor());

            if ($legend = $dataSet->getLegend()) {
                $legendLabels[] = urlencode($legend->getLabel());
            }

            // Colour collections
            // These refer to the colours of the data representation - ie the line/bar/pie slice
            if ($colorCollection = $dataSet->getColorCollection()) {

                $tmpColorCollection = [];

                foreach ($colorCollection as $dataSetColor) {
                    $tmpColorCollection[] = $this->renderColor($dataSetColor);
                }

                $colorCollections[] = implode('|', $tmpColorCollection);
            }

            if ($legend = $dataSet->getLegend()) {
                $legendLabels[] = urlencode($legend->getLabel());
            }

        }

        // Dataset data
        $url .= 'chd=t:' . implode('|', $data) . '&';

        $url .= $this->renderLineColors($lineColors);
        $url .= $this->renderLegendLabels($legendLabels);

        if (!empty($colorCollections)) {
            $url .= 'chco=' . implode(',', $colorCollections) . '&';
        }

        // Auto-scale?
        if ($this->isAutoScale($chart)) {
            $url .= 'chds=a&';
        }

        return $url;
    }

    /**
     * @param Charts\Chart $chart
     * @return boolean
     */
    protected function isAutoScale(Charts\Chart $chart)
    {
        if ($chart->isAutoScale()) {
            return true;
        }

        if ($leftAxis = $chart->getLeftAxis()) {
            if ($leftAxis->getAutoLabel()) {
                return true;
            }
        }

        return false;
    }
}


text:
#ifndef GCC_CFGLOOP_H
#define GCC_CFGLOOP_H

#include "basic-block.h"
/* For rtx_code.  */
#include "rtl.h"
#include "vecprim.h"
#include "double-int.h"

#include "bitmap.h"
#include "sbitmap.h"

/* Structure to hold decision about unrolling/peeling.  */
enum lpt_dec
{
  LPT_NONE,
  LPT_PEEL_COMPLETELY,
  LPT_PEEL_SIMPLE,
  LPT_UNROLL_CONSTANT,
  LPT_UNROLL_RUNTIME,
  LPT_UNROLL_STUPID
};

struct GTY (()) lpt_decision {
  enum lpt_dec decision;
  unsigned times;
};

/* The structure describing a bound on number of iterations of a loop.  */

struct GTY ((chain_next ("%h.next"))) nb_iter_bound {
  /* The statement STMT is executed at most ...  */
  gimple stmt;

  /* ... BOUND + 1 times (BOUND must be an unsigned constant).
     The + 1 is added for the following reasons:

     a) 0 would otherwise be unused, while we would need to care more about
        overflows (as MAX + 1 is sometimes produced as the estimate on number
	of executions of STMT).
     b) it is consistent with the result of number_of_iterations_exit.  */
  double_int bound;

  /* True if the statement will cause the loop to be leaved the (at most)
     BOUND + 1-st time it is executed, that is, all the statements after it
     are executed at most BOUND times.  */
  bool is_exit;

  /* The next bound in the list.  */
  struct nb_iter_bound *next;
};

/* Description of the loop exit.  */

struct GTY (()) loop_exit {
  /* The exit edge.  */
  struct edge_def *e;

  /* Previous and next exit in the list of the exits of the loop.  */
  struct loop_exit *prev;
  struct loop_exit *next;

  /* Next element in the list of loops from that E exits.  */
  struct loop_exit *next_e;
};

typedef struct loop *loop_p;
DEF_VEC_P (loop_p);
DEF_VEC_ALLOC_P (loop_p, heap);
DEF_VEC_ALLOC_P (loop_p, gc);

/* An integer estimation of the number of iterations.  Estimate_state
   describes what is the state of the estimation.  */
enum loop_estimation
{
  /* Estimate was not computed yet.  */
  EST_NOT_COMPUTED,
  /* Estimate is ready.  */
  EST_AVAILABLE
};

/* Structure to hold information for each natural loop.  */
struct GTY ((chain_next ("%h.next"))) loop {
  /* Index into loops array.  */
  int num;

  /* Number of loop insns.  */
  unsigned ninsns;

  /* Basic block of loop header.  */
  struct basic_block_def *header;

  /* Basic block of loop latch.  */
  struct basic_block_def *latch;

  /* For loop unrolling/peeling decision.  */
  struct lpt_decision lpt_decision;

  /* Average number of executed insns per iteration.  */
  unsigned av_ninsns;

  /* Number of blocks contained within the loop.  */
  unsigned num_nodes;

  /* Superloops of the loop, starting with the outermost loop.  */
  VEC (loop_p, gc) *superloops;

  /* The first inner (child) loop or NULL if innermost loop.  */
  struct loop *inner;

  /* Link to the next (sibling) loop.  */
  struct loop *next;

  /* Auxiliary info specific to a pass.  */
  PTR GTY ((skip (""))) aux;

  /* The number of times the latch of the loop is executed.  This can be an
     INTEGER_CST, or a symbolic expression representing the number of
     iterations like "N - 1", or a COND_EXPR containing the runtime
     conditions under which the number of iterations is non zero.

     Don't access this field directly: number_of_latch_executions
     computes and caches the computed information in this field.  */
  tree nb_iterations;

  /* An integer guaranteed to bound the number of iterations of the loop
     from above.  */
  double_int nb_iterations_upper_bound;

  /* An integer giving the expected number of iterations of the loop.  */
  double_int nb_iterations_estimate;

  bool any_upper_bound;
  bool any_estimate;

  /* True if the loop can be parallel.  */
  bool can_be_parallel;

  /* An integer estimation of the number of iterations.  Estimate_state
     describes what is the state of the estimation.  */
  enum loop_estimation estimate_state;

  /* Upper bound on number of iterations of a loop.  */
  struct nb_iter_bound *bounds;

  /* Head of the cyclic list of the exits of the loop.  */
  struct loop_exit *exits;
};

/* Flags for state of loop structure.  */
enum
{
  LOOPS_HAVE_PREHEADERS = 1,
  LOOPS_HAVE_SIMPLE_LATCHES = 2,
  LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS = 4,
  LOOPS_HAVE_RECORDED_EXITS = 8,
  LOOPS_MAY_HAVE_MULTIPLE_LATCHES = 16,
  LOOP_CLOSED_SSA = 32,
  LOOPS_NEED_FIXUP = 64,
  LOOPS_HAVE_FALLTHRU_PREHEADERS = 128
};

#define LOOPS_NORMAL (LOOPS_HAVE_PREHEADERS | LOOPS_HAVE_SIMPLE_LATCHES \
		      | LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS)
#define AVOID_CFG_MODIFICATIONS (LOOPS_MAY_HAVE_MULTIPLE_LATCHES)

/* Structure to hold CFG information about natural loops within a function.  */
struct GTY (()) loops {
  /* State of loops.  */
  int state;

  /* Array of the loops.  */
  VEC (loop_p, gc) *larray;

  /* Maps edges to the list of their descriptions as loop exits.  Edges
     whose sources or destinations have loop_father == NULL (which may
     happen during the cfg manipulations) should not appear in EXITS.  */
  htab_t GTY((param_is (struct loop_exit))) exits;

  /* Pointer to root of loop hierarchy tree.  */
  struct loop *tree_root;
};

/* Loop recognition.  */
extern int flow_loops_find (struct loops *);
extern void disambiguate_loops_with_multiple_latches (void);
extern void flow_loops_free (struct loops *);
extern void flow_loops_dump (FILE *,
			     void (*)(const struct loop *, FILE *, int), int);
extern void flow_loop_dump (const struct loop *, FILE *,
			    void (*)(const struct loop *, FILE *, int), int);
struct loop *alloc_loop (void);
extern void flow_loop_free (struct loop *);
int flow_loop_nodes_find (basic_block, struct loop *);
void fix_loop_structure (bitmap changed_bbs);
bool mark_irreducible_loops (void);
void release_recorded_exits (void);
void record_loop_exits (void);
void rescan_loop_exit (edge, bool, bool);

/* Loop data structure manipulation/querying.  */
extern void flow_loop_tree_node_add (struct loop *, struct loop *);
extern void flow_loop_tree_node_remove (struct loop *);
extern void add_loop (struct loop *, struct loop *);
extern bool flow_loop_nested_p	(const struct loop *, const struct loop *);
extern bool flow_bb_inside_loop_p (const struct loop *, const_basic_block);
extern struct loop * find_common_loop (struct loop *, struct loop *);
struct loop *superloop_at_depth (struct loop *, unsigned);
struct eni_weights_d;
extern unsigned tree_num_loop_insns (struct loop *, struct eni_weights_d *);
extern int num_loop_insns (const struct loop *);
extern int average_num_loop_insns (const struct loop *);
extern unsigned get_loop_level (const struct loop *);
extern bool loop_exit_edge_p (const struct loop *, const_edge);
extern bool loop_exits_to_bb_p (struct loop *, basic_block);
extern bool loop_exits_from_bb_p (struct loop *, basic_block);
extern void mark_loop_exit_edges (void);

/* Loops & cfg manipulation.  */
extern basic_block *get_loop_body (const struct loop *);
extern unsigned get_loop_body_with_size (const struct loop *, basic_block *,
					 unsigned);
extern basic_block *get_loop_body_in_dom_order (const struct loop *);
extern basic_block *get_loop_body_in_bfs_order (const struct loop *);
extern basic_block *get_loop_body_in_custom_order (const struct loop *,
			       int (*) (const void *, const void *));

extern VEC (edge, heap) *get_loop_exit_edges (const struct loop *);
edge single_exit (const struct loop *);
extern unsigned num_loop_branches (const struct loop *);

extern edge loop_preheader_edge (const struct loop *);
extern edge loop_latch_edge (const struct loop *);

extern void add_bb_to_loop (basic_block, struct loop *);
extern void remove_bb_from_loops (basic_block);

extern void cancel_loop_tree (struct loop *);
extern void delete_loop (struct loop *);

enum
{
  CP_SIMPLE_PREHEADERS = 1,
  CP_FALLTHRU_PREHEADERS = 2
};

basic_block create_preheader (struct loop *, int);
extern void create_preheaders (int);
extern void force_single_succ_latches (void);

extern void verify_loop_structure (void);

/* Loop analysis.  */
extern bool just_once_each_iteration_p (const struct loop *, const_basic_block);
gcov_type expected_loop_iterations_unbounded (const struct loop *);
extern unsigned expected_loop_iterations (const struct loop *);
extern rtx doloop_condition_get (rtx);

void estimate_numbers_of_iterations_loop (struct loop *, bool);
HOST_WIDE_INT estimated_loop_iterations_int (struct loop *, bool);
bool estimated_loop_iterations (struct loop *, bool, double_int *);

/* Loop manipulation.  */
extern bool can_duplicate_loop_p (const struct loop *loop);

#define DLTHE_FLAG_UPDATE_FREQ	1	/* Update frequencies in
					   duplicate_loop_to_header_edge.  */
#define DLTHE_RECORD_COPY_NUMBER 2	/* Record copy number in the aux
					   field of newly create BB.  */
#define DLTHE_FLAG_COMPLETTE_PEEL 4	/* Update frequencies expecting
					   a complete peeling.  */

extern edge create_empty_if_region_on_edge (edge, tree);
extern struct loop *create_empty_loop_on_edge (edge, tree, tree, tree, tree,
					       tree *, tree *, struct loop *);
extern struct loop * duplicate_loop (struct loop *, struct loop *);
extern void duplicate_subloops (struct loop *, struct loop *);
extern bool duplicate_loop_to_header_edge (struct loop *, edge,
					   unsigned, sbitmap, edge,
 					   VEC (edge, heap) **, int);
extern struct loop *loopify (edge, edge,
			     basic_block, edge, edge, bool,
			     unsigned, unsigned);
struct loop * loop_version (struct loop *, void *,
			    basic_block *, unsigned, unsigned, unsigned, bool);
extern bool remove_path (edge);
void scale_loop_frequencies (struct loop *, int, int);

/* Induction variable analysis.  */

/* The description of induction variable.  The things are a bit complicated
   due to need to handle subregs and extends.  The value of the object described
   by it can be obtained as follows (all computations are done in extend_mode):

   Value in i-th iteration is
     delta + mult * extend_{extend_mode} (subreg_{mode} (base + i * step)).

   If first_special is true, the value in the first iteration is
     delta + mult * base

   If extend = UNKNOWN, first_special must be false, delta 0, mult 1 and value is
     subreg_{mode} (base + i * step)

   The get_iv_value function can be used to obtain these expressions.

   ??? Add a third mode field that would specify the mode in that inner
   computation is done, which would enable it to be different from the
   outer one?  */

struct rtx_iv
{
  /* Its base and step (mode of base and step is supposed to be extend_mode,
     see the description above).  */
  rtx base, step;

  /* The type of extend applied to it (SIGN_EXTEND, ZERO_EXTEND or UNKNOWN).  */
  enum rtx_code extend;

  /* Operations applied in the extended mode.  */
  rtx delta, mult;

  /* The mode it is extended to.  */
  enum machine_mode extend_mode;

  /* The mode the variable iterates in.  */
  enum machine_mode mode;

  /* Whether the first iteration needs to be handled specially.  */
  unsigned first_special : 1;
};

/* The description of an exit from the loop and of the number of iterations
   till we take the exit.  */

struct niter_desc
{
  /* The edge out of the loop.  */
  edge out_edge;

  /* The other edge leading from the condition.  */
  edge in_edge;

  /* True if we are able to say anything about number of iterations of the
     loop.  */
  bool simple_p;

  /* True if the loop iterates the constant number of times.  */
  bool const_iter;

  /* Number of iterations if constant.  */
  unsigned HOST_WIDEST_INT niter;

  /* Upper bound on the number of iterations.  */
  unsigned HOST_WIDEST_INT niter_max;

  /* Assumptions under that the rest of the information is valid.  */
  rtx assumptions;

  /* Assumptions under that the loop ends before reaching the latch,
     even if value of niter_expr says otherwise.  */
  rtx noloop_assumptions;

  /* Condition under that the loop is infinite.  */
  rtx infinite;

  /* Whether the comparison is signed.  */
  bool signed_p;

  /* The mode in that niter_expr should be computed.  */
  enum machine_mode mode;

  /* The number of iterations of the loop.  */
  rtx niter_expr;
};

extern void iv_analysis_loop_init (struct loop *);
extern bool iv_analyze (rtx, rtx, struct rtx_iv *);
extern bool iv_analyze_result (rtx, rtx, struct rtx_iv *);
extern bool iv_analyze_expr (rtx, rtx, enum machine_mode, struct rtx_iv *);
extern rtx get_iv_value (struct rtx_iv *, rtx);
extern bool biv_p (rtx, rtx);
extern void find_simple_exit (struct loop *, struct niter_desc *);
extern void iv_analysis_done (void);

extern struct niter_desc *get_simple_loop_desc (struct loop *loop);
extern void free_simple_loop_desc (struct loop *loop);

static inline struct niter_desc *
simple_loop_desc (struct loop *loop)
{
  return (struct niter_desc *) loop->aux;
}

/* Accessors for the loop structures.  */

/* Returns the loop with index NUM from current_loops.  */

static inline struct loop *
get_loop (unsigned num)
{
  return VEC_index (loop_p, current_loops->larray, num);
}

/* Returns the number of superloops of LOOP.  */

static inline unsigned
loop_depth (const struct loop *loop)
{
  return VEC_length (loop_p, loop->superloops);
}

/* Returns the immediate superloop of LOOP, or NULL if LOOP is the outermost
   loop.  */

static inline struct loop *
loop_outer (const struct loop *loop)
{
  unsigned n = VEC_length (loop_p, loop->superloops);

  if (n == 0)
    return NULL;

  return VEC_index (loop_p, loop->superloops, n - 1);
}

/* Returns the list of loops in current_loops.  */

static inline VEC (loop_p, gc) *
get_loops (void)
{
  if (!current_loops)
    return NULL;

  return current_loops->larray;
}

/* Returns the number of loops in current_loops (including the removed
   ones and the fake loop that forms the root of the loop tree).  */

static inline unsigned
number_of_loops (void)
{
  if (!current_loops)
    return 0;

  return VEC_length (loop_p, current_loops->larray);
}

/* Returns true if state of the loops satisfies all properties
   described by FLAGS.  */

static inline bool
loops_state_satisfies_p (unsigned flags)
{
  return (current_loops->state & flags) == flags;
}

/* Sets FLAGS to the loops state.  */

static inline void
loops_state_set (unsigned flags)
{
  current_loops->state |= flags;
}

/* Clears FLAGS from the loops state.  */

static inline void
loops_state_clear (unsigned flags)
{
  if (!current_loops)
    return;
  current_loops->state &= ~flags;
}

/* Loop iterators.  */

/* Flags for loop iteration.  */

enum li_flags
{
  LI_INCLUDE_ROOT = 1,		/* Include the fake root of the loop tree.  */
  LI_FROM_INNERMOST = 2,	/* Iterate over the loops in the reverse order,
				   starting from innermost ones.  */
  LI_ONLY_INNERMOST = 4		/* Iterate only over innermost loops.  */
};

/* The iterator for loops.  */

typedef struct
{
  /* The list of loops to visit.  */
  VEC(int,heap) *to_visit;

  /* The index of the actual loop.  */
  unsigned idx;
} loop_iterator;

static inline void
fel_next (loop_iterator *li, loop_p *loop)
{
  int anum;

  while (VEC_iterate (int, li->to_visit, li->idx, anum))
    {
      li->idx++;
      *loop = get_loop (anum);
      if (*loop)
	return;
    }

  VEC_free (int, heap, li->to_visit);
  *loop = NULL;
}

static inline void
fel_init (loop_iterator *li, loop_p *loop, unsigned flags)
{
  struct loop *aloop;
  unsigned i;
  int mn;

  li->idx = 0;
  if (!current_loops)
    {
      li->to_visit = NULL;
      *loop = NULL;
      return;
    }

  li->to_visit = VEC_alloc (int, heap, number_of_loops ());
  mn = (flags & LI_INCLUDE_ROOT) ? 0 : 1;

  if (flags & LI_ONLY_INNERMOST)
    {
      for (i = 0; VEC_iterate (loop_p, current_loops->larray, i, aloop); i++)
	if (aloop != NULL
	    && aloop->inner == NULL
	    && aloop->num >= mn)
	  VEC_quick_push (int, li->to_visit, aloop->num);
    }
  else if (flags & LI_FROM_INNERMOST)
    {
      /* Push the loops to LI->TO_VISIT in postorder.  */
      for (aloop = current_loops->tree_root;
	   aloop->inner != NULL;
	   aloop = aloop->inner)
	continue;

      while (1)
	{
	  if (aloop->num >= mn)
	    VEC_quick_push (int, li->to_visit, aloop->num);

	  if (aloop->next)
	    {
	      for (aloop = aloop->next;
		   aloop->inner != NULL;
		   aloop = aloop->inner)
		continue;
	    }
	  else if (!loop_outer (aloop))
	    break;
	  else
	    aloop = loop_outer (aloop);
	}
    }
  else
    {
      /* Push the loops to LI->TO_VISIT in preorder.  */
      aloop = current_loops->tree_root;
      while (1)
	{
	  if (aloop->num >= mn)
	    VEC_quick_push (int, li->to_visit, aloop->num);

	  if (aloop->inner != NULL)
	    aloop = aloop->inner;
	  else
	    {
	      while (aloop != NULL && aloop->next == NULL)
		aloop = loop_outer (aloop);
	      if (aloop == NULL)
		break;
	      aloop = aloop->next;
	    }
	}
    }

  fel_next (li, loop);
}

#define FOR_EACH_LOOP(LI, LOOP, FLAGS) \
  for (fel_init (&(LI), &(LOOP), FLAGS); \
       (LOOP); \
       fel_next (&(LI), &(LOOP)))

#define FOR_EACH_LOOP_BREAK(LI) \
  { \
    VEC_free (int, heap, (LI)->to_visit); \
    break; \
  }

/* The properties of the target.  */
struct target_cfgloop {
  /* Number of available registers.  */
  unsigned x_target_avail_regs;

  /* Number of available registers that are call-clobbered.  */
  unsigned x_target_clobbered_regs;

  /* Number of registers reserved for temporary expressions.  */
  unsigned x_target_res_regs;

  /* The cost for register when there still is some reserve, but we are
     approaching the number of available registers.  */
  unsigned x_target_reg_cost[2];

  /* The cost for register when we need to spill.  */
  unsigned x_target_spill_cost[2];
};

extern struct target_cfgloop default_target_cfgloop;
#if SWITCHABLE_TARGET
extern struct target_cfgloop *this_target_cfgloop;
#else
#define this_target_cfgloop (&default_target_cfgloop)
#endif

#define target_avail_regs \
  (this_target_cfgloop->x_target_avail_regs)
#define target_clobbered_regs \
  (this_target_cfgloop->x_target_clobbered_regs)
#define target_res_regs \
  (this_target_cfgloop->x_target_res_regs)
#define target_reg_cost \
  (this_target_cfgloop->x_target_reg_cost)
#define target_spill_cost \
  (this_target_cfgloop->x_target_spill_cost)

/* Register pressure estimation for induction variable optimizations & loop
   invariant motion.  */
extern unsigned estimate_reg_pressure_cost (unsigned, unsigned, bool, bool);
extern void init_set_costs (void);

/* Loop optimizer initialization.  */
extern void loop_optimizer_init (unsigned);
extern void loop_optimizer_finalize (void);

/* Optimization passes.  */
extern void unswitch_loops (void);

enum
{
  UAP_PEEL = 1,		/* Enables loop peeling.  */
  UAP_UNROLL = 2,	/* Enables unrolling of loops if it seems profitable.  */
  UAP_UNROLL_ALL = 4	/* Enables unrolling of all loops.  */
};

extern void unroll_and_peel_loops (int);
extern void doloop_optimize_loops (void);
extern void move_loop_invariants (void);
extern bool finite_loop_p (struct loop *);

#endif /* GCC_CFGLOOP_H */


text:
"use strict"
angular.
  module('plantDetail').
  component('plantDetail', {
    templateUrl: 'plant-detail/plant-detail.template.1.html',
    controller: ['$routeParams', 'PlantListAPI','ngDialog',
      function PlantDetailController($routeParams, PlantListAPI , ngDialog) {
        var self = this;
        self.openModal = openModal;
        self.openTab = 'genel';
        self.getPlant = PlantListAPI.get({plantId: $routeParams.plantId}, function(getPlant) {
          // self.setImage(getPlant.data.images[0]);
          self.plant = getPlant.data;
          console.log(getPlant);
        });

        self.setImage = function setImage(imageUrl) {
          self.mainImageUrl = imageUrl;
        };

        function openModal()  {
           ngDialog.open({
             template: '../plant-detail/plant-detail-modal.html',
             className: 'ngdialog-theme-default',
             data: self,
             });
        }

      }
    ]
  });