text:
package com.mozu.android.SalesAssistantUnbranded.ui.customer;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.mozu.android.SalesAssistantUnbranded.R;
import com.mozu.api.contracts.customer.CustomerAccount;
import com.mozu.api.contracts.customer.CustomerContact;

import org.joda.time.DateTime;

/**
 * Created by rodrigo_alvarez on 3/10/14.
 */
public class CustomerFragment extends Fragment implements CustomerView {

    View mContentFrame;

    // Fragment

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_customer, container, false);
        mContentFrame = v.findViewById(R.id.content_frame);
        return v;
    }

    // CustomerView

    @Override
    public void install(Activity activity, int containerId)
    {
        FragmentManager manager = activity.getFragmentManager();
        FragmentTransaction tran = manager.beginTransaction();
        tran.replace(containerId, this);
        tran.commit();
        manager.executePendingTransactions();
    }

    @Override
    public void clear() {
        mContentFrame.setVisibility(View.GONE);
    }

    @Override
    public void render(CustomerAccount customer) {

        View v = getView();
        if(v == null) {
            return;
        }

        String firstName = customer.getFirstName();
        String lastName = customer.getLastName();
        if((firstName == null || lastName == null) && customer.getContacts() != null && !customer.getContacts().isEmpty())
        {
            firstName = customer.getContacts().get(0).getFirstName();
            lastName = customer.getContacts().get(0).getLastNameOrSurname();
        }

        ((TextView)v.findViewById(R.id.name)).setText(getString(R.string.customer_name_format, firstName, lastName));

        String email = customer.getEmailAddress();
        if(email == null && customer.getContacts() != null && !customer.getContacts().isEmpty())
        {
            email = customer.getContacts().get(0).getEmail();
        }
        ((TextView)v.findViewById(R.id.email)).setText(email);

        TextView address = (TextView)v.findViewById(R.id.address);
        if (customer.getContacts().size() > 0) {
            CustomerContact contact = customer.getContacts().get(0);
            address.setText(getString(R.string.customer_address_format, contact.getAddress().getAddress1(), contact.getAddress().getCityOrTown(), contact.getAddress().getStateOrProvince(), contact.getAddress().getPostalOrZipCode()));
        } else {
            address.setText("");
        }

        ((TextView)v.findViewById(R.id.customer_since)).setText(Html.fromHtml(getString(R.string.customer_since_format, new DateTime(customer.getAuditInfo().getCreateDate()).toString("MM/dd/yyyy"))));
        ((TextView)v.findViewById(R.id.lifetime_value)).setText(String.format("%s %.02f", customer.getCommerceSummary().getTotalOrderAmount().getCurrencyCode(), customer.getCommerceSummary().getTotalOrderAmount().getAmount()));

        TextView totalVisits = (TextView)v.findViewById(R.id.total_visits);
        String visits = String.valueOf(customer.getCommerceSummary().getVisitsCount());
        if(customer.getCommerceSummary().getVisitsCount() == null || "0".equals(visits)) {
            visits = getString(R.string.none);
        }
        totalVisits.setText(visits);

        TextView totalOrders = (TextView)v.findViewById(R.id.total_orders);
        if (customer.getCommerceSummary().getOrderCount() != null)
            totalOrders.setText(customer.getCommerceSummary().getOrderCount().toString());
        else
            totalOrders.setText("0");

        mContentFrame.setVisibility(View.VISIBLE);
    }
}


text:
class Chef::Recipe
  include Gengine
end

# parse default configuration from above
config = Gengine::Config::parse node.gengine.defaults.scheduler
# merge configuration from repository (overwrites defaults)
config.merge!(Gengine::Config::read("#{node.gengine.repo.path}/scheduler"))
# merge configuration attributes (overwrite repository configuration)
config.merge!(node.gengine.scheduler) unless node.gengine.scheduler.empty?

config_file = "#{node.gengine.config}/scheduler"

_command = "qconf -Msconf #{config_file}"
execute _command do
  command _command
  action :nothing
end

# write the global defaults configuration file
file config_file do
  content Gengine::Config::create(config)
  # trigger re-configuration on change
  notifies :run, "execute[#{_command}]", :immediately
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%5p (%F:%L) -> %m%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Root level="error">
      <AppenderRef ref="Console"/>
    </Root>
    <!--
    <Logger name="org.glassfish.grizzly.http.server.NetworkListener"
            level="trace">
      <AppenderRef ref="Console"/>
    </Logger>
    <Logger name="de.ids_mannheim.korap.response.Match"
            additivity="false"
            level="trace">
      <AppenderRef ref="Console"/>
    </Logger>
      <Logger name="de.ids_mannheim.korap.KrillIndex"
            additivity="false"
            level="trace">
      <AppenderRef ref="Console"/>
    </Logger>
    -->
  </Loggers>
</Configuration>


text:
import asyncio
import functools
import time
import inspect

from aiohttp_debugtoolbar.panels.base import DebugPanel
from aiopg.cursor import Cursor

__all__ = ['RequestPgDebugPanel']

class RequestHandler(object):
    def __init__(self):
        self._queries = []
        self._total_time = 0
        # save original
        self._tmp_execute = Cursor.execute

    @property
    def queries(self):
        return self._queries

    @property
    def total_time(self):
        return self._total_time

    def _wrapper(self, func):
        @functools.wraps(func)
        @asyncio.coroutine
        def wrapped(*args, **kwargs):
            start = time.time()

            if asyncio.iscoroutinefunction(func):
                coro = func
            else:
                coro = asyncio.coroutine(func)
            context = yield from coro(*args, **kwargs)

            called_from = []
            for stack in inspect.stack()[1:]:
                called_from.append("/{0}:{1}".format(
                    "/".join(stack[1].split('/')[-3:]), stack[2]))
                if len(called_from) >= 2:
                    break

            elapsed = time.time() - start
            arg = {
                'query': args[1].strip().replace(
                    "\n", "
").replace(
                    "\t", "  ").replace(
                    "    ", "  "),
                'params': args[2] if len(args) > 2 else [],
                'other': dict(kwargs),
                'elapsed': '%0.3f sec' % elapsed,
                'called_from': "
".join(reversed(called_from)),
            }
            self._queries.append(arg)
            self._total_time += elapsed

            return context

        return wrapped

    def on(self):
        Cursor.execute = self._wrapper(Cursor.execute)

    def off(self):
        Cursor.execute = self._tmp_execute

class RequestPgDebugPanel(DebugPanel):
    """
    A panel to display SQL queries.
    """
    name = 'PgSQL'
    template = 'request_pgsql.jinja2'
    title = 'PgSQL Queries'
    nav_title = title

    def __init__(self, request):
        super().__init__(request)
        self._handler = RequestHandler()

    @property
    def has_content(self):
        if self.data.get('queries'):
            return True
        return False

    @asyncio.coroutine
    def process_response(self, response):
        self.data = data = {}
        data.update({
            'timing_rows': {
                'Total time': '%0.3f sec' % self._handler.total_time,
                'Total': len(self._handler.queries),
            }.items(),
            'queries': [(k, v)
                        for k, v in enumerate(self._handler.queries)],
        })

    def _install_handler(self):
        self._handler.on()

    def _uninstall_handler(self):
        self._handler.off()

    def wrap_handler(self, handler, context_switcher):
        context_switcher.add_context_in(self._install_handler)
        context_switcher.add_context_out(self._uninstall_handler)
        return handler


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- 数据库配置 -->
		<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
		<property name="hibernate.connection.password">123</property>
		<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;databaseName=OrdersTable</property>
		<property name="hibernate.connection.username">sa</property>
		<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>

		<!-- hibernate属性配置 -->
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">update</property>

		<!-- 连接池 -->
		<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
		<property name="hibernate.c3p0.min_size">5</property>
		<property name="hibernate.c3p0.max_size">30</property>
		<property name="hibernate.c3p0.timeout">50000</property>
		<property name="hibernate.c3p0.max_statements">50</property>
		<property name="hibernate.c3p0.acquire_increment">2</property>
		<property name="hibernate.c3p0.validate">false</property>

		<mapping resource="com/server/entity/Orders.hbm.xml"/>
		<mapping resource="com/server/entity/Persons.hbm.xml"/>
	</session-factory>
</hibernate-configuration>


text:
<md-sidenav class="md-sidenav-left" md-component-id="help-sidenav" md-is-locked-open="$ctrl.ConfigService.showHelpSidenav">

    <md-toolbar class="md-hue-4">

راهنما

        <md-button aria-label="بستن راهنما" class="md-icon-button" title="بستن راهنما" ng-click="$ctrl.close()">
          <md-icon>close</md-icon>
        </md-button>

    </md-toolbar>
    <md-content layout="column">
      <md-card ng-repeat="document in $ctrl.documents.data">
        <md-card-header>
          <md-card-header-text>
            {{document.title}}
          </md-card-header-text>
        </md-card-header>
        <md-card-content>

        </md-card-content>
      </md-card>
    </md-content>

</md-sidenav>


text:
using System.Collections.Generic;
using ExcelDna.Integration;
using QuantSA.Core.Primitives;
using QuantSA.Excel.Shared;
using QuantSA.Shared;
using QuantSA.Shared.Dates;
using QuantSA.Shared.MarketData;
using QuantSA.Shared.Primitives;
using QuantSA.Valuation;
using QuantSA.Valuation.Models.Rates;

namespace QuantSA.ExcelFunctions
{
    public class XLValuation
    {
        [QuantSAExcelFunction(Description = "Create a curve based valuation model.",
            Name = "QSA.CreateCurveModel",
            HasGeneratedVersion = true,
            Category = "QSA.Valuation",
            ExampleSheet = "GeneralSwap.xlsx",
            IsHidden = false,
            HelpTopic = "http://www.quantsa.org/CreateCurveModel.html")]
        public static NumeraireSimulator CreateCurveModel([QuantSAExcelArgument(Description = "The discounting curve")]
            IDiscountingSource discountCurve,
            [QuantSAExcelArgument(Description =
                "The floating rate forecast curves for all the rates that the products in the portfolio will need.")]
            IFloatingRateSource[] rateForecastCurves,
            [QuantSAExcelArgument(Description =
                    "The FX rate forecast curves for all the cashflow currencies other than the discounting currency.",
                Default = null)]
            IFXSource[] fxForecastCurves)
        {
            var model = new DeterministicCurves(discountCurve);
            model.AddRateForecast(rateForecastCurves);
            if (fxForecastCurves != null)
                model.AddFXForecast(fxForecastCurves);
            return model;
        }

        [QuantSAExcelFunction(Description = "Perform a general valuation.",
            Name = "QSA.Value",
            HasGeneratedVersion = true,
            Category = "QSA.Valuation",
            ExampleSheet = "GeneralSwap.xlsx",
            IsHidden = false,
            HelpTopic = "http://www.quantsa.org/Value.html")]
        public static ResultStore Value([ExcelArgument(Description = "A list of products.")]
            Product[] products,
            [QuantSAExcelArgument(Description = "The value date.")]
            Date valueDate,
            [QuantSAExcelArgument(Description =
                "A model able to handle all the market observables required to calculate the cashflows in the portfolio.")]
            NumeraireSimulator model,
            [QuantSAExcelArgument(
                Description =
                    "Optional.  The number of simulations required if the model requires simulation.  If left blank will use a default value depending on the model.",
                Default = "1")]
            int nSims)
        {
            var coordinator = new Coordinator(model, new List<Simulator>(), nSims);
            var value = coordinator.Value(products, valueDate);
            var result = new ResultStore();
            result.Add("value", value);
            return result;
        }

        [QuantSAExcelFunction(Description = "Calculate the expected positive exposure for a general portfolio",
            Name = "QSA.EPE",
            HasGeneratedVersion = true,
            Category = "QSA.Valuation",
            ExampleSheet = "EPE.xlsx",
            IsHidden = false,
            HelpTopic = "http://www.quantsa.org/EPE.html")]
        public static double[] EPE([ExcelArgument(Description = "A list of products.")]
            IProduct[] products,
            [ExcelArgument(Description = "The value date.")]
            Date valueDate,
            [ExcelArgument(Description = "The dates at which the expected positive exposure is required.")]
            Date[] forwardValueDates,
            [ExcelArgument(Description =
                "A model able to handle all the market observables required to calculate the cashflows in the portfolio.")]
            NumeraireSimulator model,
            [ExcelArgument(Description = "The number of simulations required.")]
            int nSims)
        {
            var coordinator = new Coordinator(model, new List<Simulator>(), nSims);
            return coordinator.EPE(products, valueDate, forwardValueDates);
        }

        [QuantSAExcelFunction(Description = "An approximate PFE for a portfolio of trades.",
            Name = "QSA.PFE",
            HasGeneratedVersion = true,
            Category = "QSA.Valuation",
            ExampleSheet = "PFE.xlsx",
            IsHidden = false,
            HelpTopic = "http://www.quantsa.org/PFE.html")]
        public static double[,] PFE([ExcelArgument(Description = "A list of products.")]
            IProduct[] products,
            [ExcelArgument(Description = "The value date.")]
            Date valueDate,
            [ExcelArgument(Description = "The dates at which the expected positive exposure is required.")]
            Date[] forwardValueDates,
            [ExcelArgument(Description =
                "The required percentiles.  95th percentile should be entered as 0.95.  Can be a list of percentiles and the PFE will be calculated at each of the provided levels.")]
            double[] requiredPecentiles,
            [ExcelArgument(Description =
                "A model able to handle all the market observables required to calculate the cashflows in the portfolio.")]
            NumeraireSimulator model,
            [ExcelArgument(Description = "The number of simulations required.")]
            int nSims)
        {
            var coordinator = new Coordinator(model, new List<Simulator>(), nSims);
            return coordinator.PFE(products, valueDate, forwardValueDates, requiredPecentiles);
        }
    }
}


text:
import express from 'express';
import webpack from 'webpack';
import path from 'path';
import webpackConfig from '../webpack/webpack.config.dev';
import open from 'open';

/*eslint-disable no-console*/

const port = 3001;
const app = express();
const compiler = webpack(webpackConfig);

app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: webpackConfig.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

app.get('*', (req, res) =>{
   res.sendFile(path.join(__dirname, '../src/index.html'));
});

app.listen(port, err => {
   if(err){
       console.log(err);
   } else{
       open(`http://localhost:${port}`);
   }
});


text:
guru-monitor
============

Un logiciel dont l'histoire sera peut-être écrite au Start Up Week-End Toulon


text:
package com.amazonaws.services.lightsail.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.lightsail.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * CreateLoadBalancerTlsCertificateRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CreateLoadBalancerTlsCertificateRequestMarshaller {

    private static final MarshallingInfo<String> LOADBALANCERNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("loadBalancerName").build();
    private static final MarshallingInfo<String> CERTIFICATENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("certificateName").build();
    private static final MarshallingInfo<String> CERTIFICATEDOMAINNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("certificateDomainName").build();
    private static final MarshallingInfo<List> CERTIFICATEALTERNATIVENAMES_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("certificateAlternativeNames").build();
    private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("tags").build();

    private static final CreateLoadBalancerTlsCertificateRequestMarshaller instance = new CreateLoadBalancerTlsCertificateRequestMarshaller();

    public static CreateLoadBalancerTlsCertificateRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(CreateLoadBalancerTlsCertificateRequest createLoadBalancerTlsCertificateRequest, ProtocolMarshaller protocolMarshaller) {

        if (createLoadBalancerTlsCertificateRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(createLoadBalancerTlsCertificateRequest.getLoadBalancerName(), LOADBALANCERNAME_BINDING);
            protocolMarshaller.marshall(createLoadBalancerTlsCertificateRequest.getCertificateName(), CERTIFICATENAME_BINDING);
            protocolMarshaller.marshall(createLoadBalancerTlsCertificateRequest.getCertificateDomainName(), CERTIFICATEDOMAINNAME_BINDING);
            protocolMarshaller.marshall(createLoadBalancerTlsCertificateRequest.getCertificateAlternativeNames(), CERTIFICATEALTERNATIVENAMES_BINDING);
            protocolMarshaller.marshall(createLoadBalancerTlsCertificateRequest.getTags(), TAGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
layout: book
title: "Lincoln Tome 5 : Cul nul dans la plaine"
author: "Olivier Jouvray, Jérôme Jouvray"
isbn: "9782888901518"
editor: "Paquet Eds"
---
![Couverture](/img/9782888901518.jpg)- Mes amis, je vous présente Lincoln, c'est un grand justicier américain ! Il trouve que ce qui se passe dans votre pays est injuste. Là-bas, des hommes volent vos terres et vos richesses sans le moindre scrupule et vous obligent à trouver refuge ici, c'est inacceptable ! Lincoln refuse de laisser faire cela et c'est pour aller se battre qu'il est venu jusqu'ici !
- Mais... Ça va pas bien, non ?


text:
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" packagerversion="1.7.1" version="2.0" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd">
 <name>nahoSecurityPlugin</name>
 <channel>pear.symfony-project.com</channel>
 <summary>Simple module/action ACL plugin.</summary>
 <description>Once the plugin enabled, you just have to set "is_secure" to `on` in your
application's security.yml, and each module/action will require the
credential "application.module.action".</description>
 <lead>
  <name>Nicolas Chambrier (naholyr)</name>
  <user>naholyr</user>
  <email>naholyr@yahoo.fr</email>
  <active>yes</active>
 </lead>
 <date>2009-04-15</date>
 <time>19:31:24</time>
 <version>
  <release>0.1.0</release>
  <api>0.1.0</api>
 </version>
 <stability>
  <release>beta</release>
  <api>beta</api>
 </stability>
 <license uri="http://www.symfony-project.com/license">MIT license</license>
 <notes>-</notes>
 <contents>
  <dir name="/">
   <file md5sum="90049a15786208158fe0a7546c493fd6" name="config/app.yml" role="data"/>
   <file md5sum="8826fdb55d81dac9208648353a13b6aa" name="lib/nahoSecurityFilter.php" role="data"/>
   <file md5sum="ec5940da690b8ef545f33706ef31992e" name="README" role="data"/>
   <file md5sum="22319e53eff7081217cbfe6e1addcb07" name="LICENSE" role="data"/>
  </dir>
 </contents>
 <dependencies>
  <required>
   <php>
    <min>5.0.0</min>
   </php>
   <pearinstaller>
    <min>1.4.1</min>
   </pearinstaller>

  </required>
 </dependencies>
 <phprelease/>
 <changelog>
  <release>
   <version>
    <release>0.1.0</release>
    <api>0.1.0</api>
   </version>
   <stability>
    <release>beta</release>
    <api>beta</api>
   </stability>
   <license uri="http://www.symfony-project.com/license">MIT license</license>
   <license>MIT</license>
   <date>2009-04-15</date>
   <notes>* naholyr: first release, auto_credential features</notes>
  </release>
 </changelog>
</package>


text:
<?php
/**
 * sfPropelObject
 *
 * class to impersonate a propel object
 *
 * @package veolys
 * @subpackage lib
 * @author Romain Dorgueil <romain.dorgueil@sensio.net>
 * @version SVN: $Id$
 */
class sfPropelObject
{
  protected
    $columns;

  public function __construct($columns)
  {
    foreach($columns as $index=>$column)
    {
      if (is_array($column) && count($column)>=2)
      {
        if (!isset($column[2]))
        {
          $columns[$index][2] = trim(strtolower(preg_replace('/[^a-z]+/i', '_', $column[1])), '_');
        }
        else
        {
          $columns[$index][2] = trim(strtolower(preg_replace('/[^a-z_]+/i', '_', $column[2])), '_');
        }
      }
      else
      {
        throw new InvalidArgumentException('sfPropelObject constructor waits for a list of 2 items-array (at least) arguments.');
      }
    }

    $this->columns = $columns;
  }

  public function getPrimaryKey()
  {
    return 0;
  }

  public function hydrate(ResultSet $rs, $startcol = 1)
  {
    try
    {
      foreach($this->columns as $_array)
      {
        list($type, $field, $name) = $_array;
        $this->$name = $rs->{'get'.ucfirst($type)}($startcol);
        $startcol++;
      }

      return $startcol;
    }
    catch (Exception $e)
    {
      throw new PropelException("Error populating Impersonator object", $e);
    }
  }

  public function __call($method, $parameters)
  {
    $verb = substr($method, 0, 3);
    $field = sfInflector::underscore(substr($method, 3));

    if (property_exists($this, $field))
    {
      switch ($verb)
      {
        case 'get':
          return $this->$field;
        case 'set':
          $this->$field = $parameters[0];
          return;
      }
    }

    throw new sfException ('Unknown method called '.__CLASS__.'::'.$method.'()');
  }

  public function addSelectColumns(Criteria &$c)
  {
    foreach ($this->columns as $index => $column)
    {
      $c->addAsColumn($column[2], $column[1]);
    }
  }

  public function getPeer()
  {
    return null;
  }

  public function getColumns()
  {
    return $this->columns;
  }

  public function toArray()
  {
    $result = array();

    foreach ($this->columns as $column)
    {
      $result[$column[2]] = $this->{$column[2]};
    }

    return $result;
  }

  public function __toString()
  {
    return $this->name;
  }
}


text:
SecPolicyRef AppleCryptoNative_X509ChainCreateDefaultPolicy()
{
    // Disable on macOS 10.11 and lower due to segfaults within Security.framework.
    if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber10_12)
        return NULL;

    return SecPolicyCreateBasicX509();
}

SecPolicyRef AppleCryptoNative_X509ChainCreateRevocationPolicy()
{
    return SecPolicyCreateRevocation(kSecRevocationUseAnyAvailableMethod | kSecRevocationRequirePositiveResponse);
}

int32_t
AppleCryptoNative_X509ChainCreate(CFTypeRef certs, CFTypeRef policies, SecTrustRef* pTrustOut, int32_t* pOSStatus)
{
    if (pTrustOut != NULL)
        *pTrustOut = NULL;
    if (pOSStatus != NULL)
        *pOSStatus = noErr;

    if (certs == NULL || policies == NULL || pTrustOut == NULL || pOSStatus == NULL)
        return -1;

    *pOSStatus = SecTrustCreateWithCertificates(certs, policies, pTrustOut);
    return *pOSStatus == noErr;
}

int32_t AppleCryptoNative_X509ChainEvaluate(SecTrustRef chain,
                                            CFDateRef cfEvaluationTime,
                                            bool allowNetwork,
                                            int32_t* pOSStatus)
{
    if (pOSStatus != NULL)
        *pOSStatus = noErr;

    if (chain == NULL || pOSStatus == NULL)
        return -1;

    *pOSStatus = SecTrustSetVerifyDate(chain, cfEvaluationTime);

    if (*pOSStatus != noErr)
    {
        return -2;
    }

    *pOSStatus = SecTrustSetNetworkFetchAllowed(chain, allowNetwork);

    if (*pOSStatus != noErr)
    {
        return -3;
    }

    SecTrustResultType trustResult;
    *pOSStatus = SecTrustEvaluate(chain, &trustResult);

    // If any error is reported from the function or the trust result value indicates that
    // otherwise was a failed chain build (vs an untrusted chain, etc) return failure and
    // we'll throw in the managed layer.  (but if we hit the "or" the message is "No error")
    if (*pOSStatus != noErr || trustResult == kSecTrustResultInvalid)
    {
        return 0;
    }

    // If: The chain was built with no errors (Unspecified)
    // Or: The chain was built and involved an explicitly trusted cert (Proceed)
    // Then: Success.
    if (trustResult == kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed)
    {
        return 1;
    }

    // Should this be a different return code?
    return 1;
}

int64_t AppleCryptoNative_X509ChainGetChainSize(SecTrustRef chain)
{
    if (chain == NULL)
        return -1;

    return SecTrustGetCertificateCount(chain);
}

SecCertificateRef AppleCryptoNative_X509ChainGetCertificateAtIndex(SecTrustRef chain, int64_t index)
{
    if (chain == NULL || index < 0)
        return NULL;

    return SecTrustGetCertificateAtIndex(chain, index);
}

CFArrayRef AppleCryptoNative_X509ChainGetTrustResults(SecTrustRef chain)
{
    if (chain == NULL)
    {
        return NULL;
    }

    CFDictionaryRef detailsAndStuff = SecTrustCopyResult(chain);
    CFArrayRef details = NULL;

    if (detailsAndStuff != NULL)
    {
        CFTypeRef detailsPtr = CFDictionaryGetValue(detailsAndStuff, CFSTR("TrustResultDetails"));

        if (detailsPtr != NULL)
        {
            details = (CFArrayRef)detailsPtr;
            CFRetain(details);
        }
    }

    CFRelease(detailsAndStuff);
    return details;
}

static void MergeStatusCodes(CFTypeRef key, CFTypeRef value, void* context)
{
    // Windows (and therefore .NET) certificate status codes are defined on an int32_t.
    // The top 32 bits will be used to convey error information, the bottom 32 bits
    // as a data aggregator for the status codes.
    uint64_t* pStatus = (uint64_t*)context;

    if (key == NULL)
    {
        return;
    }

    // If any error code was already set.
    if (*pStatus > INT_MAX)
    {
        return;
    }

    if (CFGetTypeID(key) != CFStringGetTypeID())
    {
        *pStatus |= PAL_X509ChainErrorUnknownValueType;
        return;
    }

    (void)value;
    CFStringRef keyString = (CFStringRef)key;

    if (CFEqual(keyString, CFSTR("NotValidBefore")) || CFEqual(keyString, CFSTR("ValidLeaf")) ||
        CFEqual(keyString, CFSTR("ValidIntermediates")) || CFEqual(keyString, CFSTR("ValidRoot")) ||
        CFEqual(keyString, CFSTR("TemporalValidity")))
        *pStatus |= PAL_X509ChainNotTimeValid;
    else if (CFEqual(keyString, CFSTR("Revocation")))
        *pStatus |= PAL_X509ChainRevoked;
    else if (CFEqual(keyString, CFSTR("KeyUsage")))
        *pStatus |= PAL_X509ChainNotValidForUsage;
    else if (CFEqual(keyString, CFSTR("AnchorTrusted")))
        *pStatus |= PAL_X509ChainUntrustedRoot;
    else if (CFEqual(keyString, CFSTR("BasicConstraints")))
        *pStatus |= PAL_X509ChainInvalidBasicConstraints;
    else if (CFEqual(keyString, CFSTR("UsageConstraints")))
        *pStatus |= PAL_X509ChainExplicitDistrust;
    else if (CFEqual(keyString, CFSTR("RevocationResponseRequired")))
        *pStatus |= PAL_X509ChainRevocationStatusUnknown;
    else if (CFEqual(keyString, CFSTR("MissingIntermediate")))
        *pStatus |= PAL_X509ChainPartialChain;
    else if (CFEqual(keyString, CFSTR("WeakLeaf")) || CFEqual(keyString, CFSTR("WeakIntermediates")) ||
             CFEqual(keyString, CFSTR("WeakRoot")) || CFEqual(keyString, CFSTR("WeakKeySize")))
    {
        // Because we won't report this out of a chain built by .NET on Windows,
        // don't report it here.
        //
        // (On Windows CERT_CHAIN_PARA.pStrongSignPara is NULL, so "strongness" checks
        // are not performed).
    }
    else if (CFEqual(keyString, CFSTR("StatusCodes")))
    {
        // 10.13 added a StatusCodes value which may be a numeric rehashing of the string data.
        // It doesn't represent a new error code, and we're still getting the old ones, so
        // just ignore it for now.
    }
    else if (CFEqual(keyString, CFSTR("NonEmptySubject")) || CFEqual(keyString, CFSTR("GrayListedKey")))
    {
        // Not a "problem" that we report.
    }
    else
    {
#ifdef DEBUGGING_UNKNOWN_VALUE
        printf("%s\n", CFStringGetCStringPtr(keyString, CFStringGetSystemEncoding()));
#endif
        *pStatus |= PAL_X509ChainErrorUnknownValue;
    }
}

int32_t AppleCryptoNative_X509ChainGetStatusAtIndex(CFArrayRef details, int64_t index, int32_t* pdwStatus)
{
    if (pdwStatus != NULL)
        *pdwStatus = -1;

    if (details == NULL || index < 0 || pdwStatus == NULL)
    {
        return -1;
    }

    CFTypeRef element = CFArrayGetValueAtIndex(details, index);

    if (element == NULL)
    {
        return -2;
    }

    if (CFGetTypeID(element) != CFDictionaryGetTypeID())
    {
        return -2;
    }

    uint64_t status = 0;
    CFDictionaryRef statusCodes = (CFDictionaryRef)element;
    CFDictionaryApplyFunction(statusCodes, MergeStatusCodes, &status);

    *pdwStatus = (int32_t)status;
    return (int32_t)(status >> 32);
}

int32_t AppleCryptoNative_GetOSStatusForChainStatus(PAL_X509ChainStatusFlags chainStatusFlag)
{
    switch (chainStatusFlag)
    {
        case PAL_X509ChainNoError:
            return noErr;
        case PAL_X509ChainNotTimeValid:
            // This code is ambiguous.  Windows uses it for "not valid",
            // Apple makes a distinction between "not yet" and "not any more"
            // So this is just a fallback, because we should have determined it
            // via different means.`
            return errSecCertificateExpired;
        case PAL_X509ChainRevoked:
            return errSecCertificateRevoked;
        case PAL_X509ChainNotValidForUsage:
            return errSecKeyUsageIncorrect;
        case PAL_X509ChainUntrustedRoot:
            return errSecNotTrusted;
        case PAL_X509ChainInvalidBasicConstraints:
            return errSecNoBasicConstraints;
        case PAL_X509ChainPartialChain:
            return errSecCreateChainFailed;
        case PAL_X509ChainExplicitDistrust:
            return errSecTrustSettingDeny;
        case PAL_X509ChainRevocationStatusUnknown:
            return errSecIncompleteCertRevocationCheck;
        default:
            return errSecCoreFoundationUnknown;
    }
}


text:
package org.javers.core.diff.changetype.container;

import org.javers.common.string.PrettyValuePrinter;

import java.io.Serializable;
import java.util.Objects;

/**
 * Any change in an Array or Collection
 *
 * @author pawel szymczyk
 */
public abstract class ContainerElementChange implements Serializable {
    private Integer index;

    ContainerElementChange(int index) {
        this.index = index;
    }

    ContainerElementChange() {
        this.index = null;
    }

    public Integer getIndex() {
        return index;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof ContainerElementChange) {
            ContainerElementChange that = (ContainerElementChange) obj;
            return Objects.equals(this.getIndex(), that.getIndex());
        }
        return false;
    }

    protected abstract String prettyPrint(PrettyValuePrinter valuePrinter);

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), getIndex());
    }
}


text:
/*
 * arch/ppc/syslib/rheap.c
 *
 * A Remote Heap.  Remote means that we don't touch the memory that the
 * heap points to. Normal heap implementations use the memory they manage
 * to place their list. We cannot do that because the memory we manage may
 * have special properties, for example it is uncachable or of different
 * endianess.
 *
 * Author: Pantelis Antoniou <panto@intracom.gr>
 *
 * 2004 (c) INTRACOM S.A. Greece. This file is licensed under
 * the terms of the GNU General Public License version 2. This program
 * is licensed "as is" without any warranty of any kind, whether express
 * or implied.
 */
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/slab.h>

#include <asm/rheap.h>

/*
 * Fixup a list_head, needed when copying lists.  If the pointers fall
 * between s and e, apply the delta.  This assumes that
 * sizeof(struct list_head *) == sizeof(unsigned long *).
 */
static inline void fixup(unsigned long s, unsigned long e, int d,
			 struct list_head *l)
{
	unsigned long *pp;

	pp = (unsigned long *)&l->next;
	if (*pp >= s && *pp < e)
		*pp += d;

	pp = (unsigned long *)&l->prev;
	if (*pp >= s && *pp < e)
		*pp += d;
}

/* Grow the allocated blocks */
static int grow(rh_info_t * info, int max_blocks)
{
	rh_block_t *block, *blk;
	int i, new_blocks;
	int delta;
	unsigned long blks, blke;

	if (max_blocks <= info->max_blocks)
		return -EINVAL;

	new_blocks = max_blocks - info->max_blocks;

	block = kmalloc(sizeof(rh_block_t) * max_blocks, GFP_KERNEL);
	if (block == NULL)
		return -ENOMEM;

	if (info->max_blocks > 0) {

		/* copy old block area */
		memcpy(block, info->block,
		       sizeof(rh_block_t) * info->max_blocks);

		delta = (char *)block - (char *)info->block;

		/* and fixup list pointers */
		blks = (unsigned long)info->block;
		blke = (unsigned long)(info->block + info->max_blocks);

		for (i = 0, blk = block; i < info->max_blocks; i++, blk++)
			fixup(blks, blke, delta, &blk->list);

		fixup(blks, blke, delta, &info->empty_list);
		fixup(blks, blke, delta, &info->free_list);
		fixup(blks, blke, delta, &info->taken_list);

		/* free the old allocated memory */
		if ((info->flags & RHIF_STATIC_BLOCK) == 0)
			kfree(info->block);
	}

	info->block = block;
	info->empty_slots += new_blocks;
	info->max_blocks = max_blocks;
	info->flags &= ~RHIF_STATIC_BLOCK;

	/* add all new blocks to the free list */
	for (i = 0, blk = block + info->max_blocks; i < new_blocks; i++, blk++)
		list_add(&blk->list, &info->empty_list);

	return 0;
}

/*
 * Assure at least the required amount of empty slots.  If this function
 * causes a grow in the block area then all pointers kept to the block
 * area are invalid!
 */
static int assure_empty(rh_info_t * info, int slots)
{
	int max_blocks;

	/* This function is not meant to be used to grow uncontrollably */
	if (slots >= 4)
		return -EINVAL;

	/* Enough space */
	if (info->empty_slots >= slots)
		return 0;

	/* Next 16 sized block */
	max_blocks = ((info->max_blocks + slots) + 15) & ~15;

	return grow(info, max_blocks);
}

static rh_block_t *get_slot(rh_info_t * info)
{
	rh_block_t *blk;

	/* If no more free slots, and failure to extend. */
	/* XXX: You should have called assure_empty before */
	if (info->empty_slots == 0) {
		printk(KERN_ERR "rh: out of slots; crash is imminent.\n");
		return NULL;
	}

	/* Get empty slot to use */
	blk = list_entry(info->empty_list.next, rh_block_t, list);
	list_del_init(&blk->list);
	info->empty_slots--;

	/* Initialize */
	blk->start = NULL;
	blk->size = 0;
	blk->owner = NULL;

	return blk;
}

static inline void release_slot(rh_info_t * info, rh_block_t * blk)
{
	list_add(&blk->list, &info->empty_list);
	info->empty_slots++;
}

static void attach_free_block(rh_info_t * info, rh_block_t * blkn)
{
	rh_block_t *blk;
	rh_block_t *before;
	rh_block_t *after;
	rh_block_t *next;
	int size;
	unsigned long s, e, bs, be;
	struct list_head *l;

	/* We assume that they are aligned properly */
	size = blkn->size;
	s = (unsigned long)blkn->start;
	e = s + size;

	/* Find the blocks immediately before and after the given one
	 * (if any) */
	before = NULL;
	after = NULL;
	next = NULL;

	list_for_each(l, &info->free_list) {
		blk = list_entry(l, rh_block_t, list);

		bs = (unsigned long)blk->start;
		be = bs + blk->size;

		if (next == NULL && s >= bs)
			next = blk;

		if (be == s)
			before = blk;

		if (e == bs)
			after = blk;

		/* If both are not null, break now */
		if (before != NULL && after != NULL)
			break;
	}

	/* Now check if they are really adjacent */
	if (before != NULL && s != (unsigned long)before->start + before->size)
		before = NULL;

	if (after != NULL && e != (unsigned long)after->start)
		after = NULL;

	/* No coalescing; list insert and return */
	if (before == NULL && after == NULL) {

		if (next != NULL)
			list_add(&blkn->list, &next->list);
		else
			list_add(&blkn->list, &info->free_list);

		return;
	}

	/* We don't need it anymore */
	release_slot(info, blkn);

	/* Grow the before block */
	if (before != NULL && after == NULL) {
		before->size += size;
		return;
	}

	/* Grow the after block backwards */
	if (before == NULL && after != NULL) {
		after->start = (int8_t *)after->start - size;
		after->size += size;
		return;
	}

	/* Grow the before block, and release the after block */
	before->size += size + after->size;
	list_del(&after->list);
	release_slot(info, after);
}

static void attach_taken_block(rh_info_t * info, rh_block_t * blkn)
{
	rh_block_t *blk;
	struct list_head *l;

	/* Find the block immediately before the given one (if any) */
	list_for_each(l, &info->taken_list) {
		blk = list_entry(l, rh_block_t, list);
		if (blk->start > blkn->start) {
			list_add_tail(&blkn->list, &blk->list);
			return;
		}
	}

	list_add_tail(&blkn->list, &info->taken_list);
}

/*
 * Create a remote heap dynamically.  Note that no memory for the blocks
 * are allocated.  It will upon the first allocation
 */
rh_info_t *rh_create(unsigned int alignment)
{
	rh_info_t *info;

	/* Alignment must be a power of two */
	if ((alignment & (alignment - 1)) != 0)
		return ERR_PTR(-EINVAL);

	info = kmalloc(sizeof(*info), GFP_KERNEL);
	if (info == NULL)
		return ERR_PTR(-ENOMEM);

	info->alignment = alignment;

	/* Initially everything as empty */
	info->block = NULL;
	info->max_blocks = 0;
	info->empty_slots = 0;
	info->flags = 0;

	INIT_LIST_HEAD(&info->empty_list);
	INIT_LIST_HEAD(&info->free_list);
	INIT_LIST_HEAD(&info->taken_list);

	return info;
}

/*
 * Destroy a dynamically created remote heap.  Deallocate only if the areas
 * are not static
 */
void rh_destroy(rh_info_t * info)
{
	if ((info->flags & RHIF_STATIC_BLOCK) == 0 && info->block != NULL)
		kfree(info->block);

	if ((info->flags & RHIF_STATIC_INFO) == 0)
		kfree(info);
}

/*
 * Initialize in place a remote heap info block.  This is needed to support
 * operation very early in the startup of the kernel, when it is not yet safe
 * to call kmalloc.
 */
void rh_init(rh_info_t * info, unsigned int alignment, int max_blocks,
	     rh_block_t * block)
{
	int i;
	rh_block_t *blk;

	/* Alignment must be a power of two */
	if ((alignment & (alignment - 1)) != 0)
		return;

	info->alignment = alignment;

	/* Initially everything as empty */
	info->block = block;
	info->max_blocks = max_blocks;
	info->empty_slots = max_blocks;
	info->flags = RHIF_STATIC_INFO | RHIF_STATIC_BLOCK;

	INIT_LIST_HEAD(&info->empty_list);
	INIT_LIST_HEAD(&info->free_list);
	INIT_LIST_HEAD(&info->taken_list);

	/* Add all new blocks to the free list */
	for (i = 0, blk = block; i < max_blocks; i++, blk++)
		list_add(&blk->list, &info->empty_list);
}

/* Attach a free memory region, coalesces regions if adjuscent */
int rh_attach_region(rh_info_t * info, void *start, int size)
{
	rh_block_t *blk;
	unsigned long s, e, m;
	int r;

	/* The region must be aligned */
	s = (unsigned long)start;
	e = s + size;
	m = info->alignment - 1;

	/* Round start up */
	s = (s + m) & ~m;

	/* Round end down */
	e = e & ~m;

	/* Take final values */
	start = (void *)s;
	size = (int)(e - s);

	/* Grow the blocks, if needed */
	r = assure_empty(info, 1);
	if (r < 0)
		return r;

	blk = get_slot(info);
	blk->start = start;
	blk->size = size;
	blk->owner = NULL;

	attach_free_block(info, blk);

	return 0;
}

/* Detatch given address range, splits free block if needed. */
void *rh_detach_region(rh_info_t * info, void *start, int size)
{
	struct list_head *l;
	rh_block_t *blk, *newblk;
	unsigned long s, e, m, bs, be;

	/* Validate size */
	if (size <= 0)
		return ERR_PTR(-EINVAL);

	/* The region must be aligned */
	s = (unsigned long)start;
	e = s + size;
	m = info->alignment - 1;

	/* Round start up */
	s = (s + m) & ~m;

	/* Round end down */
	e = e & ~m;

	if (assure_empty(info, 1) < 0)
		return ERR_PTR(-ENOMEM);

	blk = NULL;
	list_for_each(l, &info->free_list) {
		blk = list_entry(l, rh_block_t, list);
		/* The range must lie entirely inside one free block */
		bs = (unsigned long)blk->start;
		be = (unsigned long)blk->start + blk->size;
		if (s >= bs && e <= be)
			break;
		blk = NULL;
	}

	if (blk == NULL)
		return ERR_PTR(-ENOMEM);

	/* Perfect fit */
	if (bs == s && be == e) {
		/* Delete from free list, release slot */
		list_del(&blk->list);
		release_slot(info, blk);
		return (void *)s;
	}

	/* blk still in free list, with updated start and/or size */
	if (bs == s || be == e) {
		if (bs == s)
			blk->start = (int8_t *)blk->start + size;
		blk->size -= size;

	} else {
		/* The front free fragment */
		blk->size = s - bs;

		/* the back free fragment */
		newblk = get_slot(info);
		newblk->start = (void *)e;
		newblk->size = be - e;

		list_add(&newblk->list, &blk->list);
	}

	return (void *)s;
}

void *rh_alloc(rh_info_t * info, int size, const char *owner)
{
	struct list_head *l;
	rh_block_t *blk;
	rh_block_t *newblk;
	void *start;

	/* Validate size */
	if (size <= 0)
		return ERR_PTR(-EINVAL);

	/* Align to configured alignment */
	size = (size + (info->alignment - 1)) & ~(info->alignment - 1);

	if (assure_empty(info, 1) < 0)
		return ERR_PTR(-ENOMEM);

	blk = NULL;
	list_for_each(l, &info->free_list) {
		blk = list_entry(l, rh_block_t, list);
		if (size <= blk->size)
			break;
		blk = NULL;
	}

	if (blk == NULL)
		return ERR_PTR(-ENOMEM);

	/* Just fits */
	if (blk->size == size) {
		/* Move from free list to taken list */
		list_del(&blk->list);
		blk->owner = owner;
		start = blk->start;

		attach_taken_block(info, blk);

		return start;
	}

	newblk = get_slot(info);
	newblk->start = blk->start;
	newblk->size = size;
	newblk->owner = owner;

	/* blk still in free list, with updated start, size */
	blk->start = (int8_t *)blk->start + size;
	blk->size -= size;

	start = newblk->start;

	attach_taken_block(info, newblk);

	return start;
}

/* allocate at precisely the given address */
void *rh_alloc_fixed(rh_info_t * info, void *start, int size, const char *owner)
{
	struct list_head *l;
	rh_block_t *blk, *newblk1, *newblk2;
	unsigned long s, e, m, bs, be;

	/* Validate size */
	if (size <= 0)
		return ERR_PTR(-EINVAL);

	/* The region must be aligned */
	s = (unsigned long)start;
	e = s + size;
	m = info->alignment - 1;

	/* Round start up */
	s = (s + m) & ~m;

	/* Round end down */
	e = e & ~m;

	if (assure_empty(info, 2) < 0)
		return ERR_PTR(-ENOMEM);

	blk = NULL;
	list_for_each(l, &info->free_list) {
		blk = list_entry(l, rh_block_t, list);
		/* The range must lie entirely inside one free block */
		bs = (unsigned long)blk->start;
		be = (unsigned long)blk->start + blk->size;
		if (s >= bs && e <= be)
			break;
	}

	if (blk == NULL)
		return ERR_PTR(-ENOMEM);

	/* Perfect fit */
	if (bs == s && be == e) {
		/* Move from free list to taken list */
		list_del(&blk->list);
		blk->owner = owner;

		start = blk->start;
		attach_taken_block(info, blk);

		return start;

	}

	/* blk still in free list, with updated start and/or size */
	if (bs == s || be == e) {
		if (bs == s)
			blk->start = (int8_t *)blk->start + size;
		blk->size -= size;

	} else {
		/* The front free fragment */
		blk->size = s - bs;

		/* The back free fragment */
		newblk2 = get_slot(info);
		newblk2->start = (void *)e;
		newblk2->size = be - e;

		list_add(&newblk2->list, &blk->list);
	}

	newblk1 = get_slot(info);
	newblk1->start = (void *)s;
	newblk1->size = e - s;
	newblk1->owner = owner;

	start = newblk1->start;
	attach_taken_block(info, newblk1);

	return start;
}

int rh_free(rh_info_t * info, void *start)
{
	rh_block_t *blk, *blk2;
	struct list_head *l;
	int size;

	/* Linear search for block */
	blk = NULL;
	list_for_each(l, &info->taken_list) {
		blk2 = list_entry(l, rh_block_t, list);
		if (start < blk2->start)
			break;
		blk = blk2;
	}

	if (blk == NULL || start > (blk->start + blk->size))
		return -EINVAL;

	/* Remove from taken list */
	list_del(&blk->list);

	/* Get size of freed block */
	size = blk->size;
	attach_free_block(info, blk);

	return size;
}

int rh_get_stats(rh_info_t * info, int what, int max_stats, rh_stats_t * stats)
{
	rh_block_t *blk;
	struct list_head *l;
	struct list_head *h;
	int nr;

	switch (what) {

	case RHGS_FREE:
		h = &info->free_list;
		break;

	case RHGS_TAKEN:
		h = &info->taken_list;
		break;

	default:
		return -EINVAL;
	}

	/* Linear search for block */
	nr = 0;
	list_for_each(l, h) {
		blk = list_entry(l, rh_block_t, list);
		if (stats != NULL && nr < max_stats) {
			stats->start = blk->start;
			stats->size = blk->size;
			stats->owner = blk->owner;
			stats++;
		}
		nr++;
	}

	return nr;
}

int rh_set_owner(rh_info_t * info, void *start, const char *owner)
{
	rh_block_t *blk, *blk2;
	struct list_head *l;
	int size;

	/* Linear search for block */
	blk = NULL;
	list_for_each(l, &info->taken_list) {
		blk2 = list_entry(l, rh_block_t, list);
		if (start < blk2->start)
			break;
		blk = blk2;
	}

	if (blk == NULL || start > (blk->start + blk->size))
		return -EINVAL;

	blk->owner = owner;
	size = blk->size;

	return size;
}

void rh_dump(rh_info_t * info)
{
	static rh_stats_t st[32];	/* XXX maximum 32 blocks */
	int maxnr;
	int i, nr;

	maxnr = sizeof(st) / sizeof(st[0]);

	printk(KERN_INFO
	       "info @0x%p (%d slots empty / %d max)\n",
	       info, info->empty_slots, info->max_blocks);

	printk(KERN_INFO "  Free:\n");
	nr = rh_get_stats(info, RHGS_FREE, maxnr, st);
	if (nr > maxnr)
		nr = maxnr;
	for (i = 0; i < nr; i++)
		printk(KERN_INFO
		       "    0x%p-0x%p (%u)\n",
		       st[i].start, (int8_t *) st[i].start + st[i].size,
		       st[i].size);
	printk(KERN_INFO "\n");

	printk(KERN_INFO "  Taken:\n");
	nr = rh_get_stats(info, RHGS_TAKEN, maxnr, st);
	if (nr > maxnr)
		nr = maxnr;
	for (i = 0; i < nr; i++)
		printk(KERN_INFO
		       "    0x%p-0x%p (%u) %s\n",
		       st[i].start, (int8_t *) st[i].start + st[i].size,
		       st[i].size, st[i].owner != NULL ? st[i].owner : "");
	printk(KERN_INFO "\n");
}

void rh_dump_blk(rh_info_t * info, rh_block_t * blk)
{
	printk(KERN_INFO
	       "blk @0x%p: 0x%p-0x%p (%u)\n",
	       blk, blk->start, (int8_t *) blk->start + blk->size, blk->size);
}


text:
'use strict';
let path = require('path');
let webpack = require('webpack');

module.exports = {
  entry: require('./webpack/entry'),

  context: path.join(process.cwd(), 'src'),

  output: require('./webpack/output'),

  module: require('./webpack/module'),

  plugins: require('./webpack/plugins').concat([
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      output: {
        comments: false
      },
      sourceMap: true
    })
  ]),

  resolve: require('./webpack/resolve'),

  stats: 'errors-only',

  devtool: 'source-map'
};


text:
<?php

namespace Frontend\OrderBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ShippingOption
 *
 * @ORM\Table(name="shipping_option")
 * @ORM\Entity
 */
class ShippingOption
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=60, nullable=false)
     */
    private $name;

    /**
     * Set name
     *
     * @param string $name
     * @return ShippingOption
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

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

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


text:
package com.google.android.gms.internal;

import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;

public abstract interface p extends IInterface
{
  public abstract boolean a(boolean paramBoolean);

  public abstract void b(String paramString, boolean paramBoolean);

  public abstract String e(String paramString);

  public abstract String getId();

  public static abstract class a extends Binder
    implements p
  {
    public static p b(IBinder paramIBinder)
    {
      if (paramIBinder == null)
        return null;
      IInterface localIInterface = paramIBinder.queryLocalInterface("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
      if ((localIInterface != null) && ((localIInterface instanceof p)))
        return (p)localIInterface;
      return new a(paramIBinder);
    }

    public boolean onTransact(int paramInt1, Parcel paramParcel1, Parcel paramParcel2, int paramInt2)
    {
      switch (paramInt1)
      {
      default:
        break;
      case 1598968902:
        paramParcel2.writeString("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
        return true;
      case 1:
        paramParcel1.enforceInterface("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
        String str3 = getId();
        paramParcel2.writeNoException();
        paramParcel2.writeString(str3);
        return true;
      case 2:
        paramParcel1.enforceInterface("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
        boolean bool2;
        if (paramParcel1.readInt() != 0)
          bool2 = true;
        else
          bool2 = false;
        boolean bool3 = a(bool2);
        paramParcel2.writeNoException();
        int i;
        if (bool3)
          i = 1;
        else
          i = 0;
        paramParcel2.writeInt(i);
        return true;
      case 3:
        paramParcel1.enforceInterface("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
        String str2 = e(paramParcel1.readString());
        paramParcel2.writeNoException();
        paramParcel2.writeString(str2);
        return true;
      case 4:
        paramParcel1.enforceInterface("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
        String str1 = paramParcel1.readString();
        boolean bool1;
        if (paramParcel1.readInt() != 0)
          bool1 = true;
        else
          bool1 = false;
        b(str1, bool1);
        paramParcel2.writeNoException();
        return true;
      }
      return super.onTransact(paramInt1, paramParcel1, paramParcel2, paramInt2);
    }

    static class a
      implements p
    {
      private IBinder dU;

      a(IBinder paramIBinder)
      {
        this.dU = paramIBinder;
      }

      public boolean a(boolean paramBoolean)
      {
        Parcel localParcel1 = Parcel.obtain();
        Parcel localParcel2 = Parcel.obtain();
        while (true)
        {
          try
          {
            localParcel1.writeInterfaceToken("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
            if (paramBoolean)
            {
              i = 1;
              localParcel1.writeInt(i);
              this.dU.transact(2, localParcel1, localParcel2, 0);
              localParcel2.readException();
              boolean bool;
              if (localParcel2.readInt() != 0)
                bool = true;
              else
                bool = false;
              return bool;
            }
          }
          finally
          {
            localParcel2.recycle();
            localParcel1.recycle();
          }
          int i = 0;
        }
      }

      public IBinder asBinder()
      {
        return this.dU;
      }

      public void b(String paramString, boolean paramBoolean)
      {
        Parcel localParcel1 = Parcel.obtain();
        Parcel localParcel2 = Parcel.obtain();
        while (true)
        {
          try
          {
            localParcel1.writeInterfaceToken("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
            localParcel1.writeString(paramString);
            if (paramBoolean)
            {
              i = 1;
              localParcel1.writeInt(i);
              this.dU.transact(4, localParcel1, localParcel2, 0);
              localParcel2.readException();
              return;
            }
          }
          finally
          {
            localParcel2.recycle();
            localParcel1.recycle();
          }
          int i = 0;
        }
      }

      public String e(String paramString)
      {
        Parcel localParcel1 = Parcel.obtain();
        Parcel localParcel2 = Parcel.obtain();
        try
        {
          localParcel1.writeInterfaceToken("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
          localParcel1.writeString(paramString);
          this.dU.transact(3, localParcel1, localParcel2, 0);
          localParcel2.readException();
          String str = localParcel2.readString();
          return str;
        }
        finally
        {
          localParcel2.recycle();
          localParcel1.recycle();
        }
      }

      public String getId()
      {
        Parcel localParcel1 = Parcel.obtain();
        Parcel localParcel2 = Parcel.obtain();
        try
        {
          localParcel1.writeInterfaceToken("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
          this.dU.transact(1, localParcel1, localParcel2, 0);
          localParcel2.readException();
          String str = localParcel2.readString();
          return str;
        }
        finally
        {
          localParcel2.recycle();
          localParcel1.recycle();
        }
      }
    }
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.google.android.gms.internal.p
 * JD-Core Version:    0.6.2
 */


text:
<?php

/**
 * @namespace
 */
namespace Zend\Form\Element;

/**
 * Radio form element
 *
 * @uses       \Zend\Form\Element\Multi
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
class Radio extends Multi
{
    /**
     * Use formRadio view helper by default
     * @var string
     */
    public $helper = 'formRadio';

    /**
     * Load default decorators
     *
     * Disables "for" attribute of label if label decorator enabled.
     *
     * @return void
     */
    public function loadDefaultDecorators()
    {
        if ($this->loadDefaultDecoratorsIsDisabled()) {
            return $this;
        }
        parent::loadDefaultDecorators();
        $this->addDecorator('Label', array('tag' => 'dt',
                                           'disableFor' => true));
        return $this;
    }
}


text:
module Travis::API::V3
  class Queries::Requests < Query
    def find(repository)
      relation = repository.requests.includes(:commit)
      relation.includes(:yaml_config) if includes?('request.yaml_config')
      relation.order(id: :desc)
    end

    def count(repository, time_frame)
      find(repository).
        where(event_type: 'api'.freeze).
        where('created_at > ?'.freeze, time_frame.ago).count
    end
  end
end


text:
package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args)
   {
       int firstInt, secondInt;
       System.out.println("Enter two integers ");
       Scanner in = new Scanner(System.in);

       firstInt = in.nextInt();
       secondInt = in.nextInt();

       if ( firstInt > secondInt )
           System.out.println("First number is largest.");
       else if ( secondInt > firstInt )
           System.out.println("Second number is largest.");
       else if ( firstInt == secondInt )
           System.out.println("Entered numbers are equal.");
    }
}


text:
class FtaGuidewayType < ApplicationRecord

  belongs_to :fta_asset_class
  has_many :fta_type_asset_subtype_mappings, as: :fta_type
  has_many :asset_subtypes, through: :fta_type_asset_subtype_mappings

  # All types that are available
  scope :active, -> { where(:active => true) }
  scope :sorted, -> { order(:sort_order) }

  def to_s
    name
  end

end


text:
package com.blackypaw.mc.i18n;

import com.blackypaw.mc.i18n.config.PluginConfig;
import com.blackypaw.mc.i18n.event.PlayerSetLanguageEvent;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;

import java.sql.SQLException;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author BlackyPaw
 * @version 1.0
 */
class I18NBungeeCordImpl implements I18N<UUID> {

	private final Logger logger;

	private Locale               fallbackLocale;
	private LocaleResolver<UUID> localeResolver;
	private Map<UUID, Locale>    localeStorage;
	private boolean              shouldUseFallbackLocale;

	private Set<PendingConnection> watchedConnections;

	I18NBungeeCordImpl( Logger logger ) {
		this.logger = logger;
		this.watchedConnections = new HashSet<>();
	}

	@Override
	public boolean isInjectionSupported() {
		// Injection is not supported on BungeeCord:
		return false;
	}

	@Override
	public Localizer createLocalizer( TranslationStorage storage ) {
		return new LocalizerBungeeCordImpl( storage );
	}

	@Override
	public Locale getLocale( UUID key ) {
		return this.localeStorage.get( key );
	}

	@Override
	public boolean trySetLocale( UUID key, Locale locale ) {
		if ( this.localeResolver.trySetPlayerLocale( key, locale ) ) {
			this.storeLocale( key, locale );

			// Call a player set language event so that other plugins can resend
			// scoreboards, signs, etc.:
			ProxiedPlayer player = ProxyServer.getInstance().getPlayer( key );
			if ( player != null ) {
				PlayerSetLanguageEvent event = new PlayerSetLanguageEvent( player, locale );
				ProxyServer.getInstance().getPluginManager().callEvent( event );
			}
			return true;
		}
		return false;
	}

	@Override
	public void setLocaleResolver( LocaleResolver<UUID> resolver ) {
		this.destroyLocaleResolver();
		this.localeResolver = resolver;
	}

	@Override
	public boolean shouldUseFallbackLocale() {
		return this.shouldUseFallbackLocale;
	}

	@Override
	public Locale getFallbackLocale() {
		return this.fallbackLocale;
	}

	public boolean initializeFromConfig( PluginConfig config ) {
		this.fallbackLocale = new Locale( config.getFallbackLocale() );
		this.localeStorage = new ConcurrentHashMap<>();
		this.shouldUseFallbackLocale = config.isUseFallbackLocale();

		this.logger.info( "Set fallback locale to " + ISO639.getName( this.fallbackLocale.getLanguage() ) );

		switch ( config.getDefaultLocaleResolver().toUpperCase() ) {
			case "CONSTANT":
				this.localeResolver = new ConstantLocaleResolver<>( this.fallbackLocale );
				break;
			case "DATABASE":
				try {
					this.localeResolver = new DatabaseLocaleResolver( this, config.getDbHost(), config.getDbPort(), config
							.getDbUser(), config.getDbPassword(), config.getDbName(), config.getDbPrefix() );
				} catch ( SQLException e ) {
					this.logger.log( Level.SEVERE, "Failed to connect to MySQL database", e );
					return false;
				}
				break;
			default:
				this.logger.log( Level.SEVERE, "Unknown locale resolver '" + config.getDefaultLocaleResolver() + "'; please check the documentation for your version for supported values" );
				return false;
		}

		return true;
	}

	public void close() {
		this.destroyLocaleResolver();
	}

	LocaleResolver<UUID> getLocaleResolver() {
		return this.localeResolver;
	}

	void storeLocale( UUID key, Locale locale ) {
		this.localeStorage.put( key, locale );
	}

	void watchConnection( PendingConnection connection ) {
		synchronized ( this.watchedConnections ) {
			this.watchedConnections.add( connection );
		}
	}

	void unwatchConnection( PendingConnection connection ) {
		synchronized ( this.watchedConnections ) {
			this.watchedConnections.remove( connection );
		}
	}

	void checkWatchedConnections() {
		synchronized ( this.watchedConnections ) {
			Set<PendingConnection> removable = new HashSet<>();

			for ( PendingConnection connection : this.watchedConnections ) {
				if ( !connection.isConnected() ) {
					removable.add( connection );
					this.unstoreLocale( connection.getUniqueId() );
				}
			}

			this.watchedConnections.removeAll( removable );
		}
	}

	void unstoreLocale( UUID key ) {
		this.localeStorage.remove( key );
	}

	private void destroyLocaleResolver() {
		if ( this.localeResolver != null ) {
			if ( this.localeResolver instanceof AutoCloseable ) {
				try {
					( (AutoCloseable) this.localeResolver ).close();
				} catch ( Exception e ) {
					this.logger.log( Level.WARNING, "Failed to close AutoCloseable locale resolver", e );
				}
			}
			this.localeResolver = null;
		}
	}

}


text:
package com.edgar.module.sys.service;

import com.edgar.core.repository.Pagination;
import com.edgar.core.repository.QueryExample;
import com.edgar.module.sys.repository.domain.SysUser;
import com.edgar.module.sys.repository.domain.SysUserProfile;
import com.edgar.module.sys.repository.domain.SysUserRole;
import com.edgar.module.sys.vo.ChangePasswordVo;
import com.edgar.module.sys.vo.SysUserRoleVo;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 用户的业务逻辑接口
 *
 * @author Edgar Zhang
 * @version 1.0
 */
@Validated
public interface SysUserService {
    /**
     * 新增用户
     *
     * @param sysUser 用户
     */
    void save(@NotNull SysUserRoleVo sysUser);

    /**
     * 根据用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户
     */
    SysUser get(@Min(1) int userId);

    /**
     * 分页查询用户
     *
     * @param example  查询条件
     * @param page     当前页
     * @param pageSize 每页记录数
     * @return 用户的分页类
     */
    @NotNull
    Pagination<SysUser> pagination(@NotNull QueryExample example,
                                   @Min(1) int page, @Min(1) int pageSize);

    /**
     * 修改用户
     *
     * @param sysUser 用户
     */
    void update(@NotNull SysUserRoleVo sysUser);

    /**
     * 事件用户ID和时间戳删除用户
     *
     * @param userId      用户ID
     * @param updatedTime 时间戳
     */
    void deleteWithLock(@Min(1) int userId, long updatedTime);

    /**
     * 检查用户名是否存在
     *
     * @param username 用户名
     * @return 如果存在,返回false
     */
    boolean checkUsername(@NotNull String username);

    /**
     * 根据用户ID,查询用户角色
     *
     * @param userId 用户ID
     * @return 用户角色的集合
     */
    List<SysUserRole> getRoles(@Min(1) int userId);

    /**
     * 根据用户名查询用户列表
     *
     * @param username 用户名
     * @return 用户的集合
     */
    List<SysUser> queryByUsername(String username);

    /**
     * 查询用户的个人偏好设置
     *
     * @param userId 用户ID
     * @return 个人偏好设置
     */
    SysUserProfile getProfile(int userId);

    /**
     * 更新用户的profile
     *
     * @param profile 用户偏好
     */
    void updateProfile(SysUserProfile profile);

    /**
     * 修改用户密码
     *
     * @param changePasswordVo 密码对象
     */
    void updatePassword(ChangePasswordVo changePasswordVo);

    /**
     * 创建管理员角色的用户
     *
     * @param sysUser 用户
     */
    void saveAdminUser(SysUser sysUser);

}


text:
Question

Analysis

Code

Please in backup code here!


text:
{% extends "header.html" %}
{% block body %}

<link rel="stylesheet" href="../static/css/index.css">

    <form class="form-inline" method="post" id="submitUrlForm">

        <input type="text" class="form-control" id="inputUrlField" name="url" placeholder="Enter Insta/Flickr Pic URL" required>

      <button class="btn btn-default" type="submit" name="submitUrl">Submit URL</button>
    </form>
    {% if downloadUrl %}

        <button type="button" class="btn btn-success btn-lg" data-toggle="modal" data-target="#myModal" id="saveImageButton">
          Save Image
        </button>
        <button class="btn btn-warning" id="reportImageButton">Report Image</button>

      {% endif %}

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Download Pic ?

          Hit Save to Download the Pic!

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary" onclick="CloseModalOnSave()">Save changes</button>

      Total Download Count : {{ count}}

  {% endblock %}


text:
unset GREP_OPTIONS GREP_COLOR GREP_COLORS

if   command -v md5sum > /dev/null; then md5sum="md5sum"
elif command -v md5 > /dev/null;    then md5sum="md5 -r"
fi

if   command -v sha1sum > /dev/null; then sha1sum="sha1sum"
elif command -v sha1 > /dev/null;    then sha1sum="sha1 -r"
elif command -v shasum > /dev/null;  then sha1sum="shasum"
fi

if   command -v sha256sum > /dev/null; then sha256sum="sha256sum"
elif command -v sha256 > /dev/null;    then sha256sum="sha256 -r"
elif command -v shasum > /dev/null;    then sha256sum="shasum -a 256"
fi

if   command -v sha512sum > /dev/null; then sha512sum="sha512sum"
elif command -v sha512 > /dev/null;    then sha512sum="sha512 -r"
elif command -v shasum > /dev/null;    then sha512sum="shasum -a 512"
fi

function lookup_checksum()
{
	local checksums="$1"
	local file="${2##*/}"

	if [[ ! -f "$checksums" ]]; then
		return 1
	fi

	local output="$(grep "  $file" "$checksums")"

	echo -n "${output%% *}"
}

function compute_checksum()
{
	local algorithm="$1"
	local file="$2"
	local program

	case "$algorithm" in
		md5)	program="$md5sum" ;;
		sha1)	program="$sha1sum" ;;
		sha256)	program="$sha256sum" ;;
		sha512)	program="$sha512sum" ;;
		*)	return 1 ;;
	esac

	if [[ -z "$program" ]]; then
		error "could not find $algorithm checksum utility"
		return 1
	fi

	local output="$($program "$file")"

	echo -n "${output%% *}"
}

function verify_checksum()
{
	local file="$1"
	local algorithm="$2"
	local expected_checksum="$3"

	if [[ -z "$expected_checksum" ]]; then
		warn "No $algorithm checksum for $file"
		return
	fi

	local actual_checksum="$(compute_checksum "$algorithm" "$file")"

	if [[ "$actual_checksum" != "$expected_checksum" ]]; then
		error "Invalid $algorithm checksum for $file"
		error "  expected: $expected_checksum"
		error "  actual:   $actual_checksum"
		return 1
	fi
}


text:
package com.wjiec.learn.lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ReentrantTest {

    private static final int THREAD_COUNT = 10;
    private static final Reentrant lock = new Reentrant();
    private static final CountDownLatch start = new CountDownLatch(1);
    private static final CountDownLatch thread = new CountDownLatch(THREAD_COUNT);

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < THREAD_COUNT; i++) {
            new Thread(new Worker()).start();
        }

        start.countDown();
        thread.await();
    }

    static class Worker implements Runnable {

        @Override
        public void run() {
            try {
                start.await();
            } catch (InterruptedException ignored) {}

            lock.lock();
            try {
                System.out.printf("%s locking...\n", Thread.currentThread().getName());
                printInfo();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

            thread.countDown();
        }

        private void printInfo() throws InterruptedException {
            lock.lock();
            try {
                System.out.printf("%s: printInfo before\n", Thread.currentThread().getName());
                TimeUnit.MILLISECONDS.sleep((int)(Math.random() * 1000));
                System.out.printf("%s: printInfo after\n", Thread.currentThread().getName());
            } finally {
                lock.unlock();
            }
        }

    }

}


text:
begin
  if Rails.application.routes.default_url_options[:host].blank? and AppSetting.default_host_exists?
    host = AppSetting.default_host
    Rails.logger.info "[SUCCESS] Setting default_url_options[:host] = '#{host}'"
    Rails.application.routes.default_url_options[:host] = host
  end
rescue ActiveRecord::NoDatabaseError
  Rails.logger.error "[ERROR] Failed to set default_host because: ActiveRecord::NoDatabaseError. If this is the first deploy, this is expected and will be fixed after the database is created."
rescue ActiveRecord::StatementInvalid
  Rails.logger.error "[ERROR] Failed to set default_host because: ActiveRecord::StatementInvalid. If this is the first deploy, this is expected and will be fixed after the database is migrated."
end


text:
package com.yattatech.dao;

import com.yattatech.domain.City;
import com.yattatech.domain.FedUnit;
import com.yattatech.domain.Neighbor;
import com.yattatech.domain.ZipcodeSearch;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A simple dao class responsible for inserting/updating/deleting
 * shalom data.
 *
 * @author Adriano Braga Alencar (adrianobragaalencar@gmail.com)
 *
 */
public final class DaoManager {

    private static final Logger LOGGER          = Logger.getLogger("DaoManager");
    private static final Neighbor NULL_NEIGHBOR = new Neighbor(-1, -1, "");
    private final String url;
    private List<FedUnit> fedUnits;
    private List<String> works;
    private static final String ZIPCODE_SEARCH = "select s.street_name,"              +
                                                         "s.zipcode,"                 +
                                                         "n.cd_neighbor,"             +
                                                         "c.cd_city,"                 +
                                                         "u.cd_uf"                    +
                                                 " from street s,"                    +
                                                       "neighbor n,"                  +
                                                       "city c,"                      +
                                                       "uf u"                         +
                                                 " where s.zipcode = %s and"          +
                                                 " n.cd_neighbor = s.cd_neighbor and" +
                                                 " c.cd_city = n.cd_city and"         +
                                                 " u.cd_uf = c.cd_uf";

    public DaoManager() {
        url = "jdbc:sqlite::resource:" + getClass().getResource("/shalom.db").toString();
        System.out.println(url);
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException cnfe) {
            LOGGER.log(Level.SEVERE, cnfe.getMessage());
            throw new RuntimeException(cnfe);
        }
    }

    public List<FedUnit> getFederativeUnits() {
        if (fedUnits == null) {
            fedUnits = new ArrayList<FedUnit>();
            Connection conn  = null;
            Statement statm  = null;
            ResultSet result = null;
            try {
                conn   = getConnection();
                statm  = conn.createStatement();
                result = statm.executeQuery("select * from uf");
                while (result.next()) {
                    final int code    = result.getInt("cd_uf");
                    final String desc = result.getString("uf_desc");
                    fedUnits.add(new FedUnit(code, desc));
                }
            } catch (SQLException sqle) {
                LOGGER.log(Level.SEVERE, sqle.getMessage());
            } finally {
                closeResultSet(result);
                closeStatement(statm);
                closeConnection(conn);
            }
            fedUnits = Collections.unmodifiableList(fedUnits);
        }
        return fedUnits;
    }

    public List<City> getCitiesByFedUnit(FedUnit fedUnit) {

        List<City> cities = new ArrayList<City>();
        Connection conn   = null;
        Statement statm   = null;
        ResultSet result  = null;
        try {
            conn   = getConnection();
            statm  = conn.createStatement();
            result = statm.executeQuery("select * from city where cd_uf = " + fedUnit.getCode());
            while (result.next()) {
                final int codeUF  = result.getInt("cd_uf");
                final int code    = result.getInt("cd_city");
                final String name = result.getString("city_name");
                cities.add(new City(codeUF, code, name));
            }
        } catch (SQLException sqle) {
            LOGGER.log(Level.SEVERE, sqle.getMessage());
        } finally {
            closeResultSet(result);
            closeStatement(statm);
            closeConnection(conn);
            return cities;
        }
    }

    public List<Neighbor> getNeighborsByCity(City city) {
        List<Neighbor> neighbors = new ArrayList<Neighbor>();
        Connection conn          = null;
        Statement statm          = null;
        ResultSet result         = null;
        try {
            neighbors.add(NULL_NEIGHBOR);
            conn   = getConnection();
            statm  = conn.createStatement();
            result = statm.executeQuery("select * from neighbor where cd_city = " + city.getCode());
            while (result.next()) {
                final int codeCity = result.getInt("cd_city");
                final int code     = result.getInt("cd_neighbor");
                final String name  = result.getString("neighbor_name");
                neighbors.add(new Neighbor(codeCity, code, name));
            }
        } catch (SQLException sqle) {
            LOGGER.log(Level.SEVERE, sqle.getMessage());
        } finally {
            closeResultSet(result);
            closeStatement(statm);
            closeConnection(conn);
            return neighbors;
        }
    }

    public ZipcodeSearch searchByZipcode(String zipcode) {
        ZipcodeSearch zipcodeSearch = null;
        Connection conn             = null;
        Statement statm             = null;
        ResultSet result            = null;
        try {
            conn   = getConnection();
            statm  = conn.createStatement();
            System.out.println(String.format(ZIPCODE_SEARCH, zipcode));
            result = statm.executeQuery(String.format(ZIPCODE_SEARCH, zipcode));
            if (result.next()) {
                final String streetName = result.getString("street_name");
                final String zipCode    = result.getString("zipcode");
                final int codeNeighbor  = result.getInt("cd_neighbor");
                final int codeCity      = result.getInt("cd_city");
                final int codeFU        = result.getInt("cd_uf");
                zipcodeSearch           = new ZipcodeSearch(streetName, zipCode, codeNeighbor, codeCity, codeFU);
            }
        } catch (SQLException sqle) {
            LOGGER.log(Level.SEVERE, sqle.getMessage());
        } finally {
            closeResultSet(result);
            closeStatement(statm);
            closeConnection(conn);
            return zipcodeSearch;
        }
    }

    public List<String> getWorksDescription() {
        if (works != null) {
            return works;
        }
        works            = new ArrayList<String>();
        Connection conn  = null;
        Statement statm  = null;
        ResultSet result = null;
        try {
            conn   = getConnection();
            statm  = conn.createStatement();
            result = statm.executeQuery("select desc from work");
            while (result.next()) {
                works.add(result.getString("desc"));
            }
        } catch (SQLException sqle) {
            LOGGER.log(Level.SEVERE, sqle.getMessage());
        } finally {
            closeResultSet(result);
            closeStatement(statm);
            closeConnection(conn);
            return works;
        }
    }

    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url);
    }

    private void closeConnection(Connection conn) {
        try {
            if (conn != null) {
               conn.close();
            }
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.getMessage());
        }
    }

    private void closeStatement(Statement statm) {
        try {
            if (statm != null) {
               statm.close();
            }
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.getMessage());
        }
    }

    private void closeResultSet(ResultSet result) {
        try {
            if (result != null) {
               result.close();
            }
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.getMessage());
        }
    }
}


text:
package com.jk.faces.config;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

import org.omg.IOP.ServiceContext;

import com.jk.faces.tags.JKTagWrapper;
import com.jk.faces.util.JKJsfUtil;
import com.jk.util.JKConversionUtil;
import com.jk.util.JKIOUtil;
import com.jk.util.JKObjectUtil;
import com.jk.util.logging.JKLogger;
import com.jk.util.logging.JKLoggerFactory;
import com.jk.util.xml.JKXmlHandler;
import com.jk.web.util.JKWebUtil;
import com.sun.faces.application.ApplicationAssociate;
import com.sun.faces.facelets.compiler.Compiler;
import com.sun.faces.facelets.tag.AbstractTagLibrary;

// TODO: Auto-generated Javadoc
/**
 * The Class JKFacesConfigurations.
 *
 * @author Jalal Kiswani
 */
@XmlRootElement(name = "jk-faces")
@XmlAccessorType(XmlAccessType.FIELD)
public class JKFacesConfigurations {

	/** The Constant META_INF_JK_FACES_CONFIG_XML. */
	private static final String META_INF_JK_FACES_CONFIG_XML = "/META-INF/jk-faces-config.xml";

	/** The logger. */
	static JKLogger logger = JKLoggerFactory.getLogger(JKFacesConfigurations.class);

	/** The instance. */
	private static JKFacesConfigurations instance;

	/**
	 * Gets the single instance of JKFacesConfigurations.
	 *
	 * @return single instance of JKFacesConfigurations
	 */
	public static JKFacesConfigurations getInstance() {
		if (instance == null) {
			instance = new JKFacesConfigurations();
			instance = JKXmlHandler.getInstance().parse(JKIOUtil.getInputStream(META_INF_JK_FACES_CONFIG_XML), JKFacesConfigurations.class,
					JKNamespace.class, JKTagMapping.class);

		}
		return instance;
	}

	// @XmlTransient
	// Map<String, List<String>> publicNameSpaces;

	/**
	 * The main method.
	 *
	 * @param args
	 *            the arguments
	 */
	public static void main(final String[] args) {
		final JKFacesConfigurations test = getInstance();
		final List<JKNamespace> namespaces = test.getNamespaces();
		for (final JKNamespace ns : namespaces) {
			System.out.println(ns.getPrefix() + ", " + ns.getUrl());
		}
		System.out.println("----------------");
		final List<JKTagMapping> tagMapping2 = test.getTagMapping();
		for (final JKTagMapping tagMapping : tagMapping2) {
			System.out.println(JKObjectUtil.toString(tagMapping));
		}
		System.out.println("Done");
	}

	/** The namespaces. */
	@XmlElementWrapper(name = "name-spaces")
	@XmlElement(name = "namespace")
	List<JKNamespace> namespaces;

	/** The tag mapping. */
	@XmlElementWrapper(name = "tags-mapping")
	@XmlElement(name = "tag")
	List<JKTagMapping> tagMapping;

	/** The decorate. */
	private Boolean decorate;

	/** The decorate mapping. */
	private Boolean decorateMapping;

	/** The decorate fix links. */
	private Boolean decorateFixLinks;

	/**
	 * After unmarshal.
	 *
	 * @param u the u
	 * @param parent the parent
	 */
	// JAXb callback
	void afterUnmarshal(final Unmarshaller u, final Object parent) {
		loadAllNamesSpacesFromJsfContainer();
		Collections.sort(this.tagMapping);
		System.err.println("---------------------------------------------");
		logger.debug("All tags mappings:");
		System.err.println("---------------------------------------------");
		for (final JKTagMapping mapping : this.tagMapping) {
			logger.debug(JKObjectUtil.toString(mapping));
		}
	}

	/**
	 * Find tag mapping.
	 *
	 * @param wrapper
	 *            the wrapper
	 * @return the tag mapping
	 */
	public JKTagMapping findTagMapping(final JKTagWrapper wrapper) {
		// Add caching
		logger.debug("Find mapping to tag ".concat(wrapper.getqName()));
		for (final JKTagMapping mapping : this.tagMapping) {
			if (mapping.getSourceQName().equals(wrapper.getqName())) {
				if (mapping.getAttributeName() == null) {
					return mapping;
				} else {
					final String value = wrapper.getAttributeValue(mapping.getAttributeName());
					if (value != null && value.equals(mapping.getAttributeValue())) {
						return mapping;
					}
				}
			}
		}
		return null;
	}

	/**
	 * Find tag mapping.
	 *
	 * @param tagName
	 *            the tag name
	 * @return the JK tag mapping
	 */
	public JKTagMapping findTagMapping(final String tagName) {
		for (final JKTagMapping mapping : this.tagMapping) {
			if (mapping.getSourceQName().equals(tagName)) {
				return mapping;
			}
		}
		return null;
	}

	/**
	 * Gets the namespace by letter.
	 *
	 * @param namespaceLetter
	 *            the namespace letter
	 * @return the namespace by letter
	 */
	public JKNamespace getNamespaceByLetter(final String namespaceLetter) {
		for (final JKNamespace namespace : this.namespaces) {
			if (namespace.getLetter().equals(namespaceLetter)) {
				return namespace;
			}
		}
		return null;
	}

	/**
	 * Gets the name space by url.
	 *
	 * @param url
	 *            the url
	 * @param create
	 *            the create
	 * @return the name space by url
	 */
	public JKNamespace getNameSpaceByUrl(final String url, final boolean create) {
		logger.debug("getNameSpaceByUrl :".concat(url));
		for (final JKNamespace namespace : this.namespaces) {
			if (namespace.getUrl().equals(url)) {
				return namespace;
			}
		}
		// if not found , add?
		if (create) {
			logger.debug("not found , create namespace ");
			final JKNamespace namespace = new JKNamespace(url);
			this.namespaces.add(namespace);
			return namespace;
		}
		return null;
	}

	/**
	 * Gets the namespaces.
	 *
	 * @return the namespaces
	 */
	public List<JKNamespace> getNamespaces() {
		return this.namespaces;
	}

	/**
	 * Gets the tag mapping.
	 *
	 * @return the tag mapping
	 */
	public List<JKTagMapping> getTagMapping() {
		return this.tagMapping;
	}

	/**
	 * Load all names spaces from jsf container.
	 */
	protected void loadAllNamesSpacesFromJsfContainer() {
		logger.debug("loadAllNamesSpacesFromJsfContainer....");
		// HashMap<String, Object> publicNameSpaces = new HashMap<>();
		final ApplicationAssociate currentInstance = ApplicationAssociate.getCurrentInstance();
		if (currentInstance != null) {
			final Compiler instance = currentInstance.getCompiler();
			logger.debug("loading libraries from JSF compiler");
			final List libraries = (List) JKObjectUtil.getFieldValue(instance, "libraries");
			for (final Object libObject : libraries) {
				if (libObject instanceof AbstractTagLibrary) {
					final AbstractTagLibrary library = (AbstractTagLibrary) libObject;
					logger.debug(String.format("fetching %s library", library.getNamespace()));
					// load components using reflection
					final Map map = (Map) JKObjectUtil.getFieldValue(library, "factories");
					final JKNamespace namespace = getNameSpaceByUrl(library.getNamespace(), true);

					final Set keySet = map.keySet();
					for (final Object object : keySet) {
						// add tag names
						final String localName = object.toString();
						final String qName = namespace.getLetter().concat(":").concat(localName);
						// check if mapping already exists
						if (findTagMapping(qName) == null) {
							final JKTagMapping mapping = new JKTagMapping(localName, qName, namespace);
							this.tagMapping.add(mapping);
						}
					}
				}
			}
		}
	}

	/**
	 * Sets the namespaces.
	 *
	 * @param namespaces
	 *            the new namespaces
	 */
	public void setNamespaces(final List<JKNamespace> namespaces) {
		this.namespaces = namespaces;
	}

	/**
	 * Sets the tag mapping.
	 *
	 * @param tagMapping
	 *            the new tag mapping
	 */
	public void setTagMapping(final List<JKTagMapping> tagMapping) {
		this.tagMapping = tagMapping;
	}

	/**
	 * Checks if is decorate.
	 *
	 * @return true, if is decorate
	 */
	public boolean isDecorate() {
		if (decorate == null) {
			ServletContext context = JKJsfUtil.getServletContext();
			decorate = JKConversionUtil.toBoolean(context.getInitParameter("jk.decorate"), true);
		}
		return decorate;
	}

	/**
	 * Checks if is decorate mapping.
	 *
	 * @return true, if is decorate mapping
	 */
	public boolean isDecorateMapping() {
		if (decorateMapping == null) {
			ServletContext context = JKJsfUtil.getServletContext();
			decorateMapping = JKConversionUtil.toBoolean(context.getInitParameter("jk.decorate.mapping"), true);
		}
		return decorateMapping;
	}

	/**
	 * Checks if is decorate fix links.
	 *
	 * @return true, if is decorate fix links
	 */
	public boolean isDecorateFixLinks() {
		if (decorateFixLinks == null) {
			ServletContext context = JKJsfUtil.getServletContext();
			decorateFixLinks = JKConversionUtil.toBoolean(context.getInitParameter("jk.decorate.fixlinks"), true);
		}
		return decorateFixLinks;
	}

}


text:
function [sameGroup, reverseGroup, probeGroup, targetGroup, diffGroup] = createAcrossWordGroups(firstwordpairs, secondwordpairs)
    DEBUG_ON = 0;

    sameGroup = {};
    reverseGroup = {};
    probeGroup = {};
    targetGroup = {};
    diffGroup = {};

    %%- Loop through first wordpairs and compare with block(i+1)
    for iPair=1:length(firstwordpairs),
        firstWordPair = firstwordpairs{iPair}; % get the current word pair

        %%- Get the indices for different groupings in the next blocks'
        %%word pairs (secondwordpairs)
        sameWordIndices = findSameIndices(firstWordPair, secondwordpairs);
        reverseWordIndices = findReverse(firstWordPair, secondwordpairs);
        diffWordIndices = findDifferent(firstWordPair, secondwordpairs);
        probeWordIndices = findProbe(firstWordPair, secondwordpairs);
        targetWordIndices = findTarget(firstWordPair, secondwordpairs);

        if DEBUG_ON
            disp('Checking same word find.')
            firstWordPair
            secondwordpairs{sameWordIndices}
            disp('checking reverse word find.')
            firstWordPair
            secondwordpairs{reverseWordIndices}
            disp('checking diff word find.')
            firstWordPair
            secondwordpairs{diffWordIndices}
            firstWordPair
            disp('probe')
            secondwordpairs{probeWordIndices}
            disp('target')
            secondwordpairs{targetWordIndices}
        end

        %%- Add wordPairs to their corresponding group sets
        if (~isempty(sameWordIndices)) % check if we found any in secondwordgroup
            sameGroup{end+1} = {firstWordPair, secondwordpairs{sameWordIndices}};
        end
        if (~isempty(reverseWordIndices))
            reverseGroup{end+1} = {firstWordPair, secondwordpairs{reverseWordIndices}};
        end
        if (~isempty(diffWordIndices))
            % diffWordIndices could be a list instead of just 1 pairing
            if length(diffWordIndices) == 1
                diffGroup{end+1} = {firstWordPair, secondwordpairs{diffWordIndices}};
            else
                for diffIndex=1:length(diffWordIndices)
                    diffGroup{end+1} = {firstWordPair, secondwordpairs{diffWordIndices(diffIndex)}};
                end
            end
        end
        if (~isempty(probeWordIndices))
            % probeWordIndices could be a list instead of just 1 pairing
            if length(probeWordIndices) == 1
                probeGroup{end+1} = {firstWordPair, secondwordpairs{probeWordIndices}};
            else
                for probeIndex=1:length(probeWordIndices)
                    probeGroup{end+1} = {firstWordPair, secondwordpairs{probeWordIndices(probeIndex)}};
                end
            end
        end
        if (~isempty(targetWordIndices))
            % diffWordIndices could be a list instead of just 1 pairing
            if length(targetWordIndices) == 1
                targetGroup{end+1} = {firstWordPair, secondwordpairs{targetWordIndices}};
            else
                for targetIndex=1:length(targetWordIndices)
                    targetGroup{end+1} = {firstWordPair, secondwordpairs{targetWordIndices(targetIndex)}};
                end
            end
        end
    end % end of loop through word groups
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%------------------ HELPER FUNCTIONS ---------------------------------------%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function sameWordIndices = findSameIndices(wordPair, otherWordPairGroup)
    words = strsplit(wordPair, '_');
    sameWordIndices = find(ismember(otherWordPairGroup, wordPair));
end

% find indices that show reversal of wordPair in wordPairComb
function reverseWordIndices = findReverse(wordPair, otherWordPairGroup)
    reverseWordPair = fliplr(strsplit(wordPair, '_')); % split word and reverse
    reverseWordPair = strjoin(reverseWordPair, '_');   % join the reversed word
    reverseWordIndices = find(ismember(otherWordPairGroup, reverseWordPair)); % find in cell array
end

% find indices that show different of wordPair in wordPairComb
function diffWordIndices = findDifferent(wordPair, otherWordPairGroup)
    words = strsplit(wordPair, '_'); % split word and reverse
    diffWordIndices = [];

    % loop through all wordpairs in other group
    for iPair=1:length(otherWordPairGroup),
        otherWordPair = strsplit(otherWordPairGroup{iPair}, '_');

        % append index, if the word is different
        if ~ismember(words, otherWordPair)
            diffWordIndices = [diffWordIndices; iPair];
        end
    end
end

function probeWordIndices = findProbe(wordPair, otherWordPairGroup)
    words = strsplit(wordPair, '_'); % split word and reverse
    probeWordIndices = [];

    for iPair=1:length(otherWordPairGroup),
        otherWordPair = strsplit(otherWordPairGroup{iPair}, '_');

        % check that is is not the samepair and the probe word overlaps
        if isempty(find(ismember(otherWordPairGroup, wordPair))) && ...
                strcmp(words{1}, otherWordPair{1})

            probeWordIndices = [probeWordIndices; iPair];
        end
    end
end

function targetWordIndices = findTarget(wordPair, otherWordPairGroup)
    words = strsplit(wordPair, '_'); % split word and reverse
    targetWordIndices = [];

    for iPair=1:length(otherWordPairGroup),
        otherWordPair = strsplit(otherWordPairGroup{iPair}, '_');

        % check that is is not the samepair and the probe word overlaps
        if isempty(find(ismember(otherWordPairGroup, wordPair))) && ...
                strcmp(words{2}, otherWordPair{2})

            targetWordIndices = [targetWordIndices; iPair];
        end
    end
end


text:
#import <Foundation/Foundation.h>

@class OCMLocation;
@class OCClassMockObject;
@class OCPartialMockObject;

BOOL OCMIsClassType(const char *objCType);
BOOL OCMIsBlockType(const char *objCType);
BOOL OCMIsObjectType(const char *objCType);
const char *OCMTypeWithoutQualifiers(const char *objCType);
BOOL OCMEqualTypesAllowingOpaqueStructs(const char *type1, const char *type2);
CFNumberType OCMNumberTypeForObjCType(const char *objcType);

Class OCMCreateSubclass(Class cls, void *ref);

BOOL OCMIsAliasSelector(SEL selector);
SEL OCMAliasForOriginalSelector(SEL selector);
SEL OCMOriginalSelectorForAlias(SEL selector);

void OCMSetAssociatedMockForClass(OCClassMockObject *mock, Class aClass);
OCClassMockObject *OCMGetAssociatedMockForClass(Class aClass, BOOL includeSuperclasses);

void OCMSetAssociatedMockForObject(OCClassMockObject *mock, id anObject);
OCPartialMockObject *OCMGetAssociatedMockForObject(id anObject);

void OCMReportFailure(OCMLocation *loc, NSString *description);


text:
This directory contains images that are used for specific tasks in Lagoon.
These tasks are mainly used when using the Lagoon Kubernetes Controllers


text:
package honeyspoon;

import com.cloudera.sqoop.mapreduce.db.DBConfiguration;
import com.cloudera.sqoop.mapreduce.db.DBInputFormat;
import com.cloudera.sqoop.mapreduce.db.DataDrivenDBRecordReader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.sqoop.mapreduce.DBWritable;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

public class HSDBRecordReader<T extends DBWritable>
        extends DataDrivenDBRecordReader<T> {

    private static final Log LOG = LogFactory.getLog(HSDBRecordReader.class);

    public HSDBRecordReader(DBInputFormat.DBInputSplit split,
                            Class<T> inputClass, Configuration conf, Connection conn,
                            DBConfiguration dbConfig, String cond, String[] fields,
                            String table) throws SQLException {
        super(split, inputClass, conf, conn, dbConfig, cond, fields, table, "HONEYSPOON");
    }

    protected String getSelectQuery() {
        StringBuilder query = new StringBuilder();
        DBConfiguration dbConf = getDBConf();
        String conditions = getConditions();
        String tableName = getTableName();
        String[] fieldNames = getFieldNames();
        DBInputFormat.DBInputSplit split = getSplit();

        if (dbConf.getInputQuery() == null) {
            query.append("SELECT ");

            for (int i = 0; i < fieldNames.length; i++) {
                query.append(fieldNames[i]);
                if (i != fieldNames.length - 1) {
                    query.append(", ");
                }
            }

            query.append(" FROM ").append(tableName);
            query.append(" t ");
            if (conditions != null && conditions.length() > 0) {
                query.append(" WHERE (").append(conditions).append(")");
            }

            String orderBy = dbConf.getInputOrderBy();
            if (orderBy != null && orderBy.length() > 0) {
                query.append(" ORDER BY ").append(orderBy);
            }
        } else {
            query.append(dbConf.getInputQuery());
        }

        try {
            if (split.getLength() > 0 || split.getStart() > 0) {
                throw new IllegalArgumentException("Start/Length based splits are not supported.");
            }
        } catch (IOException ex) {
            LOG.error(ex.toString());
        }

        return query.toString();
    }
}