text:
DiagnosticsDialog::DiagnosticsDialog(QWidget *parent, ResearcherModel* researcher_model) :
    QDialog(parent),
    ui(new Ui::DiagnosticsDialog),
    m_researcher_model(researcher_model)
{
    ui->setupUi(this);
}

DiagnosticsDialog::~DiagnosticsDialog()
{
    delete ui;
}

void DiagnosticsDialog::SetResearcherModel(ResearcherModel *researcherModel)
{
    m_researcher_model = researcherModel;
}

void DiagnosticsDialog::SetResultLabel(QLabel *label, DiagnosticTestStatus test_status,
                                       DiagnosticResult test_result, QString override_text)
{
    switch (test_status)
    {
    case DiagnosticTestStatus::unknown:
        label->setText(tr(""));
        label->setStyleSheet("");
        break;
    case DiagnosticTestStatus::pending:
        label->setText(tr("Testing..."));
        label->setStyleSheet("");
        break;
    case DiagnosticTestStatus::completed:
        switch (test_result)
        {
        case DiagnosticResult::NA:
            label->setText(tr("N/A"));
            label->setStyleSheet("color:black;background-color:grey");
            break;
        case DiagnosticResult::passed:
            label->setText(tr("Passed"));
            label->setStyleSheet("color:white;background-color:green");
            break;
        case DiagnosticResult::warning:
            label->setText(tr("Warning"));
            label->setStyleSheet("color:black;background-color:yellow");
            break;
        case DiagnosticResult::failed:
            label->setText(tr("Failed"));
            label->setStyleSheet("color:white;background-color:red");
        }
    }

    if (override_text.size()) label->setText(override_text);
}

unsigned int DiagnosticsDialog::GetNumberOfTestsPending()
{
    LOCK(cs_diagnostictests);

    unsigned int pending_count = 0;

    for (const auto& entry : test_status_map)
    {
        if (entry.second == pending) pending_count++;
    }

    return pending_count;
}

DiagnosticsDialog::DiagnosticTestStatus DiagnosticsDialog::GetTestStatus(std::string test_name)
{
    LOCK(cs_diagnostictests);

    auto entry = test_status_map.find(test_name);

    if (entry != test_status_map.end())
    {
        return entry->second;
    }
    else
    {
        return unknown;
    }
}

unsigned int DiagnosticsDialog::UpdateTestStatus(std::string test_name, QLabel *label,
                                                 DiagnosticTestStatus test_status, DiagnosticResult test_result,
                                                 QString override_text)
{
    LOCK(cs_diagnostictests);

    test_status_map[test_name] = test_status;

    SetResultLabel(label, test_status, test_result, override_text);

    UpdateOverallDiagnosticResult(test_result);

    return test_status_map.size();
}

void DiagnosticsDialog::ResetOverallDiagnosticResult(unsigned int& number_of_tests_in)
{
    LOCK(cs_diagnostictests);

    number_of_tests = number_of_tests_in;

    test_status_map.clear();

    diagnostic_result_status = pending;

    diagnostic_result = NA;
}

void DiagnosticsDialog::UpdateOverallDiagnosticResult(DiagnosticResult diagnostic_result_in)
{
    LOCK(cs_diagnostictests);

    // Set diagnostic_result_status to completed. This is under lock, so no one can snoop.
    diagnostic_result_status = completed;

    // If the total number of registered tests is less than the initialized number, then
    // the overall status is pending by default.
    if (test_status_map.size() < number_of_tests)
    {
        diagnostic_result_status = pending;
    }

    diagnostic_result = (DiagnosticResult) std::max<int>(diagnostic_result_in,  diagnostic_result);

    // If diagnostic_result_status is still set to completed, then at least all tests
    // are registered. Walk through the map of tests one by one and check the status.
    // The first one encountered that is pending means the overall status is pending.
    if (diagnostic_result_status == completed)
    {
        for (const auto& entry : test_status_map)
        {
            if (entry.second == pending)
            {
                diagnostic_result_status = pending;
                break;
            }
        }
    }
}

// Lock should be taken on cs_diagnostictests before calling this function.
DiagnosticsDialog::DiagnosticResult DiagnosticsDialog::GetOverallDiagnosticResult()
{
    return diagnostic_result;
}

// Lock should be taken on cs_diagnostictests before calling this function.
DiagnosticsDialog::DiagnosticTestStatus DiagnosticsDialog::GetOverallDiagnosticStatus()
{
    return diagnostic_result_status;
}

void DiagnosticsDialog::DisplayOverallDiagnosticResult()
{
    LOCK(cs_diagnostictests);

    SetResultLabel(ui->overallResultResultLabel, GetOverallDiagnosticStatus(), GetOverallDiagnosticResult());

    this->repaint();
}

bool DiagnosticsDialog::VerifyBoincPath()
{
    fs::path boincPath = (fs::path) GRC::GetBoincDataDir();

    if (boincPath.empty())
        boincPath = (fs::path) GetArgument("boincdatadir", "");

    boincPath = boincPath / "client_state.xml";

    return fs::exists(boincPath);
}

bool DiagnosticsDialog::VerifyIsCPIDValid()
{
    return m_researcher_model->hasEligibleProjects();
}

bool DiagnosticsDialog::VerifyCPIDIsEligible()
{
    return m_researcher_model->hasActiveBeacon();
}

bool DiagnosticsDialog::VerifyWalletIsSynced()
{
    return !OutOfSyncByAge();
}

bool DiagnosticsDialog::VerifyCPIDHasRAC()
{
    return m_researcher_model->hasRAC();
}

double DiagnosticsDialog::VerifyETTSReasonable()
{
    // We are going to compute the ETTS with ignore_staking_status set to true
    // and also use a 960 block diff as the input, which smooths out short
    // term fluctuations. The standard 1-1/e confidence (mean) is used.

    double diff = GRC::GetAverageDifficulty(960);

    double result = GRC::GetEstimatedTimetoStake(true, diff);

    return result;
}

int DiagnosticsDialog::VerifyCountSeedNodes()
{
    LOCK(cs_vNodes);

    int count = 0;

    for (auto const& vnodes : vNodes)
        if (!vnodes->fInbound)
            count++;

    return count;
}

int DiagnosticsDialog::VerifyCountConnections()
{
    LOCK(cs_vNodes);

    return (int)vNodes.size();
}

void DiagnosticsDialog::on_testButton_clicked()
{
    // Check to see if there is already a test run in progress, and if so return.
    // We do not want overlapping test runs.

    if (GetNumberOfTestsPending())
    {
        LogPrintf("INFO: DiagnosticsDialog::on_testButton_clicked: Tests still in progress from a prior run: %u", GetNumberOfTestsPending());
        this->repaint();
        return;
    }

    // This needs to be updated if there are more tests added.
    unsigned int number_of_tests = 11;

    ResetOverallDiagnosticResult(number_of_tests);
    DisplayOverallDiagnosticResult();

    // Tests that are N/A if in investor or pool mode.
    if (m_researcher_model->configuredForInvestorMode() || m_researcher_model->detectedPoolMode())
    {
        // N/A tests for investor/pool mode
        UpdateTestStatus("boincPath", ui->boincPathResultLabel, completed, NA);
        UpdateTestStatus("verifyCPIDValid", ui->verifyCPIDValidResultLabel, completed, NA);
        UpdateTestStatus("verifyCPIDHasRAC", ui->verifyCPIDHasRACResultLabel, completed, NA);
        UpdateTestStatus("verifyCPIDIsActive", ui->verifyCPIDIsActiveResultLabel, completed, NA);
        UpdateTestStatus("checkETTS", ui->checkETTSResultLabel, completed, NA);
    }
    else
    {
        //BOINC path
        UpdateTestStatus("boincPath", ui->boincPathResultLabel, pending, NA);
        this->repaint();

        if (VerifyBoincPath())
        {
            UpdateTestStatus("boincPath", ui->boincPathResultLabel, completed, passed);
        }
        else
        {
            UpdateTestStatus("boincPath", ui->boincPathResultLabel, completed, failed);
        }

        //CPID valid
        UpdateTestStatus("verifyCPIDValid", ui->verifyCPIDValidResultLabel, pending, NA);
        this->repaint();

        if (VerifyIsCPIDValid())
        {
            UpdateTestStatus("verifyCPIDValid", ui->verifyCPIDValidResultLabel, completed, passed);
        }
        else
        {
            UpdateTestStatus("verifyCPIDValid", ui->verifyCPIDValidResultLabel, completed, failed);
        }

        //CPID has rac
        UpdateTestStatus("verifyCPIDHasRAC", ui->verifyCPIDHasRACResultLabel, pending, NA);
        this->repaint();

        if (VerifyCPIDHasRAC())
        {
            UpdateTestStatus("verifyCPIDHasRAC", ui->verifyCPIDHasRACResultLabel, completed, passed);
        }
        else
        {
            UpdateTestStatus("verifyCPIDHasRAC", ui->verifyCPIDHasRACResultLabel, completed, failed);
        }

        //cpid is active
        UpdateTestStatus("verifyCPIDIsActive", ui->verifyCPIDIsActiveResultLabel, pending, NA);
        this->repaint();

        if (VerifyCPIDIsEligible())
        {
            UpdateTestStatus("verifyCPIDIsActive", ui->verifyCPIDIsActiveResultLabel, completed, passed);
        }
        else
        {
            UpdateTestStatus("verifyCPIDIsActive", ui->verifyCPIDIsActiveResultLabel, completed, failed);
        }

        // verify reasonable ETTS
        // This is only checked if wallet is a researcher wallet because the purpose is to
        // alert the owner that his stake time is too long and therefore there is a chance
        // of research rewards loss between stakes due to the 180 day limit.
        UpdateTestStatus("checkETTS", ui->checkETTSResultLabel, pending, NA);

        double ETTS = VerifyETTSReasonable() / (24.0 * 60.0 * 60.0);

        std::string rounded_ETTS;

        //round appropriately for display.
        if (ETTS >= 100)
        {
            rounded_ETTS = RoundToString(ETTS, 0);
        }
        else if (ETTS >= 10)
        {
            rounded_ETTS = RoundToString(ETTS, 1);
        }
        else
        {
            rounded_ETTS = RoundToString(ETTS, 2);
        }

        // ETTS of zero actually means no coins, i.e. infinite.
        if (ETTS == 0.0)
        {
            UpdateTestStatus("checkETTS", ui->checkETTSResultLabel, completed, failed,
                             tr("Failed: ETTS is infinite. No coins to stake."));
        }
        else if (ETTS > 90.0)
        {
            UpdateTestStatus("checkETTS", ui->checkETTSResultLabel, completed, failed,
                             tr("Failed: ETTS is infinite. No coins to stake."));
        }
        else if (ETTS > 45.0 && ETTS <= 90.0)
        {
            UpdateTestStatus("checkETTS", ui->checkETTSResultLabel, completed, warning,
                             tr("Warning: 45 days < ETTS = %1 <= 90 days").arg(QString(rounded_ETTS.c_str())));
        }
        else
        {
            UpdateTestStatus("checkETTS", ui->checkETTSResultLabel, completed, passed,
                             tr("Passed: ETTS = %1 <= 45 days").arg(QString(rounded_ETTS.c_str())));
        }
    }

    // Tests that are common to both investor and researcher mode.
    // wallet synced
    UpdateTestStatus("verifyWalletIsSynced", ui->verifyWalletIsSyncedResultLabel, pending, NA);
    this->repaint();

    if (VerifyWalletIsSynced())
    {
        UpdateTestStatus("verifyWalletIsSynced", ui->verifyWalletIsSyncedResultLabel, completed, passed);
    }

    else
    {
        UpdateTestStatus("verifyWalletIsSynced", ui->verifyWalletIsSyncedResultLabel, completed, failed);
    }

    // clock
    UpdateTestStatus("verifyClockResult", ui->verifyClockResultLabel, pending, NA);
    this->repaint();

    VerifyClock();

    // seed nodes
    UpdateTestStatus("verifySeedNodes", ui->verifySeedNodesResultLabel, pending, NA);
    this->repaint();

    unsigned int seed_node_connections = VerifyCountSeedNodes();

    if (seed_node_connections >= 1 && seed_node_connections < 3)
    {
        UpdateTestStatus("verifySeedNodes", ui->verifySeedNodesResultLabel, completed, warning,
                         tr("Warning: Count = %1 (Pass = 3+)").arg(QString::number(seed_node_connections)));
    }
    else if(seed_node_connections >= 3)
    {
        UpdateTestStatus("verifySeedNodes", ui->verifySeedNodesResultLabel, completed, passed,
                         tr("Passed: Count = %1").arg(QString::number(seed_node_connections)));
    }
    else
    {
        UpdateTestStatus("verifySeedNodes", ui->verifySeedNodesResultLabel, completed, failed,
                         tr("Failed: Count = %1").arg(QString::number(seed_node_connections)));
    }

    // connection count
    UpdateTestStatus("verifyConnections", ui->verifyConnectionsResultLabel, pending, NA);
    this->repaint();

    unsigned int connections = VerifyCountConnections();

    if (connections <= 7 && connections >= 1)
    {
        UpdateTestStatus("verifyConnections", ui->verifyConnectionsResultLabel, completed, warning,
                         tr("Warning: Count = %1 (Pass = 8+)").arg(QString::number(connections)));
    }
    else if (connections >= 8)
    {
        UpdateTestStatus("verifyConnections", ui->verifyConnectionsResultLabel, completed, passed,
                         tr("Passed: Count = %1").arg(QString::number(connections)));
    }
    else
    {
        UpdateTestStatus("verifyConnections", ui->verifyConnectionsResultLabel, completed, failed,
                         tr("Failed: Count = %1").arg(QString::number(connections)));
    }

    // tcp port
    UpdateTestStatus("verifyTCPPort", ui->verifyTCPPortResultLabel, pending, NA);
    this->repaint();

    VerifyTCPPort();

    // client version
    UpdateTestStatus("checkClientVersion", ui->checkClientVersionResultLabel, pending, NA);

    std::string client_message;

    if (g_UpdateChecker->CheckForLatestUpdate(false, client_message))
    {
        UpdateTestStatus("checkClientVersion", ui->checkClientVersionResultLabel, completed, warning,
                         tr("Warning: New Client version available:\n %1").arg(QString(client_message.c_str())));
    }
    else
    {
        UpdateTestStatus("checkClientVersion", ui->checkClientVersionResultLabel, completed, passed);
    }

    DisplayOverallDiagnosticResult();
}

void DiagnosticsDialog::VerifyClock()
{
    QTimer *timerVerifyClock = new QTimer();

    // Set up a timeout clock of 10 seconds as a fail-safe.
    connect(timerVerifyClock, SIGNAL(timeout()), this, SLOT(clkFinished()));
    timerVerifyClock->start(10 * 1000);

    QHostInfo NTPHost = QHostInfo::fromName("pool.ntp.org");
    udpSocket = new QUdpSocket(this);

    connect(udpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(clkStateChanged(QAbstractSocket::SocketState)));
    connect(udpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(clkSocketError()));

    udpSocket->connectToHost(QHostAddress(NTPHost.addresses().first()), 123, QIODevice::ReadWrite);
}

void DiagnosticsDialog::clkStateChanged(QAbstractSocket::SocketState state)
{
    if (state == QAbstractSocket::ConnectedState)
    {
        connect(udpSocket, SIGNAL(readyRead()), this, SLOT(clkFinished()));

        char NTPMessage[48] = {0x1b, 0, 0, 0 ,0, 0, 0, 0, 0};

        udpSocket->write(NTPMessage, sizeof(NTPMessage));
    }

    return;
}

void DiagnosticsDialog::clkSocketError()
{
    udpSocket->close();

    // Call clkFinished to handle.
    clkFinished();

    return;
}

void DiagnosticsDialog::clkFinished()
{
    if (udpSocket->waitForReadyRead(10 * 1000))
    {
        int64_t start_time = GetAdjustedTime();

        // Only allow this loop to run for 5 seconds maximum.
        while (udpSocket->hasPendingDatagrams() && GetAdjustedTime() - start_time <= 5)
        {
            QByteArray BufferSocket = udpSocket->readAll();

            if (BufferSocket.size() == 48)
            {
                int nNTPCount = 40;
                unsigned long DateTimeIn = uchar(BufferSocket.at(nNTPCount))
                        + (uchar(BufferSocket.at(nNTPCount + 1)) << 8)
                        + (uchar(BufferSocket.at(nNTPCount + 2)) << 16)
                        + (uchar(BufferSocket.at(nNTPCount + 3)) << 24);
                long tmit = ntohl((time_t)DateTimeIn);
                tmit -= 2208988800U;

                udpSocket->close();

                boost::posix_time::ptime localTime = boost::posix_time::microsec_clock::universal_time();
                boost::posix_time::ptime networkTime = boost::posix_time::from_time_t(tmit);
                boost::posix_time::time_duration timeDiff = networkTime - localTime;

                if (timeDiff.minutes() < 3)
                {
                    UpdateTestStatus("verifyClockResult", ui->verifyClockResultLabel, completed, passed);
                }
                else
                {
                    UpdateTestStatus("verifyClockResult", ui->verifyClockResultLabel, completed, failed);
                }

                DisplayOverallDiagnosticResult();

                return;
            }
        }
    }
    else // The other state here is a socket or other indeterminate error such as a timeout (coming from clkSocketError).
    {
        // This is needed to "cancel" the timeout timer. Essentially if the test was marked completed via the normal exits
        // above, then when the timer calls clkFinished again, it will hit this conditional and be a no-op.
        if (GetTestStatus("verifyClockResult") != completed)
        {
            UpdateTestStatus("verifyClockResult", ui->verifyClockResultLabel,completed, warning,
                             tr("Warning: Cannot connect to NTP server"));

            DisplayOverallDiagnosticResult();
        }

        return;
    }
}

void DiagnosticsDialog::VerifyTCPPort()
{
    tcpSocket = new QTcpSocket(this);

    connect(tcpSocket, SIGNAL(connected()), this, SLOT(TCPFinished()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(TCPFailed(QAbstractSocket::SocketError)));

    tcpSocket->connectToHost("portquiz.net", GetListenPort());
}

void DiagnosticsDialog::TCPFinished()
{
    tcpSocket->close();
    UpdateTestStatus("verifyTCPPort", ui->verifyTCPPortResultLabel, completed, passed);

    DisplayOverallDiagnosticResult();

    return;
}

void DiagnosticsDialog::TCPFailed(QAbstractSocket::SocketError socket)
{
    UpdateTestStatus("verifyTCPPort", ui->verifyTCPPortResultLabel, completed, warning,
                     tr("Warning: Port 32749 may be blocked by your firewall"));

    DisplayOverallDiagnosticResult();

    return;
}


text:
<?php
session_start();
if (isset($_SESSION['login_user'])) {
?>
<!DOCTYPE html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>Cetak Invoice - Artha Laras</title>
  <!-- Bootstrap Core CSS -->
  <link href="../dist/css/sb-admin-2.css" rel="stylesheet">
  <link href="../dist/css/bootstrap-toggle.min.css" rel="stylesheet">
  <link href="../dist/css/github.min.css" rel="stylesheet">
  <link href="../vendor/bootstrap/css/bootstrap.css" rel="stylesheet">
  <link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
  <link href="../vendor/morrisjs/morris.css" rel="stylesheet">
  <link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link href="../vendor/datatables-plugins/dataTables.bootstrap.css" rel="stylesheet">
  <link href="../vendor/datatables-responsive/dataTables.responsive.css" rel="stylesheet">
  <link href="../vendor/bootstrap-toggle/doc/stylesheet.css" rel="stylesheet">

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
  <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
  <![endif]-->
</head>
<body>

  <div id="wrapper">

    <?php include 'header.php'; ?>

    <?php include 'nav.php'; ?>

    <?php include '../view/cetakinvoice.php'; ?>

  </div>
  <!-- /#wrapper -->

  <script src="../vendor/jquery/jquery.min.js"></script>
  <script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
  <script src="../vendor/metisMenu/metisMenu.min.js"></script>
  <script src="../vendor/raphael/raphael.min.js"></script>
  <script src="../vendor/morrisjs/morris.min.js"></script>
  <script src="../vendor/bootstrap-toggle/doc/script.js"></script>
  <script src="../dist/js/morris-data.js"></script>
  <script src="../dist/js/bootstrap-toggle.min.js"></script>
  <script src="../dist/js/highlight.min.js"></script>

  <!-- Custom Theme JavaScript -->
  <script src="../dist/js/sb-admin-2.js"></script>

  <!-- DataTables JavaScript -->
  <script src="../vendor/datatables/js/jquery.dataTables.min.js"></script>
  <script src="../vendor/datatables-plugins/dataTables.bootstrap.min.js"></script>
  <script src="../vendor/datatables-responsive/dataTables.responsive.js"></script>

  <script>
  $(document).ready(function() {
    $('#dataTables-example').DataTable({
      responsive: true
    });
  });

  $(document).ready(function() {
    $('#dataTablesPenyewa').DataTable({
      responsive: true
    });
  });

  //hitung harga sewa, supir, dan lama sewa
  $(document).ready(function(){
     $("#lama_sewa").keyup(function(){
       var harga      = parseInt($("#harga").val());
       var jasa_supir = parseInt($("#jasa_supir").val());
       var lama_sewa  = parseInt($("#lama_sewa").val());
       var total      = (harga+jasa_supir)*lama_sewa;
       $("#total_harga").val(total);
     });
   });

  </script>

</body>
</html>
<?php
} else {
  header("location: ../pages/login.php");
}
?>

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package com.intellij.tasks.context;

import com.intellij.ide.projectView.impl.AbstractProjectViewPane;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.util.ui.tree.TreeUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * @author Dmitry Avdeev
 */
public class ProjectViewContextProvider extends WorkingContextProvider {

  private final AbstractProjectViewPane[] myPanes;

  public ProjectViewContextProvider(Project project) {
    myPanes = AbstractProjectViewPane.EP_NAME.getExtensions(project);
  }

  @NotNull
  @Override
  public String getId() {
    return "projectView";
  }

  @NotNull
  @Override
  public String getDescription() {
    return "Project view state";
  }

  @Override
  public void saveContext(Element toElement) throws WriteExternalException {
    for (AbstractProjectViewPane pane : myPanes) {
      Element paneElement = new Element(pane.getId());
      pane.writeExternal(paneElement);
      toElement.addContent(paneElement);
    }
  }

  @Override
  public void loadContext(Element fromElement) throws InvalidDataException {
    for (AbstractProjectViewPane pane : myPanes) {
      Element paneElement = fromElement.getChild(pane.getId());
      if (paneElement != null) {
        pane.readExternal(paneElement);
        if (pane.getTree() != null) {
          pane.restoreExpandedPaths();
        }
      }
    }
  }

  @Override
  public void clearContext() {
    for (AbstractProjectViewPane pane : myPanes) {
      JTree tree = pane.getTree();
      if (tree != null) {
        TreeUtil.collapseAll(tree, 0);
      }
    }
  }
}


text:
package net.minder.config;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class MapMethodSampleTest {

  public static class Target {
    private int limit = 3;

    @Configure
    public void setRetryLimit( int value ) {
      limit = value;
    }
  }

  static Map<String,String> config = new HashMap<String,String>();
  static { config.put( "retryLimit", "5" ); }

  @Test
  public void sample() {
    Target target = new Target();
    ConfigurationInjectorBuilder.configuration().target( target ).source( config ).inject();
    assertThat( target.limit, is( 5 ) );
  }

}


text:
id: Float
section: utilities
---

import './Float.css'

## Examples
### Basic
```hbs
{{#> float float--type="left"}}
  Float left
{{/float}}
{{#> float float--type="right"}}
  Float right
{{/float}}
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Earum, odit fugit eaque ad assumenda fuga alias aut ipsum repudiandae enim pariatur ullam distinctio omnis dolorem at voluptatum saepe, beatae officiis?
</p>
```

## Documentation
### Overview
[Breakpoint](/developer-resources/global-css-variables#breakpoint-variables-and-class-suffixes) is optional. Breakpoints: base (no breakpoint value), `-on-sm`, `-on-md`, `-on-lg`, and `-on-xl`. **Example .pf-u-text-left-on-lg**

### Usage
| Class | Applied to | Outcome |
| -- | -- | -- |
| `.pf-u-float-left{-on-[breakpoint]}` | `*` |  Float element left |
| `.pf-u-float-right{-on-[breakpoint]}` | `*` |  Float element right |


text:
/**
 * The representation of incoming requests from the Slack Platform.
 */
package com.slack.api.bolt.request;


text:
<?php

/**
 * @category   Zend
 * @package    Zend_Tool
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Tool_Project_Provider_Application
    extends Zend_Tool_Project_Provider_Abstract
    implements Zend_Tool_Framework_Provider_Pretendable
{

    protected $_specialties = array('ClassNamePrefix');

    /**
     *
     * @param $classNamePrefix Prefix of classes
     * @param $force
     */
    public function changeClassNamePrefix($classNamePrefix /* , $force = false */)
    {
        $profile = $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION);

        $originalClassNamePrefix = $classNamePrefix;

        if (substr($classNamePrefix, -1) != '_') {
            $classNamePrefix .= '_';
        }

        $configFileResource = $profile->search('ApplicationConfigFile');
        $zc = $configFileResource->getAsZendConfig('production');
        if ($zc->appnamespace == $classNamePrefix) {
            throw new Zend_Tool_Project_Exception('The requested name ' . $classNamePrefix . ' is already the prefix.');
        }

        // remove the old
        $configFileResource->removeStringItem('appnamespace', 'production');
        $configFileResource->create();

        // add the new
        $configFileResource->addStringItem('appnamespace', $classNamePrefix, 'production', true);
        $configFileResource->create();

        // update the project profile
        $applicationDirectory = $profile->search('ApplicationDirectory');
        $applicationDirectory->setClassNamePrefix($classNamePrefix);

        $response = $this->_registry->getResponse();

        if ($originalClassNamePrefix !== $classNamePrefix) {
            $response->appendContent(
                'Note: the name provided "' . $originalClassNamePrefix . '" was'
                    . ' altered to "' . $classNamePrefix . '" for correctness.',
                array('color' => 'yellow')
                );
        }

        // note to the user
        $response->appendContent('Note: All existing models will need to be altered to this new namespace by hand', array('color' => 'yellow'));
        $response->appendContent('application.ini updated with new appnamespace ' . $classNamePrefix);

        // store profile
        $this->_storeProfile();
    }

}


text:
package org.eclipse.php.internal.core.typeinference.goals;

import org.eclipse.dltk.core.IType;
import org.eclipse.dltk.ti.IContext;
import org.eclipse.dltk.ti.types.IEvaluatedType;

public class MethodElementReturnTypeGoal extends AbstractMethodReturnTypeGoal {

	public MethodElementReturnTypeGoal(IContext context, IEvaluatedType evaluatedType, String methodName,
			String[] argNames, int offset) {
		super(context, evaluatedType, methodName, argNames, offset);
	}

	public MethodElementReturnTypeGoal(IContext context, IType[] types, String methodName, String[] argNames,
			int offset) {
		super(context, types, methodName, argNames, offset);
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof MethodElementReturnTypeGoal)) {
			return false;
		}
		return this == obj;
	}
}


text:
namespace supersonic {

namespace {

using testing::HasSubstr;
using testing::InvokeWithoutArgs;
using testing::NiceMock;
using testing::Return;
using testing::ReturnRef;
using testing::_;

class MockBenchmarkNode : public BenchmarkTreeNode {
 public:
  explicit MockBenchmarkNode(CursorStatistics* cursor_statistics)
      : BenchmarkTreeNode(cursor_statistics) {}

  MOCK_METHOD0(GatherAllData, void());
};

class BenchmarkManagerTest : public testing::Test {
 protected:
  // Caller takes ownership of the Cursor.
  MockCursor* CreateMockCursor() {
    // Using NiceMock for cursor as BenchmarkManager only acts on the cursor
    // through the tree builder.
    std::unique_ptr<MockCursor> cursor(new NiceMock<MockCursor>);
    ON_CALL(*cursor, schema()).WillByDefault(ReturnRef(schema_));
    ON_CALL(*cursor, GetCursorId()).WillByDefault(Return(VIEW));
    return cursor.release();
  }

  // Caller takes ownership of the result node.
  BenchmarkTreeNode* CreateMockNodeWithExpectation() {
    std::unique_ptr<CursorStatistics> stats(new MockCursorStatistics(&dummy_));
    std::unique_ptr<MockBenchmarkNode> node(
        new MockBenchmarkNode(stats.release()));
    EXPECT_CALL(*node, GatherAllData());
    return node.release();
  }

  TupleSchema schema_;
  CursorWithBenchmarkListener dummy_;
};

TEST_F(BenchmarkManagerTest, TypicalUseCaseTest) {
  rowcount_t block_size = -1;
  std::unique_ptr<MockCursor> cursor(CreateMockCursor());

  // Return EOS on next call, hence there should only be one call to Next()
  // with the argument being the specified block size.
  ON_CALL(*cursor, Next(_)).WillByDefault(
      InvokeWithoutArgs(&ResultView::EOS));
  EXPECT_CALL(*cursor, Next(_)).Times(0);
  EXPECT_CALL(*cursor, Next(block_size));
  GraphVisualisationOptions options(DOT_STRING);
  string dot_code = PerformBenchmark("ManagerTest",
                                     cursor.release(),
                                     block_size,
                                     options);
  EXPECT_THAT(dot_code, HasSubstr("ManagerTest"));
}

TEST_F(BenchmarkManagerTest, SetUpTest) {
  std::unique_ptr<Cursor> cursor(CreateMockCursor());
  std::unique_ptr<BenchmarkDataWrapper> data_wrapper(
      SetUpBenchmarkForCursor(cursor.release()));
  std::unique_ptr<Cursor> transformed_cursor(data_wrapper->release_cursor());

  EXPECT_TRUE(transformed_cursor.get() != NULL);
  ASSERT_TRUE(data_wrapper->node() != NULL);

  const BenchmarkData& data =
      data_wrapper->node()->GetStats().GetBenchmarkData();
  EXPECT_EQ("VIEW", data.cursor_name());
  EXPECT_EQ(BenchmarkData::BENCHMARKED, data.cursor_type());
}

class BenchmarkManagerWithOutputTest
    : public BenchmarkManagerTest,
      public testing::WithParamInterface<Destination> {
 protected:
  virtual GraphVisualisationOptions CreateOptions(
      Destination destination) {
    GraphVisualisationOptions options(destination);
    if (destination == DOT_FILE) {
      options.file_name = TempFile::TempFilename(NULL);
    }

    return options;
  }
};

INSTANTIATE_TEST_CASE_P(Destination,
                        BenchmarkManagerWithOutputTest,
                        testing::Values(DOT_STRING, DOT_FILE));

TEST_P(BenchmarkManagerWithOutputTest, CreateStringGraphTest) {
  std::unique_ptr<BenchmarkTreeNode> node(CreateMockNodeWithExpectation());
  CreateGraph("CreateGraphTest",
              node.get(),
              CreateOptions(GetParam()));
}

}  // namespace

}  // namespace supersonic


text:
var common = require("./utils-common");
var color_1 = require("color");
var enums = require("ui/enums");
global.moduleMerge(common, exports);
var trace;
function ensureTrace() {
    if (!trace) {
        trace = require("trace");
    }
}
function isOrientationLandscape(orientation) {
    return orientation === 3 || orientation === 4;
}
var layout;
(function (layout) {
    var MODE_SHIFT = 30;
    var MODE_MASK = 0x3 << MODE_SHIFT;
    function makeMeasureSpec(size, mode) {
        return (Math.round(size) & ~MODE_MASK) | (mode & MODE_MASK);
    }
    layout.makeMeasureSpec = makeMeasureSpec;
    function getDisplayDensity() {
        return 1;
    }
    layout.getDisplayDensity = getDisplayDensity;
    function toDevicePixels(value) {
        return value * getDisplayDensity();
    }
    layout.toDevicePixels = toDevicePixels;
    function toDeviceIndependentPixels(value) {
        return value / getDisplayDensity();
    }
    layout.toDeviceIndependentPixels = toDeviceIndependentPixels;
})(layout = exports.layout || (exports.layout = {}));
var ios;
(function (ios) {
    function setTextAlignment(view, value) {
        switch (value) {
            case enums.TextAlignment.left:
                view.textAlignment = 0;
                break;
            case enums.TextAlignment.center:
                view.textAlignment = 1;
                break;
            case enums.TextAlignment.right:
                view.textAlignment = 2;
                break;
            default:
                break;
        }
    }
    ios.setTextAlignment = setTextAlignment;
    function getter(_this, property) {
        if (typeof property === "function") {
            return property.call(_this);
        }
        else {
            return property;
        }
    }
    ios.getter = getter;
    function getTransformedText(view, source, transform) {
        var result = source;
        switch (transform) {
            case enums.TextTransform.none:
            default:
                result = view.text;
                break;
            case enums.TextTransform.uppercase:
                result = NSStringFromNSAttributedString(source).uppercaseString;
                break;
            case enums.TextTransform.lowercase:
                result = NSStringFromNSAttributedString(source).lowercaseString;
                break;
            case enums.TextTransform.capitalize:
                result = NSStringFromNSAttributedString(source).capitalizedString;
                break;
        }
        return result;
    }
    ios.getTransformedText = getTransformedText;
    function NSStringFromNSAttributedString(source) {
        return NSString.stringWithString(source instanceof NSAttributedString && source.string || source);
    }
    function setWhiteSpace(view, value, parentView) {
        if (value === enums.WhiteSpace.normal) {
            view.lineBreakMode = 0;
            view.numberOfLines = 0;
        }
        else {
            if (parentView) {
                view.lineBreakMode = 5;
            }
            else {
                view.lineBreakMode = 4;
            }
            view.numberOfLines = 1;
        }
    }
    ios.setWhiteSpace = setWhiteSpace;
    var collections;
    (function (collections) {
        function jsArrayToNSArray(str) {
            return NSArray.arrayWithArray(str);
        }
        collections.jsArrayToNSArray = jsArrayToNSArray;
        function nsArrayToJSArray(a) {
            var arr = [];
            if ("undefined" !== typeof a) {
                var count = a.count;
                for (var i = 0; i < count; i++) {
                    arr.push(a.objectAtIndex(i));
                }
            }
            return arr;
        }
        collections.nsArrayToJSArray = nsArrayToJSArray;
    })(collections = ios.collections || (ios.collections = {}));
    function getColor(uiColor) {
        var redRef = new interop.Reference();
        var greenRef = new interop.Reference();
        var blueRef = new interop.Reference();
        var alphaRef = new interop.Reference();
        uiColor.getRedGreenBlueAlpha(redRef, greenRef, blueRef, alphaRef);
        var red = redRef.value * 255;
        var green = greenRef.value * 255;
        var blue = blueRef.value * 255;
        var alpha = alphaRef.value * 255;
        return new color_1.Color(alpha, red, green, blue);
    }
    ios.getColor = getColor;
    function isLandscape() {
        var device = getter(UIDevice, UIDevice.currentDevice);
        var statusBarOrientation = getter(UIApplication, UIApplication.sharedApplication).statusBarOrientation;
        var isStatusBarOrientationLandscape = isOrientationLandscape(statusBarOrientation);
        return isOrientationLandscape(device.orientation) || isStatusBarOrientationLandscape;
    }
    ios.isLandscape = isLandscape;
    ios.MajorVersion = NSString.stringWithString(getter(UIDevice, UIDevice.currentDevice).systemVersion).intValue;
    function openFile(filePath) {
        try {
            var fs = require("file-system");
            var path = filePath.replace("~", fs.knownFolders.currentApp().path);
            var controller = UIDocumentInteractionController.interactionControllerWithURL(NSURL.fileURLWithPath(path));
            controller.delegate = new UIDocumentInteractionControllerDelegateImpl();
            return controller.presentPreviewAnimated(true);
        }
        catch (e) {
            ensureTrace();
            trace.write("Error in openFile", trace.categories.Error, trace.messageType.error);
        }
        return false;
    }
    ios.openFile = openFile;
})(ios = exports.ios || (exports.ios = {}));
function GC() {
    __collect();
}
exports.GC = GC;
function openUrl(location) {
    try {
        var url = NSURL.URLWithString(location.trim());
        if (ios.getter(UIApplication, UIApplication.sharedApplication).canOpenURL(url)) {
            return ios.getter(UIApplication, UIApplication.sharedApplication).openURL(url);
        }
    }
    catch (e) {
        ensureTrace();
        trace.write("Error in OpenURL", trace.categories.Error, trace.messageType.error);
    }
    return false;
}
exports.openUrl = openUrl;
var UIDocumentInteractionControllerDelegateImpl = (function (_super) {
    __extends(UIDocumentInteractionControllerDelegateImpl, _super);
    function UIDocumentInteractionControllerDelegateImpl() {
        _super.apply(this, arguments);
    }
    UIDocumentInteractionControllerDelegateImpl.prototype.getViewController = function () {
        var frame = require("ui/frame");
        return frame.topmost().currentPage.ios;
    };
    UIDocumentInteractionControllerDelegateImpl.prototype.documentInteractionControllerViewControllerForPreview = function (controller) {
        return this.getViewController();
    };
    UIDocumentInteractionControllerDelegateImpl.prototype.documentInteractionControllerViewForPreview = function (controller) {
        return this.getViewController().view;
    };
    UIDocumentInteractionControllerDelegateImpl.prototype.documentInteractionControllerRectForPreview = function (controller) {
        return this.getViewController().view.frame;
    };
    UIDocumentInteractionControllerDelegateImpl.ObjCProtocols = [UIDocumentInteractionControllerDelegate];
    return UIDocumentInteractionControllerDelegateImpl;
}(NSObject));
//# sourceMappingURL=utils.js.map


text:
package cmd

import (
	"errors"
	"fmt"
	"io"
	"sort"
	"strconv"
	"strings"

	"time"

	units "github.com/docker/go-units"
	"github.com/spf13/cobra"

	kapi "k8s.io/kubernetes/pkg/api"
	kerrors "k8s.io/kubernetes/pkg/api/errors"
	kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"

	"github.com/openshift/origin/pkg/client"
	"github.com/openshift/origin/pkg/cmd/cli/describe"
	"github.com/openshift/origin/pkg/cmd/templates"
	"github.com/openshift/origin/pkg/cmd/util/clientcmd"
	deployapi "github.com/openshift/origin/pkg/deploy/api"
	deployutil "github.com/openshift/origin/pkg/deploy/util"
)

// DeployOptions holds all the options for the `deploy` command
type DeployOptions struct {
	out             io.Writer
	osClient        client.Interface
	kubeClient      kclientset.Interface
	builder         *resource.Builder
	namespace       string
	baseCommandName string

	deploymentConfigName string
	deployLatest         bool
	retryDeploy          bool
	cancelDeploy         bool
	enableTriggers       bool
	follow               bool
}

var (
	deployLong = templates.LongDesc(`
		View, start, cancel, or retry a deployment

		This command allows you to control a deployment config. Each individual deployment is exposed
		as a new replication controller, and the deployment process manages scaling down old deployments
		and scaling up new ones. Use '%[1]s rollback' to rollback to any previous deployment.

		There are several deployment strategies defined:

		* Rolling (default) - scales up the new deployment in stages, gradually reducing the number
		  of old deployments. If one of the new deployed pods never becomes "ready", the new deployment
		  will be rolled back (scaled down to zero). Use when your application can tolerate two versions
		  of code running at the same time (many web applications, scalable databases)
		* Recreate - scales the old deployment down to zero, then scales the new deployment up to full.
		  Use when your application cannot tolerate two versions of code running at the same time
		* Custom - run your own deployment process inside a Docker container using your own scripts.

		If a deployment fails, you may opt to retry it (if the error was transient). Some deployments may
		never successfully complete - in which case you can use the '--latest' flag to force a redeployment.
		If a deployment config has completed deploying successfully at least once in the past, it would be
		automatically rolled back in the event of a new failed deployment. Note that you would still need
		to update the erroneous deployment config in order to have its template persisted across your
		application.

		If you want to cancel a running deployment, use '--cancel' but keep in mind that this is a best-effort
		operation and may take some time to complete. It's possible the deployment will partially or totally
		complete before the cancellation is effective. In such a case an appropriate event will be emitted.

		If no options are given, shows information about the latest deployment.`)

	deployExample = templates.Examples(`
		# Display the latest deployment for the 'database' deployment config
	  %[1]s deploy database

	  # Start a new deployment based on the 'database'
	  %[1]s deploy database --latest

	  # Start a new deployment and follow its log
	  %[1]s deploy database --latest --follow

	  # Retry the latest failed deployment based on 'frontend'
	  # The deployer pod and any hook pods are deleted for the latest failed deployment
	  %[1]s deploy frontend --retry

	  # Cancel the in-progress deployment based on 'frontend'
	  %[1]s deploy frontend --cancel`)
)

// NewCmdDeploy creates a new `deploy` command.
func NewCmdDeploy(fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	options := &DeployOptions{
		baseCommandName: fullName,
	}

	cmd := &cobra.Command{
		Use:        "deploy DEPLOYMENTCONFIG [--latest|--retry|--cancel|--enable-triggers]",
		Short:      "View, start, cancel, or retry a deployment",
		Long:       fmt.Sprintf(deployLong, fullName),
		Example:    fmt.Sprintf(deployExample, fullName),
		SuggestFor: []string{"deployment"},
		Run: func(cmd *cobra.Command, args []string) {
			if err := options.Complete(f, args, out); err != nil {
				kcmdutil.CheckErr(err)
			}

			if err := options.Validate(); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
			}

			if err := options.RunDeploy(); err != nil {
				kcmdutil.CheckErr(err)
			}
		},
	}

	cmd.Flags().BoolVar(&options.deployLatest, "latest", false, "If true, start a new deployment now.")
	cmd.Flags().MarkDeprecated("latest", fmt.Sprintf("use '%s rollout latest' instead", fullName))
	cmd.Flags().BoolVar(&options.retryDeploy, "retry", false, "If true, retry the latest failed deployment.")
	cmd.Flags().BoolVar(&options.cancelDeploy, "cancel", false, "If true, cancel the in-progress deployment.")
	cmd.Flags().MarkDeprecated("cancel", fmt.Sprintf("use '%s rollout cancel' instead", fullName))
	cmd.Flags().BoolVar(&options.enableTriggers, "enable-triggers", false, "If true, enables all image triggers for the deployment config.")
	cmd.Flags().MarkDeprecated("enable-triggers", fmt.Sprintf("use '%s set triggers' instead", fullName))
	cmd.Flags().BoolVar(&options.follow, "follow", false, "If true, follow the logs of a deployment")

	return cmd
}

func (o *DeployOptions) Complete(f *clientcmd.Factory, args []string, out io.Writer) error {
	if len(args) > 1 {
		return errors.New("only one deployment config name is supported as argument.")
	}
	var err error

	o.osClient, o.kubeClient, err = f.Clients()
	if err != nil {
		return err
	}
	o.namespace, _, err = f.DefaultNamespace()
	if err != nil {
		return err
	}

	mapper, typer := f.Object()
	o.builder = resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), kapi.Codecs.UniversalDecoder())

	o.out = out

	if len(args) > 0 {
		o.deploymentConfigName = args[0]
	}

	return nil
}

func (o DeployOptions) Validate() error {
	if len(o.deploymentConfigName) == 0 {
		msg := fmt.Sprintf("a deployment config name is required.\nUse \"%s get dc\" for a list of available deployment configs.", o.baseCommandName)
		return errors.New(msg)
	}
	numOptions := 0
	if o.deployLatest {
		numOptions++
	}
	if o.retryDeploy {
		numOptions++
	}
	if o.cancelDeploy {
		if o.follow {
			return errors.New("cannot follow the logs while canceling a deployment")
		}
		numOptions++
	}
	if o.enableTriggers {
		if o.follow {
			return errors.New("cannot follow the logs while enabling triggers for a deployment")
		}
		numOptions++
	}
	if numOptions > 1 {
		return errors.New("only one of --latest, --retry, --cancel, or --enable-triggers is allowed.")
	}
	return nil
}

func (o DeployOptions) RunDeploy() error {
	r := o.builder.
		NamespaceParam(o.namespace).
		ResourceNames("deploymentconfigs", o.deploymentConfigName).
		SingleResourceType().
		Do()
	resultObj, err := r.Object()
	if err != nil {
		return err
	}
	config, ok := resultObj.(*deployapi.DeploymentConfig)
	if !ok {
		return fmt.Errorf("%s is not a valid deployment config", o.deploymentConfigName)
	}

	switch {
	case o.deployLatest:
		err = o.deploy(config)
	case o.retryDeploy:
		err = o.retry(config)
	case o.cancelDeploy:
		err = o.cancel(config)
	case o.enableTriggers:
		err = o.reenableTriggers(config)
	default:
		if o.follow {
			return o.getLogs(config)
		}
		describer := describe.NewLatestDeploymentsDescriber(o.osClient, o.kubeClient, -1)
		desc, err := describer.Describe(config.Namespace, config.Name)
		if err != nil {
			return err
		}
		fmt.Fprint(o.out, desc)
	}

	return err
}

// deploy launches a new deployment unless there's already a deployment
// process in progress for config.
func (o DeployOptions) deploy(config *deployapi.DeploymentConfig) error {
	if config.Spec.Paused {
		return fmt.Errorf("cannot deploy a paused deployment config")
	}
	// TODO: This implies that deploymentconfig.status.latestVersion is always synced. Currently,
	// that's the case because clients (oc, trigger controllers) are updating the status directly.
	// Clients should be acting either on spec or on annotations and status updates should be a
	// responsibility of the main controller. We need to start by unplugging this assumption from
	// our client tools.
	deploymentName := deployutil.LatestDeploymentNameForConfig(config)
	deployment, err := o.kubeClient.Core().ReplicationControllers(config.Namespace).Get(deploymentName)
	if err == nil && !deployutil.IsTerminatedDeployment(deployment) {
		// Reject attempts to start a concurrent deployment.
		return fmt.Errorf("#%d is already in progress (%s).\nOptionally, you can cancel this deployment using 'oc rollout cancel dc/%s'.",
			config.Status.LatestVersion, deployutil.DeploymentStatusFor(deployment), deployment.Name)
	}
	if err != nil && !kerrors.IsNotFound(err) {
		return err
	}

	request := &deployapi.DeploymentRequest{
		Name:   config.Name,
		Latest: false,
		Force:  true,
	}

	dc, err := o.osClient.DeploymentConfigs(config.Namespace).Instantiate(request)
	// Pre 1.4 servers don't support the instantiate endpoint. Fallback to incrementing
	// latestVersion on them.
	if kerrors.IsNotFound(err) || kerrors.IsForbidden(err) {
		config.Status.LatestVersion++
		dc, err = o.osClient.DeploymentConfigs(config.Namespace).Update(config)
	}
	if err != nil {
		if kerrors.IsBadRequest(err) {
			err = fmt.Errorf("%v - try 'oc rollout latest dc/%s'", err, config.Name)
		}
		return err
	}
	fmt.Fprintf(o.out, "Started deployment #%d\n", dc.Status.LatestVersion)
	if o.follow {
		return o.getLogs(dc)
	}
	fmt.Fprintf(o.out, "Use '%s logs -f dc/%s' to track its progress.\n", o.baseCommandName, dc.Name)
	return nil
}

// retry resets the status of the latest deployment to New, which will cause
// the deployment to be retried. An error is returned if the deployment is not
// currently in a failed state.
func (o DeployOptions) retry(config *deployapi.DeploymentConfig) error {
	if config.Spec.Paused {
		return fmt.Errorf("cannot retry a paused deployment config")
	}
	if config.Status.LatestVersion == 0 {
		return fmt.Errorf("no deployments found for %s/%s", config.Namespace, config.Name)
	}
	// TODO: This implies that deploymentconfig.status.latestVersion is always synced. Currently,
	// that's the case because clients (oc, trigger controllers) are updating the status directly.
	// Clients should be acting either on spec or on annotations and status updates should be a
	// responsibility of the main controller. We need to start by unplugging this assumption from
	// our client tools.
	deploymentName := deployutil.LatestDeploymentNameForConfig(config)
	deployment, err := o.kubeClient.Core().ReplicationControllers(config.Namespace).Get(deploymentName)
	if err != nil {
		if kerrors.IsNotFound(err) {
			return fmt.Errorf("unable to find the latest deployment (#%d).\nYou can start a new deployment with 'oc deploy --latest dc/%s'.", config.Status.LatestVersion, config.Name)
		}
		return err
	}

	if !deployutil.IsFailedDeployment(deployment) {
		message := fmt.Sprintf("#%d is %s; only failed deployments can be retried.\n", config.Status.LatestVersion, deployutil.DeploymentStatusFor(deployment))
		if deployutil.IsCompleteDeployment(deployment) {
			message += fmt.Sprintf("You can start a new deployment with 'oc deploy --latest dc/%s'.", config.Name)
		} else {
			message += fmt.Sprintf("Optionally, you can cancel this deployment with 'oc rollout cancel dc/%s'.", config.Name)
		}

		return fmt.Errorf(message)
	}

	// Delete the deployer pod as well as the deployment hooks pods, if any
	pods, err := o.kubeClient.Core().Pods(config.Namespace).List(kapi.ListOptions{LabelSelector: deployutil.DeployerPodSelector(deploymentName)})
	if err != nil {
		return fmt.Errorf("failed to list deployer/hook pods for deployment #%d: %v", config.Status.LatestVersion, err)
	}
	for _, pod := range pods.Items {
		err := o.kubeClient.Core().Pods(pod.Namespace).Delete(pod.Name, kapi.NewDeleteOptions(0))
		if err != nil {
			return fmt.Errorf("failed to delete deployer/hook pod %s for deployment #%d: %v", pod.Name, config.Status.LatestVersion, err)
		}
	}

	deployment.Annotations[deployapi.DeploymentStatusAnnotation] = string(deployapi.DeploymentStatusNew)
	// clear out the cancellation flag as well as any previous status-reason annotation
	delete(deployment.Annotations, deployapi.DeploymentStatusReasonAnnotation)
	delete(deployment.Annotations, deployapi.DeploymentCancelledAnnotation)
	_, err = o.kubeClient.Core().ReplicationControllers(deployment.Namespace).Update(deployment)
	if err != nil {
		return err
	}
	fmt.Fprintf(o.out, "Retried #%d\n", config.Status.LatestVersion)
	if o.follow {
		return o.getLogs(config)
	}
	fmt.Fprintf(o.out, "Use '%s logs -f dc/%s' to track its progress.\n", o.baseCommandName, config.Name)
	return nil
}

// cancel cancels any deployment process in progress for config.
// TODO: this code will be deprecated
func (o DeployOptions) cancel(config *deployapi.DeploymentConfig) error {
	if config.Spec.Paused {
		return fmt.Errorf("cannot cancel a paused deployment config")
	}
	deploymentList, err := o.kubeClient.Core().ReplicationControllers(config.Namespace).List(kapi.ListOptions{LabelSelector: deployutil.ConfigSelector(config.Name)})
	if err != nil {
		return err
	}
	if len(deploymentList.Items) == 0 {
		fmt.Fprintf(o.out, "There have been no deployments for %s/%s\n", config.Namespace, config.Name)
		return nil
	}
	deployments := make([]*kapi.ReplicationController, 0, len(deploymentList.Items))
	for i := range deploymentList.Items {
		deployments = append(deployments, &deploymentList.Items[i])
	}
	sort.Sort(deployutil.ByLatestVersionDesc(deployments))
	failedCancellations := []string{}
	anyCancelled := false
	for _, deployment := range deployments {
		status := deployutil.DeploymentStatusFor(deployment)
		switch status {
		case deployapi.DeploymentStatusNew,
			deployapi.DeploymentStatusPending,
			deployapi.DeploymentStatusRunning:

			if deployutil.IsDeploymentCancelled(deployment) {
				continue
			}

			deployment.Annotations[deployapi.DeploymentCancelledAnnotation] = deployapi.DeploymentCancelledAnnotationValue
			deployment.Annotations[deployapi.DeploymentStatusReasonAnnotation] = deployapi.DeploymentCancelledByUser
			_, err := o.kubeClient.Core().ReplicationControllers(deployment.Namespace).Update(deployment)
			if err == nil {
				fmt.Fprintf(o.out, "Cancelled deployment #%d\n", config.Status.LatestVersion)
				anyCancelled = true
			} else {
				fmt.Fprintf(o.out, "Couldn't cancel deployment #%d (status: %s): %v\n", deployutil.DeploymentVersionFor(deployment), status, err)
				failedCancellations = append(failedCancellations, strconv.FormatInt(deployutil.DeploymentVersionFor(deployment), 10))
			}
		}
	}
	if len(failedCancellations) > 0 {
		return fmt.Errorf("couldn't cancel deployment %s", strings.Join(failedCancellations, ", "))
	}
	if !anyCancelled {
		latest := deployments[0]
		maybeCancelling := ""
		if deployutil.IsDeploymentCancelled(latest) && !deployutil.IsTerminatedDeployment(latest) {
			maybeCancelling = " (cancelling)"
		}
		timeAt := strings.ToLower(units.HumanDuration(time.Now().Sub(latest.CreationTimestamp.Time)))
		fmt.Fprintf(o.out, "No deployments are in progress (latest deployment #%d %s%s %s ago)\n",
			deployutil.DeploymentVersionFor(latest),
			strings.ToLower(string(deployutil.DeploymentStatusFor(latest))),
			maybeCancelling,
			timeAt)
	}
	return nil
}

// reenableTriggers enables all image triggers and then persists config.
func (o DeployOptions) reenableTriggers(config *deployapi.DeploymentConfig) error {
	enabled := []string{}
	for _, trigger := range config.Spec.Triggers {
		if trigger.Type == deployapi.DeploymentTriggerOnImageChange {
			trigger.ImageChangeParams.Automatic = true
			enabled = append(enabled, trigger.ImageChangeParams.From.Name)
		}
	}
	if len(enabled) == 0 {
		fmt.Fprintln(o.out, "No image triggers found to enable")
		return nil
	}
	_, err := o.osClient.DeploymentConfigs(config.Namespace).Update(config)
	if err != nil {
		return err
	}
	fmt.Fprintf(o.out, "Enabled image triggers: %s\n", strings.Join(enabled, ","))
	return nil
}

func (o DeployOptions) getLogs(config *deployapi.DeploymentConfig) error {
	opts := deployapi.DeploymentLogOptions{
		Follow: true,
	}
	readCloser, err := o.osClient.DeploymentLogs(config.Namespace).Get(config.Name, opts).Stream()
	if err != nil {
		return err
	}
	defer readCloser.Close()
	_, err = io.Copy(o.out, readCloser)
	return err
}


text:
import os
from airflow import configuration as conf
from flask_appbuilder.security.manager import AUTH_DB
# from flask_appbuilder.security.manager import AUTH_LDAP
# from flask_appbuilder.security.manager import AUTH_OAUTH
# from flask_appbuilder.security.manager import AUTH_OID
# from flask_appbuilder.security.manager import AUTH_REMOTE_USER
basedir = os.path.abspath(os.path.dirname(__file__))

# The SQLAlchemy connection string.
SQLALCHEMY_DATABASE_URI = conf.get('core', 'SQL_ALCHEMY_CONN')

# Flask-WTF flag for CSRF
CSRF_ENABLED = True

# ----------------------------------------------------
# AUTHENTICATION CONFIG
# ----------------------------------------------------
# For details on how to set up each of the following authentication, see
# http://flask-appbuilder.readthedocs.io/en/latest/security.html# authentication-methods
# for details.

# The authentication type
# AUTH_OID : Is for OpenID
# AUTH_DB : Is for database
# AUTH_LDAP : Is for LDAP
# AUTH_REMOTE_USER : Is for using REMOTE_USER from web server
# AUTH_OAUTH : Is for OAuth
AUTH_TYPE = AUTH_DB

# Uncomment to setup Full admin role name
# AUTH_ROLE_ADMIN = 'Admin'

# Uncomment to setup Public role name, no authentication needed
# AUTH_ROLE_PUBLIC = 'Public'

# Will allow user self registration
# AUTH_USER_REGISTRATION = True

# The default user self registration role
# AUTH_USER_REGISTRATION_ROLE = "Public"

# When using OAuth Auth, uncomment to setup provider(s) info
# Google OAuth example:
# OAUTH_PROVIDERS = [{
# 	'name':'google',
#     'whitelist': ['@YOU_COMPANY_DOMAIN'],  # optional
#     'token_key':'access_token',
#     'icon':'fa-google',
#         'remote_app': {
#             'base_url':'https://www.googleapis.com/oauth2/v2/',
#             'request_token_params':{
#                 'scope': 'email profile'
#             },
#             'access_token_url':'https://accounts.google.com/o/oauth2/token',
#             'authorize_url':'https://accounts.google.com/o/oauth2/auth',
#             'request_token_url': None,
#             'consumer_key': CONSUMER_KEY,
#             'consumer_secret': SECRET_KEY,
#         }
# }]

# When using LDAP Auth, setup the ldap server
# AUTH_LDAP_SERVER = "ldap://ldapserver.new"

# When using OpenID Auth, uncomment to setup OpenID providers.
# example for OpenID authentication
# OPENID_PROVIDERS = [
#    { 'name': 'Yahoo', 'url': 'https://me.yahoo.com' },
#    { 'name': 'AOL', 'url': 'http://openid.aol.com/<username>' },
#    { 'name': 'Flickr', 'url': 'http://www.flickr.com/<username>' },
#    { 'name': 'MyOpenID', 'url': 'https://www.myopenid.com' }]


text:
@implementation TXCouponModel

@end