text:
package voldemort.server.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import org.apache.log4j.Logger;

import voldemort.VoldemortException;
import voldemort.cluster.Cluster;
import voldemort.routing.RoutingStrategy;
import voldemort.routing.RoutingStrategyFactory;
import voldemort.serialization.VoldemortOpCode;
import voldemort.server.StoreRepository;
import voldemort.server.UnableUpdateMetadataException;
import voldemort.server.VoldemortMetadata;
import voldemort.server.protocol.RequestHandler;
import voldemort.store.ErrorCodeMapper;
import voldemort.store.StorageEngine;
import voldemort.store.StoreDefinition;
import voldemort.store.metadata.MetadataStore;
import voldemort.utils.ByteArray;
import voldemort.utils.ByteUtils;
import voldemort.utils.ClosableIterator;
import voldemort.utils.IoThrottler;
import voldemort.utils.Pair;
import voldemort.versioning.VectorClock;
import voldemort.versioning.Versioned;
import voldemort.xml.ClusterMapper;
import voldemort.xml.StoreDefinitionsMapper;

/**
 * Responsible for interpreting and handling a Admin Request Stream
 *
 * @author bbansal
 *
 */
public class AdminServiceRequestHandler implements RequestHandler {

    private final Logger logger = Logger.getLogger(AdminServiceRequestHandler.class);

    private final StoreRepository storeRepository;
    private final VoldemortMetadata metadata;
    private final MetadataStore metadataStore;

    private final ErrorCodeMapper errorMapper;
    private final int streamMaxBytesReadPerSec;
    private final int streamMaxBytesWritesPerSec;

    public AdminServiceRequestHandler(ErrorCodeMapper errorMapper,
                                      StoreRepository storeRepository,
                                      VoldemortMetadata metadata,
                                      String metadataDir,
                                      int streamMaxBytesReadPerSec,
                                      int streamMaxBytesWritesPerSec) {
        this.storeRepository = storeRepository;
        this.metadata = metadata;
        this.errorMapper = errorMapper;
        this.metadataStore = MetadataStore.readFromDirectory(new File(metadataDir));
        this.streamMaxBytesReadPerSec = streamMaxBytesReadPerSec;
        this.streamMaxBytesWritesPerSec = streamMaxBytesWritesPerSec;
    }

    public void handleRequest(DataInputStream inputStream, DataOutputStream outputStream)
            throws IOException {
        byte opCode = inputStream.readByte();
        StorageEngine<ByteArray, byte[]> engine;
        switch(opCode) {
            case VoldemortOpCode.GET_PARTITION_AS_STREAM_OP_CODE:
                engine = readStorageEngine(inputStream, outputStream);
                if(engine != null)
                    handleGetPartitionsAsStream(engine, inputStream, outputStream);
                break;
            case VoldemortOpCode.PUT_ENTRIES_AS_STREAM_OP_CODE:
                engine = readStorageEngine(inputStream, outputStream);
                if(engine != null)
                    handleUpdateEntries(engine, inputStream, outputStream);
                break;
            case VoldemortOpCode.UPDATE_METADATA_OP_CODE:
                String keyString = inputStream.readUTF();
                handleUpdateMetadataRequest(keyString, inputStream, outputStream);
                break;

            case VoldemortOpCode.SERVER_STATE_CHANGE_OP_CODE:
                handleServerStateChangeRequest(inputStream, outputStream);
                break;
            case VoldemortOpCode.REDIRECT_GET_OP_CODE:
                engine = readStorageEngine(inputStream, outputStream);
                byte[] key = readKey(inputStream);
                handleRedirectGetRequest(engine, key, outputStream);
                break;
            default:
                throw new IOException("Unknown op code : " + opCode + " at Node:"
                                      + metadata.getIdentityNode().getId());
        }

        outputStream.flush();
    }

    private byte[] readKey(DataInputStream inputStream) throws IOException {
        int keySize = inputStream.readInt();
        byte[] key = new byte[keySize];
        ByteUtils.read(inputStream, key);

        return key;
    }

    private StorageEngine<ByteArray, byte[]> readStorageEngine(DataInputStream inputStream,
                                                               DataOutputStream outputStream)
            throws IOException {
        String storeName = inputStream.readUTF();
        StorageEngine<ByteArray, byte[]> engine = storeRepository.getStorageEngine(storeName);
        if(engine == null) {
            writeException(outputStream, new VoldemortException("No store named '" + storeName
                                                                + "'."));
        }

        return engine;
    }

    /**
     * provides a way to write a batch of entries to a storageEngine. expects
     * format as
     *

     * KeyLength(int32) bytes(keyLength) valueLength(int32)
     * bytes(valueLength)
     *

     *  Reads entries unless see a keyLength value of -1.
     *

     * Possible usecases
     *

     *
data grandfathering

     *
cluster rebalancing

     *
nodes replication

     *

     *
     * @param engine
     * @throws IOException
     */
    private void handleUpdateEntries(StorageEngine<ByteArray, byte[]> engine,
                                     DataInputStream inputStream,
                                     DataOutputStream outputStream) throws IOException {
        IoThrottler throttler = new IoThrottler(streamMaxBytesWritesPerSec);

        try {
            int keySize = inputStream.readInt();
            while(keySize != -1) {
                byte[] key = new byte[keySize];
                ByteUtils.read(inputStream, key);

                int valueSize = inputStream.readInt();
                byte[] value = new byte[valueSize];
                ByteUtils.read(inputStream, value);

                VectorClock clock = new VectorClock(value);
                Versioned<byte[]> versionedValue = new Versioned<byte[]>(ByteUtils.copy(value,
                                                                                clock.sizeInBytes(),
                                                                                value.length),
                                                                         clock);

                engine.put(new ByteArray(key), versionedValue);

                if(throttler != null) {
                    throttler.maybeThrottle(key.length + clock.sizeInBytes() + value.length);
                }

                keySize = inputStream.readInt(); // read next KeySize
            }
            // all puts are handled.
            outputStream.writeShort(0);
        } catch(VoldemortException e) {
            writeException(outputStream, e);
        }
    }

    /**
     * provides a way to read batch entries from a storageEngine. expects an
     * integer list of partitions requested. writes back to dataStream in format
     *

     * KeyLength(int32) bytes(keyLength) valueLength(int32)
     * bytes(valueLength)
     *

     * Stream end is indicated by writing a keyLength value of
     * -1.
     *

     * Possible usecases
     *

     *
data grandfathering

     *
cluster rebalancing

     *
nodes replication

     *

     *
     * @param engine
     * @throws IOException
     */
    private void handleGetPartitionsAsStream(StorageEngine<ByteArray, byte[]> engine,
                                             DataInputStream inputStream,
                                             DataOutputStream outputStream) throws IOException {
        // read partition List
        int partitionSize = inputStream.readInt();
        int[] partitionList = new int[partitionSize];
        for(int i = 0; i < partitionSize; i++) {
            partitionList[i] = inputStream.readInt();
        }

        RoutingStrategy routingStrategy = new RoutingStrategyFactory(metadata.getCurrentCluster()).getRoutingStrategy(metadata.getStoreDef(engine.getName()));
        IoThrottler throttler = new IoThrottler(streamMaxBytesReadPerSec);
        try {
            /**
             * TODO HIGH: This way to iterate over all keys is not optimal
             * stores should be made routing aware to fix this problem
             */
            ClosableIterator<Pair<ByteArray, Versioned<byte[]>>> iterator = engine.entries();

            while(iterator.hasNext()) {
                Pair<ByteArray, Versioned<byte[]>> entry = iterator.next();

                if(validPartition(entry.getFirst().get(), partitionList, routingStrategy)) {
                    outputStream.writeShort(0);

                    // write key
                    byte[] key = entry.getFirst().get();
                    outputStream.writeInt(key.length);
                    outputStream.write(key);

                    // write value
                    byte[] clock = ((VectorClock) entry.getSecond().getVersion()).toBytes();
                    byte[] value = entry.getSecond().getValue();
                    outputStream.writeInt(clock.length + value.length);
                    outputStream.write(clock);
                    outputStream.write(value);

                    if(throttler != null) {
                        throttler.maybeThrottle(key.length + clock.length + value.length);
                    }
                }
            }
            // close the iterator here
            iterator.close();
            // client reads exception before every key length
            outputStream.writeShort(0);
            // indicate that all keys are done
            outputStream.writeInt(-1);
            outputStream.flush();

        } catch(VoldemortException e) {
            writeException(outputStream, e);
        }
    }

    private void handleUpdateMetadataRequest(String keyString,
                                             DataInputStream inputStream,
                                             DataOutputStream outputStream) throws IOException {
        if(keyString.equals(MetadataStore.CLUSTER_KEY)
           || keyString.equals(MetadataStore.ROLLBACK_CLUSTER_KEY)) {
            handleUpdateClusterMetadataRequest(keyString, inputStream, outputStream);
        } else if(keyString.equals(MetadataStore.STORES_KEY)) {
            handleUpdateStoresMetadataRequest(keyString, inputStream, outputStream);
        } else {
            writeException(outputStream, new VoldemortException("Metadata Key passed " + keyString
                                                                + " is not handled yet ..."));
        }
    }

    private void handleUpdateClusterMetadataRequest(String cluster_key,
                                                    DataInputStream inputStream,
                                                    DataOutputStream outputStream)
            throws IOException {
        // get current ClusterInfo
        List<Versioned<byte[]>> clusterInfo = metadataStore.get(ByteUtils.getBytes(cluster_key,
                                                                                "UTF-8"));
        if(clusterInfo.size() > 1) {
            throw new UnableUpdateMetadataException("Inconistent Cluster Metdata found on Server:"
                                                    + metadata.getIdentityNode().getId()
                                                    + " for Key:" + cluster_key);
        }
        logger.debug("Cluster metadata  update called " + cluster_key);
        // update version
        VectorClock updatedVersion = new VectorClock();
        if(clusterInfo.size() > 0) {
            updatedVersion = ((VectorClock) clusterInfo.get(0).getVersion());
        }

        updatedVersion.incrementVersion(metadata.getIdentityNode().getId(),
                                        System.currentTimeMillis());

        try {
            String clusterString = inputStream.readUTF();

            Cluster updatedCluster = new ClusterMapper().readCluster(new StringReader(clusterString));

            // update cluster details in metaDataStore
            metadataStore.put(new ByteArray(ByteUtils.getBytes(cluster_key, "UTF-8")),
                              new Versioned<byte[]>(ByteUtils.getBytes(new ClusterMapper().writeCluster(updatedCluster),
                                                                       "UTF-8"),
                                                    updatedVersion));
            // if successfull update state in Voldemort Metadata
            if(MetadataStore.CLUSTER_KEY.equalsIgnoreCase(cluster_key)) {
                metadata.setCurrentCluster(updatedCluster);
                metadata.reinitRoutingStrategies();
            } else if(MetadataStore.ROLLBACK_CLUSTER_KEY.equalsIgnoreCase(cluster_key)) {
                metadata.setRollbackCluster(updatedCluster);
            }
            outputStream.writeShort(0);
        } catch(VoldemortException e) {
            e.printStackTrace();
            writeException(outputStream, e);
            return;
        }
    }

    private void handleUpdateStoresMetadataRequest(String storeKey,
                                                   DataInputStream inputStream,
                                                   DataOutputStream outputStream)
            throws IOException {
        // get current Store Info
        List<Versioned<byte[]>> storesInfo = metadataStore.get(ByteUtils.getBytes(storeKey, "UTF-8"));
        if(storesInfo.size() > 1) {
            throw new UnableUpdateMetadataException("Inconistent Stores Metdata found on Server:"
                                                    + metadata.getIdentityNode().getId());
        }

        // update version
        VectorClock updatedVersion = ((VectorClock) storesInfo.get(0).getVersion());
        updatedVersion.incrementVersion(metadata.getIdentityNode().getId(),
                                        System.currentTimeMillis());

        try {
            String storesString = inputStream.readUTF();

            List<StoreDefinition> storeDefs = new StoreDefinitionsMapper().readStoreList(new StringReader(new String(storesString)));

            // update cluster details in metaDataStore
            metadataStore.put(new ByteArray(ByteUtils.getBytes(MetadataStore.STORES_KEY, "UTF-8")),
                              new Versioned<byte[]>(ByteUtils.getBytes(new StoreDefinitionsMapper().writeStoreList(storeDefs),
                                                                       "UTF-8"),
                                                    updatedVersion));
            metadata.setStoreDefs(storeDefs);
            // if successfull update state in Voldemort Metadata
            metadata.setStoreDefMap(storeDefs);
            metadata.reinitRoutingStrategies();
            outputStream.writeShort(0);
        } catch(VoldemortException e) {
            e.printStackTrace();
            writeException(outputStream, e);
            return;
        }
    }

    private void handleServerStateChangeRequest(DataInputStream inputStream,
                                                DataOutputStream outputStream) throws IOException {
        try {
            VoldemortMetadata.ServerState newState = VoldemortMetadata.ServerState.valueOf(inputStream.readUTF());
            metadata.setServerState(newState);

            outputStream.writeShort(0);
        } catch(VoldemortException e) {
            e.printStackTrace();
            writeException(outputStream, e);
            return;
        }

    }

    /**
     * By pass store level consistency checks needed to handle redirect gets
     * while rebalancing
     *
     * @param engine
     * @param key
     * @throws IOException
     */
    private void handleRedirectGetRequest(StorageEngine<ByteArray, byte[]> engine,
                                          byte[] key,
                                          DataOutputStream outputStream) throws IOException {
        List<Versioned<byte[]>> results = null;
        try {
            results = engine.get(new ByteArray(key));
            outputStream.writeShort(0);
        } catch(VoldemortException e) {
            e.printStackTrace();
            writeException(outputStream, e);
            return;
        }
        outputStream.writeInt(results.size());
        for(Versioned<byte[]> v: results) {
            byte[] clock = ((VectorClock) v.getVersion()).toBytes();
            byte[] value = v.getValue();
            outputStream.writeInt(clock.length + value.length);
            outputStream.write(clock);
            outputStream.write(value);
        }
    }

    private void writeException(DataOutputStream stream, VoldemortException e) throws IOException {
        short code = errorMapper.getCode(e);
        stream.writeShort(code);
        stream.writeUTF(e.getMessage());
    }

    private boolean validPartition(byte[] key, int[] partitionList, RoutingStrategy routingStrategy) {
        List<Integer> keyPartitions = routingStrategy.getPartitionList(key);
        for(int p: partitionList) {
            if(keyPartitions.contains(p)) {
                return true;
            }
        }
        return false;
    }

}


text:
describe Facts::Solaris::Kernel do
  describe '#call_the_resolver' do
    subject(:fact) { Facts::Solaris::Kernel.new }

    let(:value) { 'SunOs' }

    before do
      allow(Facter::Resolvers::Uname).to receive(:resolve).with(:kernelname).and_return(value)
    end

    it 'calls Facter::Resolvers::Uname' do
      fact.call_the_resolver
      expect(Facter::Resolvers::Uname).to have_received(:resolve).with(:kernelname)
    end

    it 'returns kernel fact' do
      expect(fact.call_the_resolver).to be_an_instance_of(Facter::ResolvedFact).and \
        have_attributes(name: 'kernel', value: value)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import mock
import testtools

from openstacksdk_plugin.other.v1 import _proxy

class TestExampleProxy(testtools.TestCase):
    def setUp(self):
        super(TestExampleProxy, self).setUp()
        self.session = mock.MagicMock()
        self.proxy = _proxy.Proxy(self.session)

    def test_everything(self):
        self.assertEqual('Bonjour', self.proxy.return_bonjour())
        self.assertEqual('Au revoir', self.proxy.return_au_revoir())


text:
lamana.utils package
====================

Submodules
----------

lamana.utils.config module
--------------------------

.. automodule:: lamana.utils.config
    :members:
    :undoc-members:
    :show-inheritance:

lamana.utils.plottools module
-----------------------------

.. automodule:: lamana.utils.plottools
    :members:
    :undoc-members:
    :show-inheritance:

lamana.utils.references module
------------------------------

.. automodule:: lamana.utils.references
    :members:
    :undoc-members:
    :show-inheritance:

lamana.utils.tools module
-------------------------

.. automodule:: lamana.utils.tools
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: lamana.utils
    :members:
    :undoc-members:
    :show-inheritance:


text:
package org.springframework.web.context.request;

/**
 * Request-backed {@link org.springframework.beans.factory.config.Scope}
 * implementation.
 *
 *
Relies on a thread-bound {@link RequestAttributes} instance, which
 * can be exported through {@link RequestContextListener},
 * {@link org.springframework.web.filter.RequestContextFilter} or
 * {@link org.springframework.web.servlet.DispatcherServlet}.
 *
 *
This Scope will also work for Portlet environments,
 * through an alternate RequestAttributes implementation
 * (as exposed out-of-the-box by Spring's
 * {@link org.springframework.web.portlet.DispatcherPortlet}.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @since 2.0
 * @see RequestContextHolder#currentRequestAttributes()
 * @see RequestAttributes#SCOPE_REQUEST
 * @see RequestContextListener
 * @see org.springframework.web.filter.RequestContextFilter
 * @see org.springframework.web.servlet.DispatcherServlet
 * @see org.springframework.web.portlet.DispatcherPortlet
 */
public class RequestScope extends AbstractRequestAttributesScope {

	protected int getScope() {
		return RequestAttributes.SCOPE_REQUEST;
	}

	/**
	 * There is no conversation id concept for a request, so this method
	 * returns null.
	 */
	public String getConversationId() {
		return null;
	}

}


text:
<?php

declare(strict_types=1);

namespace Broadway\EventStore\Management;

/**
 * Criteria not supported by implementation.
 *
 * In some cases an event store implementation may implement management
 * but not be able to satisfy all criteria options. In this case, the
 * implementation must throw this exception.
 *
 * Class CriteriaNotSupportedException
 */
final class CriteriaNotSupportedException extends EventStoreManagementException
{
}


text:
        <meta charset="UTF-8">
        <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">

        <legend>

            Entrer l'identifiant du noeud que vous voulez éditer :
        </legend>

                <input id="textinput" name="textinput" type="text" class="form-control input-md">
                Par exemple : 532031656 ou 1429442329

                <button id="singlebutton" name="singlebutton" class="btn btn-primary" onclick='test_edit()'>Éditer</button>

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

Édition du bar dans OpenBeerMap

Vous n'êtes pas connecté à OpenStreetMap. Vos contributions seront post-modérées. blabla, bouton de connexion ...

Vous êtes connecté à OpenStreetMap. blabla, bienvenue ...

                        <form class="form-horizontal" name="edit_form">
                            <fieldset>

                                        <input id="OSM_id" name="OSM_id" class="form-control input-md hidden" type="text">

                                    Nom

                                        <input id="bar-name" name="bar-name" class="form-control input-md" type="text">

                                    Wifi

                                            <input name="wifi" id="radios-0" value="wlan" type="radio">
                                            oui

                                            <input name="wifi" id="radios-1" value="no" type="radio">
                                            non

                                            <input name="wifi" id="radios-2" value="unknown" type="radio">
                                            peut-être

                                    Heures d'ouverture

                                        <input id="opening_hours" name="opening_hours" class="form-control input-md" type="text" disabled="disabled">
                                        exemple : Mo-Fr 11:30-20:00

                                        Enregistrer

                                                Éditer directement dans OpenStreetMap

                                    </fieldset>
                                </form>

                                <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>

                    <button id='authenticate'>login</button>
                    <button id='logout'>logout</button>


text:
<?php

namespace Mergy;

/**
 * Represents a revision
 *
 * @author Hans-Peter Buniat <hpbuniat@googlemail.com>
 * @copyright 2011-2012 Hans-Peter Buniat <hpbuniat@googlemail.com>
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 * @version Release: @package_version@
 * @link https://github.com/hpbuniat/mergy
 */
class Revision {

    /**
     * Revision repository url
     *
     * @var string
     */
    public $sRepository;

    /**
     * Revision-Number
     *
     * @var int
     */
    public $iRevision;

    /**
     * Commit-Message
     *
     * @var string
     */
    public $sInfo;

    /**
     * Author of this revision
     *
     * @var string
     */
    public $sAuthor;

    /**
     * Creation-Date
     *
     * @var string
     */
    public $sDate;

    /**
     * Modified Files
     *
     * @var array
     */
    public $aFiles = null;

    /**
     * Diffs of modified files
     *
     * @var array
     */
    public $aDiffs = null;

    /**
     * The revision builder
     *
     * @var Revision\Builder
     */
    protected $_oBuilder;

    /**
     * Create a Revision-Object
     *
     * @param  string $sRepository
     * @param  int $iRevision
     * @param  Revision\Builder $oBuilder
     */
    public function __construct($sRepository, $iRevision, Revision\Builder $oBuilder) {
        $this->iRevision = $iRevision;
        $this->sRepository = $sRepository;
        $this->_oBuilder = $oBuilder;
    }

    /**
     * Read additional info to a revision
     *
     * @return Revision
     */
    public function read() {
        $this->_fetchInfo();
        return $this;
    }

    /**
     * Get diff-output for modified files
     *
     * @return Revision
     */
    public function diff() {
        $this->aDiffs = array();
        if ($this->aFiles === null) {
            $this->_fetchFiles();
        }

        foreach ($this->aFiles as $aFile) {
            $oAggregate = $this->_oBuilder->getAggregator(Revision\Builder::AGGREGATE_DIFF, array(
                $this->sRepository,
                $this->iRevision,
                $aFile['path'],
                $aFile['type']
            ));
            $this->aDiffs[] = array(
                'file' => $aFile['path'],
                'diff' => (string) $oAggregate->get(),
                'type' => $aFile['type']
            );
            unset($oAggregate);
        }

        return $this;
    }

    /**
     * In String-Context show a formatted output
     *
     * @return string
     */
    public function __toString() {
        return str_pad($this->iRevision, 7) . str_pad($this->sAuthor, 18) . str_replace("\n", ' ', $this->sInfo);
    }

    /**
     * Read Information about a revision from a repository
     *
     * @return Revision
     */
    protected function _fetchInfo() {
        $oAggregate = $this->_oBuilder->getAggregator(Revision\Builder::AGGREGATE_INFO, array(
            $this->sRepository,
            $this->iRevision
        ));

        try {
            $oInfo = $oAggregate->get();
            $this->sInfo = (string) $oInfo->msg;
            $this->sAuthor = (string) $oInfo->author;
            $this->sDate = (string) $oInfo->date;
            unset ($oInfo);
        }
        catch (Revision\Aggregator\Exception $oException) {
            /* currently, there is nothing to do here */
            \Mergy\TextUI\Output::error($oException->getMessage());
        }

        unset($oAggregate);
        return $this;
    }

    /**
     * Read modifications of a revision from a repository
     *
     * @return Revision
     */
    protected function _fetchFiles() {
        $this->aFiles = array();
        $oAggregate = $this->_oBuilder->getAggregator(Revision\Builder::AGGREGATE_FILES, array(
            $this->sRepository,
            $this->iRevision
        ));

        try {
            $this->aFiles = $oAggregate->get();
        }
        catch (Revision\Aggregator\Exception $oException) {
            /* currently, there is nothing to do here */
            \Mergy\TextUI\Output::error($oException->getMessage());
        }

        unset($oAggregate);
        return $this;
    }
}


text:
(function() {
  console.log('inline');
})();


text:
<?php

class Google_Service_ShoppingContent_SettlementTransaction extends Google_Model
{
  protected $amountType = 'Google_Service_ShoppingContent_SettlementTransactionAmount';
  protected $amountDataType = '';
  protected $identifiersType = 'Google_Service_ShoppingContent_SettlementTransactionIdentifiers';
  protected $identifiersDataType = '';
  public $kind;
  protected $transactionType = 'Google_Service_ShoppingContent_SettlementTransactionTransaction';
  protected $transactionDataType = '';

  /**
   * @param Google_Service_ShoppingContent_SettlementTransactionAmount
   */
  public function setAmount(Google_Service_ShoppingContent_SettlementTransactionAmount $amount)
  {
    $this->amount = $amount;
  }
  /**
   * @return Google_Service_ShoppingContent_SettlementTransactionAmount
   */
  public function getAmount()
  {
    return $this->amount;
  }
  /**
   * @param Google_Service_ShoppingContent_SettlementTransactionIdentifiers
   */
  public function setIdentifiers(Google_Service_ShoppingContent_SettlementTransactionIdentifiers $identifiers)
  {
    $this->identifiers = $identifiers;
  }
  /**
   * @return Google_Service_ShoppingContent_SettlementTransactionIdentifiers
   */
  public function getIdentifiers()
  {
    return $this->identifiers;
  }
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  /**
   * @param Google_Service_ShoppingContent_SettlementTransactionTransaction
   */
  public function setTransaction(Google_Service_ShoppingContent_SettlementTransactionTransaction $transaction)
  {
    $this->transaction = $transaction;
  }
  /**
   * @return Google_Service_ShoppingContent_SettlementTransactionTransaction
   */
  public function getTransaction()
  {
    return $this->transaction;
  }
}


text:
package inna.qa.dp.tests;

import inna.qa.dp.model.ContactData;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.stream.Collectors;

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

public class ContactEmailTests extends TestBase{
    @Test
    public void testContactPhones(){
        app.goTo().gotoHomePage();
        ContactData contact = app.contact().all().iterator().next();
        ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact);

        assertThat(contact.getAllEmails(), equalTo(mergeEmails(contactInfoFromEditForm)));
    }

    private String mergeEmails(ContactData contact) {
        return Arrays.asList(contact.getEmail1(), contact.getEmail2(), contact.getEmail3()).
                stream().filter((s) -> ! s.equals("")).map(ContactEmailTests::cleaned).
                collect(Collectors.joining("\n"));
    }

    public static String cleaned(String contact) {
        return contact.replaceAll("\\s+", "").replaceAll("\n", " ");
    }
}


text:
module QA
  RSpec.describe 'Verify', :docker, :runner do
    describe 'Code coverage statistics' do
      let(:simplecov) { '\(\d+.\d+\%\) covered' }
      let(:executor) { "qa-runner-#{Time.now.to_i}" }
      let(:runner) do
        Resource::Runner.fabricate_via_api! do |runner|
          runner.name = executor
          runner.tags = ['e2e-test']
        end
      end

      let(:merge_request) do
        Resource::MergeRequest.fabricate_via_api! do |mr|
          mr.project = runner.project
          mr.file_name = '.gitlab-ci.yml'
          mr.file_content = <<~EOF
            test:
              tags: [e2e-test]
              script:
                - echo '(66.67%) covered'
          EOF
        end
      end

      before do
        Flow::Login.sign_in
      end

      after do
        runner.remove_via_api!
      end

      it 'creates an MR with code coverage statistics', status_issue: 'https://gitlab.com/gitlab-org/quality/testcases/-/issues/807' do
        runner.project.visit!
        configure_code_coverage(simplecov)
        merge_request.visit!

        Page::MergeRequest::Show.perform do |mr_widget|
          Support::Retrier.retry_until(max_attempts: 5, sleep_interval: 5) do
            mr_widget.has_pipeline_status?(/Pipeline #\d+ passed/)
          end
          expect(mr_widget).to have_content('Coverage 66.67%')
        end
      end
    end

    private

    def configure_code_coverage(coverage_tool_pattern)
      Page::Project::Menu.perform(&:go_to_ci_cd_settings)
      Page::Project::Settings::CICD.perform do |settings|
        settings.expand_general_pipelines do |coverage|
          coverage.configure_coverage_regex(coverage_tool_pattern)
        end
      end
    end
  end
end


text:
#import "IBICMultipartImage.h"

@interface IBICMultipartImage (DisplayAdditions)
+ (id)keyPathsForValuesAffectingIbInspectedImageName;
- (id)ibInspectedHasRepsForSuggestionSet:(id)arg1;
- (void)setIbInspectedHasRepsForSuggestionSet:(id)arg1 toValue:(id)arg2;
- (void)setIbInspectedImageName:(id)arg1;
- (id)ibInspectedImageName;
- (id)itemsForOpeningInExternalEditor;
- (BOOL)isSelectableInDetailArea;
- (id)validatedFileNameForProposedDisplayName:(id)arg1;
- (BOOL)isDisplayNameEditable;
- (BOOL)displaysInOutlineView;
- (BOOL)displaysChildrenInOutlineView;
- (id)icon;
@end


text:
/*********************************************************************
*                        TRIMER
*                    Barbara M. Rodeker
*                    TSP
*                    Arora`s implementation
*
**********************************************************************/
//
//  Licensed to the Apache Software Foundation (ASF) under one
//  or more contributor license agreements.  See the NOTICE file
//  distributed with this work for additional information
//  regarding copyright ownership.  The ASF licenses this file
//  to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
//  with the License.  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing,
//  software distributed under the License is distributed on an
//  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//  KIND, either express or implied.  See the License for the
//  specific language governing permissions and limitations
//  under the License.
//

#ifndef TrimerH
#define TrimerH

#include <System.hpp>

#include "QuadTreeTSP.h"
#include "ProgramacionDinamica.h"
#include "Portalizacion.h"

#include "Punto.h"
#include "PuntoExtendido.h"
#include "Cuadrante.h"
#include "SubSolucion.h"

class Trimer{
     private:
            QuadTreeTSP *quad;
            Cuadrante **quadtr;
            ProgramacionDinamica *pd;
            Perturbacion *pert;
            unsigned int tamanio,numNodos,divide;
            PuntoExtendido **caminoTrimed;

            void setMaxTamanio(); //setea la variable tamaño que se refiere al arreglo de Par
            void Trim(); //prepara las condiciones para optimizar el camino
            void Trim2(unsigned int,unsigned int ,unsigned int *); //optimiza el camino obtenido poligonizandolo

            void inicCaminoTrimed();

     public:
            Trimer(QuadTreeTSP *,ProgramacionDinamica *,Perturbacion *);
            ~Trimer();
            void execute();
            PuntoExtendido **getCaminoTrimed();
            AnsiString toString();
            float getLargoCamino();
            int getDivide(){return divide;};

};
//---------------------------------------------------------------------------
#endif


text:
package grafos;

import grafos.representacoes.ListaDeAdjacencia;

/**
 *
 * @author Willian Soares
 */
public class TestAddArestaListaAdjacencia {
    ListaDeAdjacencia grafo;

    public TestAddArestaListaAdjacencia() {
        this.grafo = new ListaDeAdjacencia(0);
    }

    public long[] testSequencial(){
        long[] values = {3, 13, 130, 500, 1300, 2600, 5000, 8000, 13000, 26000};
        long inicio;
        for (int i = 0; i < values.length; i++) {
            this.grafo = new ListaDeAdjacencia((int)values[i]);
            for (int j = 0; j < values[i]; j++) {
                this.grafo.addAresta(1, j);
            }
            inicio = System.nanoTime();
            this.grafo.addAresta(1, (int)values[i]+1);
            values[i] = System.nanoTime() - inicio;
            System.out.println(values[i]);
        }
        this.grafo = new ListaDeAdjacencia(0);
        return values;
    }
}


text:
package org.smartdeveloperhub.curator.connector.rdf;

import java.net.URI;
import java.net.URL;

public interface PropertyHelper {

	<T extends PropertyHelper & ResourceHelper & ModelHelper> T withLiteral(Object value);

	<T extends PropertyHelper & ResourceHelper & ModelHelper> T withLanguageLiteral(Object value, String lang);

	<T extends PropertyHelper & ResourceHelper & ModelHelper> T withTypedLiteral(Object value, URI type);

	<T extends PropertyHelper & ResourceHelper & ModelHelper> T withTypedLiteral(Object value, String type);

	<T extends PropertyHelper & ResourceHelper & ModelHelper> T withResource(String value);

	<T extends PropertyHelper & ResourceHelper & ModelHelper> T withResource(URI value);

	<T extends PropertyHelper & ResourceHelper & ModelHelper> T withResource(URL value);

	<T extends PropertyHelper & ResourceHelper & ModelHelper> T withBlankNode(String value);

}


text:
package bootstrap

import (
	"time"

	"k8s.io/klog"

	"k8s.io/api/core/v1"
	bootstrapapi "k8s.io/cluster-bootstrap/token/api"
	bootstrapsecretutil "k8s.io/cluster-bootstrap/util/secrets"
)

func validateSecretForSigning(secret *v1.Secret) (tokenID, tokenSecret string, ok bool) {
	nameTokenID, ok := bootstrapsecretutil.ParseName(secret.Name)
	if !ok {
		klog.V(3).Infof("Invalid secret name: %s. Must be of form %s<secret-id>.", secret.Name, bootstrapapi.BootstrapTokenSecretPrefix)
		return "", "", false
	}

	tokenID = bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenIDKey)
	if len(tokenID) == 0 {
		klog.V(3).Infof("No %s key in %s/%s Secret", bootstrapapi.BootstrapTokenIDKey, secret.Namespace, secret.Name)
		return "", "", false
	}

	if nameTokenID != tokenID {
		klog.V(3).Infof("Token ID (%s) doesn't match secret name: %s", tokenID, nameTokenID)
		return "", "", false
	}

	tokenSecret = bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenSecretKey)
	if len(tokenSecret) == 0 {
		klog.V(3).Infof("No %s key in %s/%s Secret", bootstrapapi.BootstrapTokenSecretKey, secret.Namespace, secret.Name)
		return "", "", false
	}

	// Ensure this secret hasn't expired.  The TokenCleaner should remove this
	// but if that isn't working or it hasn't gotten there yet we should check
	// here.
	if bootstrapsecretutil.HasExpired(secret, time.Now()) {
		return "", "", false
	}

	// Make sure this secret can be used for signing
	okToSign := bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenUsageSigningKey)
	if okToSign != "true" {
		return "", "", false
	}

	return tokenID, tokenSecret, true
}


text:
package org.funtastic.bucket;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.BulkWriteOperation;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;
import org.bson.types.ObjectId;

import static com.mongodb.QueryBuilder.start;

public class Producer {

    public static void main(String[] args) throws Exception {

        final MongoClient client = new MongoClient();
        final DB brokerDb = client.getDB("broker");
        final String queueName = "funqueue";

        DBCollection queue = brokerDb.getCollection(queueName);
        queue.createIndex(start("processing").is(1).and("bucket").is(1).get());

        int bucket = 0;
        int maxBuckets = 100;

        int count = 0;
        long start = System.currentTimeMillis();

        while (true) {

            BulkWriteOperation bulk = queue.initializeUnorderedBulkOperation();
            for (int q=0; q<100; q++) {

                BasicDBList list = new BasicDBList();
                for (int j = 0; j < 100; j++) {
                    DBObject o = new BasicDBObject();
                    o.put("messageId", new ObjectId());
                    list.add(o);
                }

                DBObject o = start("bucket").is("" + bucket).and("processing").is(false).get();
                o.put("batch", list);
//                queue.insert(o, WriteConcern.UNACKNOWLEDGED);
                bulk.insert(o);

                bucket++;
                if (bucket == maxBuckets) {
                    bucket = 0;
                }

                count += list.size();
            }
            bulk.execute(WriteConcern.ACKNOWLEDGED);

            if (count % 1000 == 0) {
                long now = System.currentTimeMillis();
                long duration = now - start;
                double rate = count / (1d * duration / 1000);
                System.out.println("rate: " + rate + "/sec");
            }
        }
    }
}


text:
import { DiceThrow, IDiceThrowSettings } from './dice-throw';
import ChanceThrowResult from './chance-throw-result';
import IRollScoreSettings from './roll-score-settings.i';
export interface IChanceThrowSettings extends IDiceThrowSettings {
    rollScores: IRollScoreSettings;
}
export declare class ChanceThrow extends DiceThrow {
    settings: IChanceThrowSettings;
    constructor(settings?: IChanceThrowSettings);
    /**
     * Returns the range for a success rate.
     *
     * @private
     * @function
     * @param {string} key - The success rate to lookup.
     * @return {Range}
     */
    private _range(key);
    /**
     * Determines the success rate of the throw.
     *
     * @private
     * @function
     * @param {Number} rollSum - The results of the throw.
     * @return {String}
     */
    private _calculateThrowType(rollSum);
    /**
     * Rolls the dice.
     *
     * @public
     * @function roll
     * @override
     */
    roll(): ChanceThrowResult;
}


text:
package org.knowm.xchange.kuna;

import org.knowm.xchange.BaseExchange;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.kuna.service.KunaAccountService;
import org.knowm.xchange.kuna.service.KunaMarketDataService;
import org.knowm.xchange.kuna.service.KunaTradeService;

/**
 * Class for accessing Kuna Exchange.
 *
 * @author Dat Bui
 */
public class KunaExchange extends BaseExchange implements Exchange {

  public static final String KUNA_URL = "https://kuna.io/api/";
  public static final String KUNA_HOST = "kuna.io";
  public static final int KUNA_PORT = 80;

  @Override
  protected void initServices() {
    this.marketDataService = new KunaMarketDataService(this);
    this.accountService = new KunaAccountService(this);
    this.tradeService = new KunaTradeService(this);
  }

  @Override
  public ExchangeSpecification getDefaultExchangeSpecification() {
    ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass());
    exchangeSpecification.setSslUri(KUNA_URL);
    exchangeSpecification.setHost(KUNA_HOST);
    exchangeSpecification.setPort(KUNA_PORT);
    exchangeSpecification.setExchangeName("Kuna");
    exchangeSpecification.setExchangeDescription(
        "Kuna is the ukrainian crypto currency exchange platform.");
    return exchangeSpecification;
  }
}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CustomersController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('customers.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('customers.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

	<include resource="org/springframework/boot/logging/logback/base.xml"/>

	<!--logger name="org.springframework" level="DEBUG"/-->
	<logger name="org.springframework.core.env" level="WARN"/>
	<logger name="org.springframework.jndi" level="WARN"/>

</configuration>


text:
<!DOCTYPE html>

  <title>Technical Blog | Joe McGrath</title>
  <link href="stylesheets/bootstrap.css" rel="stylesheet">
  <link href="stylesheets/technical.css" rel="stylesheet">

Technical

Mon. August 11, 2014

Ruby Classes

 Let's try and model a car using a ruby class in order to better understand what a class is made up of.  Instance variables would be things like body, engine, color, and radio.  Instance methods would manipulate these instance variables.  So a listen_to_radio method would change the value of radio from off to on.  This is a simple example, obviously.  You could make your Car class very complex and have thousands of variables and methods to manipulate those variables.  A way to think about what needs to be an instance variable would to think about what things in are able to change states. Then determine what states those variables can be in and create methods to change those states.

Archives

              Week 1

              Week 2

              Week 3

              Week 4

              Week 5

              Week 6

              Week 7

              Week 8

        Back to top


text:
<?php

// autoload.php generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit3542afc83763740f924b62028662d115::getLoader();


text:
/*!
 * Copyright (c) 2018 by Contributors
 *
 * \file kindchecker.cc
 *
 * \brief Check that types are well formed by applying "kinding rules".
 *
 * This pass ensures we do not do things that violate the design of the
 * type system when writing down types.
 *
 * For example tensors are not allowed to contain functions in Relay.
 *
 * We check this by ensuring the `dtype` field of a Tensor always
 * contains a data type such as `int`, `float`, `uint`.
 */
#include <tvm/relay/analysis.h>
#include <tvm/relay/error.h>
#include "../ir/type_functor.h"

namespace tvm {
namespace relay {

using namespace tvm::runtime;

struct KindChecker : TypeFunctor<Kind(const Type&)> {
  const Module& mod;
  ErrorReporter err_reporter;

  explicit KindChecker(const Module& mod) : mod(mod), err_reporter() {}

  void ReportFatalError(const Error& err) {
    this->err_reporter.Report(err);
    this->err_reporter.RenderErrors(mod);
  }

  void CheckKindMatches(const Type& t, const Type& outer,
                        Kind expected, const std::string& description) {
    Kind k = this->VisitType(t);
    if (k != expected) {
      ReportFatalError(RELAY_ERROR("Incorrect kind for a " << description
                                   << ". Type " << t << " inside " << outer
                                   << " is of kind " << k
                                   << " but was expected to be "
                                   << expected));
    }
  }

  Kind VisitType_(const IncompleteTypeNode* op) override {
    return op->kind;
  }

  Kind VisitType_(const TypeVarNode* op) override {
    return op->kind;
  }

  Kind VisitType_(const GlobalTypeVarNode* op) override {
    return op->kind;
  }

  Kind VisitType_(const TensorTypeNode* op) override {
    return Kind::kType;
  }

  Kind VisitType_(const TupleTypeNode* op) override {
    // tuples should only contain normal types
    for (const Type& t : op->fields) {
      CheckKindMatches(t, GetRef<TupleType>(op), Kind::kType,
                       "tuple member");
    }
    return Kind::kType;
  }

  Kind VisitType_(const FuncTypeNode* op) override {
    // Func types should only take normal types for arguments
    // and only return a normal type. They should also have
    // well-formed constraints
    FuncType ft = GetRef<FuncType>(op);
    for (const Type& t : op->arg_types) {
      CheckKindMatches(t, ft, Kind::kType, "function type parameter");
    }

    CheckKindMatches(ft->ret_type, ft, Kind::kType, "function return type");

    for (const TypeConstraint& tc : op->type_constraints) {
      CheckKindMatches(tc, ft, Kind::kConstraint, "function type constraint");
    }

    return Kind::kType;
  }

  Kind VisitType_(const RefTypeNode* op) override {
    // ref types should only contain normal types
    RefType rt = GetRef<RefType>(op);
    CheckKindMatches(op->value, rt, Kind::kType, "ref contents");
    return Kind::kType;
  }

  Kind VisitType_(const TypeRelationNode* op) override {
    // arguments to type relation should be normal types
    for (const Type& t : op->args) {
      CheckKindMatches(t, GetRef<TypeRelation>(op), Kind::kType,
                       "argument to type relation");
    }
    return Kind::kConstraint;
  }

  Kind VisitType_(const TypeCallNode* op) override {
    // type call func should be a global type var, args should be type
    TypeCall tc = GetRef<TypeCall>(op);
    const auto* gtv = op->func.as<GlobalTypeVarNode>();
    if (gtv == nullptr) {
      ReportFatalError(RELAY_ERROR("The callee in " << tc
                                   << " is not a global type var, but is " << op->func));
    }

    CheckKindMatches(op->func, tc, Kind::kAdtHandle, "type call function");

    for (const Type& t : op->args) {
      CheckKindMatches(t, tc, Kind::kType, "type call argument");
    }

    // finally we need to check the module to check the number of type params
    auto var = GetRef<GlobalTypeVar>(gtv);
    auto data = mod->LookupDef(var);
    if (data->type_vars.size() != op->args.size()) {
      ReportFatalError(RELAY_ERROR("Expected " << data->type_vars.size() << "arguments for " << tc
                                   << "; got " << op->args.size()));
    }
    return Kind::kType;
  }

  Kind VisitType_(const TypeDataNode* op) override {
    // Constructors can reference the header var, but no other GlobalTypeVars.
    // In theory, a TypeData could be nested, so the header scope
    // should be tracked recursively, but it is unclear that we need
    // to support it.
    TypeData td = GetRef<TypeData>(op);
    CheckKindMatches(op->header, td, Kind::kAdtHandle, "type data header");

    for (const auto& var : op->type_vars) {
      CheckKindMatches(var, td, Kind::kType, "ADT type var");
    }

    for (const auto& con : op->constructors) {
      if (!con->belong_to.same_as(op->header)) {
        ReportFatalError(RELAY_ERROR(con << " has header " << con->belong_to
                                     << " but " << op << " has header " << op->header));
      }

      for (const Type& t : con->inputs) {
        CheckKindMatches(t, td, Kind::kType, "ADT constructor input");
      }
    }
    return Kind::kTypeData;
  }

  Kind Check(const Type& t) {
    return this->VisitType(t);
  }
};

Kind KindCheck(const Type& t, const Module& mod) {
  KindChecker kc(mod);
  return kc.Check(t);
}

TVM_REGISTER_API("relay._analysis.check_kind")
.set_body([](TVMArgs args, TVMRetValue* ret) {
    if (args.size() == 1) {
      *ret = KindCheck(args[0], ModuleNode::make({}, {}));
    } else {
      *ret = KindCheck(args[0], args[1]);
    }
  });

}  // namespace relay
}  // namespace tvm


text:
/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

sammy.bind
(
  'cores_load_data',
  function( event, params )
  {
    $.ajax
    (
      {
        url : app.config.solr_path + app.config.core_admin_path + '?wt=json',
        dataType : 'json',
        beforeSend : function( xhr, settings )
        {
        },
        success : function( response, text_status, xhr )
        {
          app.set_cores_data( response );
          params.callback( app.cores_data );
        },
        error : function( xhr, text_status, error_thrown)
        {
        },
        complete : function( xhr, text_status )
        {
        }
      }
    );
  }
);

sammy.bind
(
  'cores_build_navigation',
  function( event, params )
  {
    var navigation_content = ['
'];

    for( var core in params.cores )
    {
      var core_name = core;
      if( !core_name )
      {
        core_name = '(empty)';
      }
      navigation_content.push( '
' + core_name + '
' );
    }

    params.navigation_element
      .html( navigation_content.join( "\n" ) );

    $( 'a[href="' + params.basepath + params.current_core + '"]', params.navigation_element ).parent()
      .addClass( 'current' );
  }
);

sammy.bind
(
  'cores_load_template',
  function( event, params )
  {
    if( app.cores_template )
    {
      params.callback();
      return true;
    }

    $.get
    (
      'tpl/cores.html',
      function( template )
      {
        params.content_element
          .html( template );

        app.cores_template = template;
        params.callback();
      }
    );
  }
);

// #/~cores
sammy.get
(
  /^#\/(~cores)$/,
  function( context )
  {
    delete app.cores_template;

    sammy.trigger
    (
      'cores_load_data',
      {
        callback :  function( cores )
        {
          var first_core = null;
          for( var key in cores )
          {
            if( !first_core )
            {
              first_core = key;
            }
            continue;
          }
          context.redirect( context.path + '/' + first_core );
        }
      }
    );
  }
);

// #/~cores
sammy.get
(
  /^#\/(~cores)\//,
  function( context )
  {
    var content_element = $( '#content' );

    var path_parts = this.path.match( /^(.+\/~cores\/)(.*)$/ );
    var current_core = path_parts[2];

    sammy.trigger
    (
      'cores_load_data',
      {
        callback : function( cores )
        {
          sammy.trigger
          (
            'cores_load_template',
            {
              content_element : content_element,
              callback : function()
              {
                var cores_element = $( '#cores', content_element );
                var navigation_element = $( '#navigation', cores_element );
                var data_element = $( '#data', cores_element );
                var core_data_element = $( '#core-data', data_element );
                var index_data_element = $( '#index-data', data_element );

                sammy.trigger
                (
                  'cores_build_navigation',
                  {
                    cores : cores,
                    basepath : path_parts[1],
                    current_core : current_core,
                    navigation_element : navigation_element
                  }
                );

                var core_data = cores[current_core];
                var core_basepath = $( '#' + current_core, app.menu_element ).attr( 'data-basepath' );

                // core-data

                $( '.startTime dd', core_data_element )
                  .html( core_data.startTime );

                $( '.instanceDir dd', core_data_element )
                  .html( core_data.instanceDir );

                $( '.dataDir dd', core_data_element )
                  .html( core_data.dataDir );

                // index-data

                $( '.lastModified dd', index_data_element )
                  .html( core_data.index.lastModified || '-' );

                $( '.version dd', index_data_element )
                  .html( core_data.index.version );

                $( '.numDocs dd', index_data_element )
                  .html( core_data.index.numDocs );

                $( '.maxDoc dd', index_data_element )
                  .html( core_data.index.maxDoc );

                $( '.deletedDocs dd', index_data_element )
                  .html( core_data.index.deletedDocs || '-' );

                $( '.optimized dd', index_data_element )
                  .addClass( !core_data.index.hasDeletions ? 'ico-1' : 'ico-0' );

                $( '#actions #optimize', cores_element )
                  .show();

                $( '.optimized dd span', index_data_element )
                  .html( !core_data.index.hasDeletions ? 'yes' : 'no' );

                $( '.current dd', index_data_element )
                  .addClass( core_data.index.current ? 'ico-1' : 'ico-0' );

                $( '.current dd span', index_data_element )
                  .html( core_data.index.current ? 'yes' : 'no' );

                $( '.directory dd', index_data_element )
                  .html
                  (
                    core_data.index.directory
                      .replace( /:/g, ':' )
                      .replace( /@/g, '@' )
                  );

                var core_names = [];
                var core_selects = $( '#actions select', cores_element );

                for( var key in cores )
                {
                  core_names.push( '<option value="' + key + '">' + key + '</option>' )
                }

                core_selects
                  .html( core_names.join( "\n") );

                $( 'option[value="' + current_core + '"]', core_selects.filter( '.other' ) )
                  .remove();

                $( 'input[data-core="current"]', cores_element )
                  .val( current_core );

                // layout

                var ui_block = $( '#ui-block' );
                var actions_element = $( '.actions', cores_element );
                var div_action = $( 'div.action', actions_element );

                ui_block
                  .css( 'opacity', 0.7 )
                  .width( cores_element.width() + 10 )
                  .height( cores_element.height() );

                if( $( '#cloud.global' ).is( ':visible' ) )
                {
                  $( '.cloud', div_action )
                    .show();
                }

                $( 'button.action', actions_element )
                  .die( 'click' )
                  .live
                  (
                    'click',
                    function( event )
                    {
                      var self = $( this );

                      self
                        .toggleClass( 'open' );

                      $( '.action.' + self.attr( 'id' ), actions_element )
                        .trigger( 'open' );

                      return false;
                    }
                  );

                div_action
                  .die( 'close' )
                  .live
                  (
                    'close',
                    function( event )
                    {
                      div_action.hide();
                      ui_block.hide();
                    }
                  )
                  .die( 'open' )
                  .live
                  (
                    'open',
                    function( event )
                    {
                      var self = $( this );
                      var rel = $( '#' + self.data( 'rel' ) );

                      self
                        .trigger( 'close' )
                        .show()
                        .css( 'left', rel.position().left );

                      ui_block
                        .show();
                    }
                  );

                $( 'form button.reset', actions_element )
                  .die( 'click' )
                  .live
                  (
                    'click',
                    function( event )
                    {
                      $( this ).closest( 'div.action' )
                        .trigger( 'close' );
                    }
                  );

                var form_callback = {

                  rename : function( form, response )
                  {
                    var url = path_parts[1] + $( 'input[name="other"]', form ).val();
                    context.redirect( url );
                  }

                };

                $( 'form', div_action )
                  .ajaxForm
                  (
                    {
                      url : app.config.solr_path + app.config.core_admin_path + '?wt=json&indexInfo=false',
                      dataType : 'json',
                      beforeSubmit : function( array, form, options )
                      {
                        $( 'button[type="submit"] span', form )
                          .addClass( 'loader' );
                      },
                      success : function( response, status_text, xhr, form )
                      {
                        var action = $( 'input[name="action"]', form ).val().toLowerCase();

                        delete app.cores_data;

                        if( form_callback[action] )
                        {
                         form_callback[action]( form, response );
                        }
                        else
                        {
                          sammy.refresh();
                        }

                        $( 'button.reset', form )
                          .trigger( 'click' );
                      },
                      error : function( xhr, text_status, error_thrown )
                      {
                        var response = null;
                        eval( 'response = ' + xhr.responseText + ';' );

                        var error_elem = $( '.error', div_action.filter( ':visible' ) );
                        error_elem.show();
                        $( 'span', error_elem ).text( response.error.msg );
                      },
                      complete : function()
                      {
                        $( 'button span.loader', actions_element )
                          .removeClass( 'loader' );
                      }
                    }
                  );

                var reload_button = $( '#actions #reload', cores_element );
                reload_button
                  .die( 'click' )
                  .live
                  (
                    'click',
                    function( event )
                    {
                      $.ajax
                      (
                        {
                          url : app.config.solr_path + app.config.core_admin_path + '?wt=json&action=RELOAD&core=' + current_core,
                          dataType : 'json',
                          context : $( this ),
                          beforeSend : function( xhr, settings )
                          {
                            $( 'span', this )
                              .addClass( 'loader' );
                          },
                          success : function( response, text_status, xhr )
                          {
                            this
                              .addClass( 'success' );

                            delete app.cores_data;
                            sammy.refresh();

                            window.setTimeout
                            (
                              function()
                              {
                                reload_button
                                  .removeClass( 'success' );
                              },
                              1000
                            );
                          },
                          error : function( xhr, text_status, error_thrown )
                          {
                          },
                          complete : function( xhr, text_status )
                          {
                            $( 'span', this )
                              .removeClass( 'loader' );
                          }
                        }
                      );
                    }
                  );

                $( '#actions #unload', cores_element )
                  .die( 'click' )
                  .live
                  (
                    'click',
                    function( event )
                    {
                      var ret = confirm( 'Do you really want to unload Core "' + current_core + '"?' );
                      if( !ret )
                      {
                        return false;
                      }

                      $.ajax
                      (
                        {
                          url : app.config.solr_path + app.config.core_admin_path + '?wt=json&action=UNLOAD&core=' + current_core,
                          dataType : 'json',
                          context : $( this ),
                          beforeSend : function( xhr, settings )
                          {
                            $( 'span', this )
                              .addClass( 'loader' );
                          },
                          success : function( response, text_status, xhr )
                          {
                            delete app.cores_data;
                            context.redirect( path_parts[1].substr( 0, path_parts[1].length - 1 ) );
                          },
                          error : function( xhr, text_status, error_thrown )
                          {
                          },
                          complete : function( xhr, text_status )
                          {
                            $( 'span', this )
                              .removeClass( 'loader' );
                          }
                        }
                      );
                    }
                  );

                var optimize_button = $( '#actions #optimize', cores_element );
                optimize_button
                  .die( 'click' )
                  .live
                  (
                    'click',
                    function( event )
                    {
                      $.ajax
                      (
                        {
                          url : core_basepath + '/update?optimize=true&waitFlush=true&wt=json',
                          dataType : 'json',
                          context : $( this ),
                          beforeSend : function( xhr, settings )
                          {
                            $( 'span', this )
                              .addClass( 'loader' );
                          },
                          success : function( response, text_status, xhr )
                          {
                            this
                              .addClass( 'success' );

                            window.setTimeout
                            (
                              function()
                              {
                                optimize_button
                                  .removeClass( 'success' );
                              },
                              1000
                            );

                            $( '.optimized dd.ico-0', index_data_element )
                              .removeClass( 'ico-0' )
                              .addClass( 'ico-1' );
                          },
                          error : function( xhr, text_status, error_thrown)
                          {
                            console.warn( 'd0h, optimize broken!' );
                          },
                          complete : function( xhr, text_status )
                          {
                            $( 'span', this )
                              .removeClass( 'loader' );
                          }
                        }
                      );
                    }
                  );

                $( '.timeago', data_element )
                  .timeago();

                $( 'ul', data_element )
                  .each
                  (
                    function( i, element )
                    {
                      $( 'li:odd', element )
                        .addClass( 'odd' );
                    }
                  )
              }
            }
          );
        }
      }
    );
  }
);


text:
{% extends "base.html" %}
{% set active_page = "login" %}

{% block body_content %}

Sign In

        <form class="form-horizontal" accept-charset="UTF-8"
              action="/login.passwd" method="post">

                Username
                <input autocapitolize="off" autofocus="autofocus"
                       id="login_field" name="login" tabindex="1" type="text"
                       value="{{username}}"/>

                Password
                <input autocomplete="disabled" class="input-block" id="password"
                       name="passwd" tabindex="2" type="password"/>

                <input type="hidden" name="next" value="{{next}}"/>
                <input class="btn" name="commit" tabindex="3" type="submit"
                       value="Sign in"/>

        </form>

{% endblock body_content %}


text:
<md-sidenav-container>
    <md-sidenav mode="side" [opened]="sidebarOpened" class="bg2">

		<md-list>
		  <md-list-item>
		    PARAGRAPHE
		  </md-list-item>
		  <md-list-item>
		    WORDS
		  </md-list-item>
		  <md-list-item>
		    LIST
		  </md-list-item>
		</md-list>

			<particles [style]="myStyle" [width]="particleWidth" [height]="particleHeight" [params]="myParams"></particles>

    </md-sidenav>

Paragraphe

	    			<md-slider (change)="reloadParagraphes()" warn min="0" max="10" step="1" [(ngModel)]="paragrapheNumberValue" thumb-label="true"></md-slider>

	    			<md-slider (change)="reloadParagraphes()" warn min="0" max="30" step="5" thumb-label="true" [(ngModel)]="paragrapheSizeValue" ></md-slider>

	    			<button md-button [ngxClipboard]="paragraphes">
	    			</button>

    		<textarea #paragraphes [(ngModel)]="outputParagrapheString" class="fake-hidden"></textarea>

{{t}}

Words

	    			<md-slider (change)="reloadWords()" warn min="0" max="30" step="5" [(ngModel)]="wordNumberValue" thumb-label="true"></md-slider>

	    			<button md-button [ngxClipboard]="words">
	    			</button>

    		<textarea #words [(ngModel)]="outputWords" class="fake-hidden"></textarea>

    			{{outputWords}}

List

	    			<md-slider (change)="reloadLists()" warn min="0" max="10" step="1" [(ngModel)]="listNumberValue" thumb-label="true"></md-slider>

	    			<md-slider (change)="reloadLists()" warn min="0" max="30" step="5" thumb-label="true" [(ngModel)]="listSizeValue" ></md-slider>

	    			<button md-button [ngxClipboard]="lists">
	    			</button>

    		<textarea #lists [(ngModel)]="outputListString" class="fake-hidden"></textarea>

{{t}}

	<app-footer></app-footer>
</md-sidenav-container>


text:
from django.conf import settings
from django.utils import translation

import logging
logger = logging.getLogger(__name__)

class SyncLanguageCookie(object):
    """Sync the user preferred language
        Detect if different exists among COOKIE language code and url language code
    """

    def process_response(self, request, response):
        try:
            # if language CODE in URL is different from COOKIE code, sync them
            url_lang_code = translation.get_language()
            cookie_lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)

            if url_lang_code != cookie_lang_code:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, url_lang_code)

            if cookie_lang_code == None:
                cookie_lang_code = url_lang_code

            return response
        except Exception, ex:
            logger.error(str(ex))
            return response


text:
package com.tomkasp.fitapp.activitytrackers.application.commands.handlers;

import com.tomkasp.common.service.UserService;
import com.tomkasp.fitapp.activitytrackers.application.commands.ExchangeStravaTokenCommand;
import com.tomkasp.fitapp.activitytrackers.domain.ActivitySource;
import com.tomkasp.fitapp.activitytrackers.domain.TrackersData;
import com.tomkasp.fitapp.activitytrackers.infrastructure.TrackersDataRepository;
import com.tomkasp.fitapp.cqrs.command.handler.CommandHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author Tomasz Kasprzycki
 */
@Service
public class UpdateStravaMetadata implements CommandHandler<ExchangeStravaTokenCommand, Void> {

    private final Logger log = LoggerFactory.getLogger(UpdateStravaMetadata.class);

    private final UserService userService;
    private final TrackersDataRepository trackersDataRepository;

    @Autowired
    public UpdateStravaMetadata(UserService userService, TrackersDataRepository trackersDataRepository) {
        this.userService = userService;
        this.trackersDataRepository = trackersDataRepository;
    }

    @Override
    public Void handle(ExchangeStravaTokenCommand command) {
        log.info("updating strava metadata");
        final Optional<TrackersData> trackersData = trackersDataRepository.findByUserId(userService.getUserWithAuthorities().getId());
        trackersData.map(result -> {
            log.info("updating trackers data entry with code: {}", command.getCode());
//                result.getTrackerMetadata().setStravaCode(command.getCode());
                return trackersDataRepository.save(result);
            }
        ).orElseGet(() -> {
            log.info("creating new trackersdata entry");
            TrackersData freshTrackersData = new TrackersData();
            freshTrackersData.user(userService.getUserWithAuthorities())
                .activitySource(ActivitySource.STRAVA);
//                .trackerMetadata(new TrackersMetadata().setStravaCode(command.getCode()));
            return trackersDataRepository.save(freshTrackersData);
        });
        return null;
    }
}


text:
var Cancel = require('../../../lib/cancel/Cancel');

describe('Cancel', function() {
  describe('toString', function() {
    it('returns correct result when message is not specified', function() {
      var cancel = new Cancel();
      expect(cancel.toString()).toBe('Cancel');
    });

    it('returns correct result when message is specified', function() {
      var cancel = new Cancel('Operation has been canceled.');
      expect(cancel.toString()).toBe('Cancel: Operation has been canceled.');
    });
  });
});


text:
{% extends "account/base.html" %}

{% load i18n %}
{% load account %}

{% block head_title %}{% trans "Password Reset" %}{% endblock %}

{% block content %}

{% trans "Password Reset" %}

    {% if user.is_authenticated %}
    {% include "account/snippets/already_logged_in.html" %}
    {% endif %}

{% blocktrans %}We have sent you an e-mail. Please contact us if you do not receive it within a few minutes.{% endblocktrans %}

{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="50dip" />

</LinearLayout>


text:
layout: page
title: "NRSC 6100: Advances in Neuroscience Seminar Statistics"
comments: true
description: "blanks"
keywords: "NRSC,6100,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 0.35%

**Percent incomplete**: 0.28%

**Average grade** (4.0 scale): 3.98

**Standard deviation in grades** (4.0 scale): 0.06

**Average workload** (raw): 1.5

**Standard deviation in workload** (raw): 0.29

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 5.13

**Standard deviation in course rating** (6 point scale): 0.39

**Average instructor rating** (6 point scale): 5.56

**Standard deviation in instructor rating** (6 point scale): 0.29

**Instructors**: Ryan Karn Bachtell, Serge Campeau, Susan Patterson, Robert Spencer

#### GENERAL CLASS INFORMATION

**Years provided**: Fall 2006, Spring 2007, Fall 2007, Spring 2008, Fall 2008, Spring 2009, Fall 2009, Spring 2010, Fall 2010, Spring 2012, Fall 2012, Spring 2013, Fall 2013, Spring 2014, Fall 2014, Fall 2015, Spring 2016, Fall 2016, Spring 2017

**Credits**: 2

**RAP/Honors class?** Neither

**Number of Sections**: 19

**Department**: PSYC

**College**: College of Arts and Sciences

**A&S Division**: Natural Sciences

**Level**: Masters

**Activity**: SEM - Seminar


text:
@protocol windowDelegate <NSObject>

-(void)openNewPage:(NSString*)pageTitle;

@end


text:
var Descriptor = require('../Descriptor');

/**
 * @constructor
 */
Descriptor['tdta'] = function() {
  /** @type {number} */
  this.offset;
  /** @type {number} */
  this.length;
  /** @type {!(Array.<number>|Uint8Array)} */
  this.value;
};

/**
 * @param {StreamReader} stream
 */
Descriptor['tdta'].prototype.parse = function(stream) {
  /** @type {number} */
  var length;

  this.offset = stream.tell();

  length = stream.readUint32();
  this.data = stream.read(length);

  this.length = stream.tell() - this.offset;
};

Descriptor['tdta'].prototype.toObject = function() {
  return this.data;
}


text:
#include "postgres.h"

#include <unistd.h>

#include "access/xact.h"
#include "miscadmin.h"
#include "replication/syncrep.h"
#include "replication/walsender.h"
#include "replication/walsender_private.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/ps_status.h"

/* User-settable parameters for sync rep */
char	   *SyncRepStandbyNames;

#define SyncStandbysDefined() \
	(SyncRepStandbyNames != NULL && SyncRepStandbyNames[0] != '\0')

static bool announce_next_takeover = true;

static int	SyncRepWaitMode = SYNC_REP_NO_WAIT;

static void SyncRepQueueInsert(int mode);
static void SyncRepCancelWait(void);
static int	SyncRepWakeQueue(bool all, int mode);

static int	SyncRepGetStandbyPriority(void);

#ifdef USE_ASSERT_CHECKING
static bool SyncRepQueueIsOrderedByLSN(int mode);
#endif

/*
 * ===========================================================
 * Synchronous Replication functions for normal user backends
 * ===========================================================
 */

/*
 * Wait for synchronous replication, if requested by user.
 *
 * Initially backends start in state SYNC_REP_NOT_WAITING and then
 * change that state to SYNC_REP_WAITING before adding ourselves
 * to the wait queue. During SyncRepWakeQueue() a WALSender changes
 * the state to SYNC_REP_WAIT_COMPLETE once replication is confirmed.
 * This backend then resets its state to SYNC_REP_NOT_WAITING.
 */
void
SyncRepWaitForLSN(XLogRecPtr XactCommitLSN)
{
	char	   *new_status = NULL;
	const char *old_status;
	int			mode = SyncRepWaitMode;

	/*
	 * Fast exit if user has not requested sync replication, or there are no
	 * sync replication standby names defined. Note that those standbys don't
	 * need to be connected.
	 */
	if (!SyncRepRequested() || !SyncStandbysDefined())
		return;

	Assert(SHMQueueIsDetached(&(MyProc->syncRepLinks)));
	Assert(WalSndCtl != NULL);

	LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
	Assert(MyProc->syncRepState == SYNC_REP_NOT_WAITING);

	/*
	 * We don't wait for sync rep if WalSndCtl->sync_standbys_defined is not
	 * set.  See SyncRepUpdateSyncStandbysDefined.
	 *
	 * Also check that the standby hasn't already replied. Unlikely race
	 * condition but we'll be fetching that cache line anyway so it's likely
	 * to be a low cost check.
	 */
	if (!WalSndCtl->sync_standbys_defined ||
		XactCommitLSN <= WalSndCtl->lsn[mode])
	{
		LWLockRelease(SyncRepLock);
		return;
	}

	/*
	 * Set our waitLSN so WALSender will know when to wake us, and add
	 * ourselves to the queue.
	 */
	MyProc->waitLSN = XactCommitLSN;
	MyProc->syncRepState = SYNC_REP_WAITING;
	SyncRepQueueInsert(mode);
	Assert(SyncRepQueueIsOrderedByLSN(mode));
	LWLockRelease(SyncRepLock);

	/* Alter ps display to show waiting for sync rep. */
	if (update_process_title)
	{
		int			len;

		old_status = get_ps_display(&len);
		new_status = (char *) palloc(len + 32 + 1);
		memcpy(new_status, old_status, len);
		sprintf(new_status + len, " waiting for %X/%X",
				(uint32) (XactCommitLSN >> 32), (uint32) XactCommitLSN);
		set_ps_display(new_status, false);
		new_status[len] = '\0'; /* truncate off " waiting ..." */
	}

	/*
	 * Wait for specified LSN to be confirmed.
	 *
	 * Each proc has its own wait latch, so we perform a normal latch
	 * check/wait loop here.
	 */
	for (;;)
	{
		int			syncRepState;

		/* Must reset the latch before testing state. */
		ResetLatch(MyLatch);

		/*
		 * Try checking the state without the lock first.  There's no
		 * guarantee that we'll read the most up-to-date value, so if it looks
		 * like we're still waiting, recheck while holding the lock.  But if
		 * it looks like we're done, we must really be done, because once
		 * walsender changes the state to SYNC_REP_WAIT_COMPLETE, it will
		 * never update it again, so we can't be seeing a stale value in that
		 * case.
		 */
		syncRepState = MyProc->syncRepState;
		if (syncRepState == SYNC_REP_WAITING)
			syncRepState = MyProc->syncRepState;
		if (syncRepState == SYNC_REP_WAIT_COMPLETE)
			break;

		/*
		 * If a wait for synchronous replication is pending, we can neither
		 * acknowledge the commit nor raise ERROR or FATAL.  The latter would
		 * lead the client to believe that that the transaction aborted, which
		 * is not true: it's already committed locally. The former is no good
		 * either: the client has requested synchronous replication, and is
		 * entitled to assume that an acknowledged commit is also replicated,
		 * which might not be true. So in this case we issue a WARNING (which
		 * some clients may be able to interpret) and shut off further output.
		 * We do NOT reset ProcDiePending, so that the process will die after
		 * the commit is cleaned up.
		 */
		if (ProcDiePending)
		{
			ereport(WARNING,
					(errcode(ERRCODE_ADMIN_SHUTDOWN),
					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
			whereToSendOutput = DestNone;
			SyncRepCancelWait();
			break;
		}

		/*
		 * It's unclear what to do if a query cancel interrupt arrives.  We
		 * can't actually abort at this point, but ignoring the interrupt
		 * altogether is not helpful, so we just terminate the wait with a
		 * suitable warning.
		 */
		if (QueryCancelPending)
		{
			QueryCancelPending = false;
			ereport(WARNING,
					(errmsg("canceling wait for synchronous replication due to user request"),
					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
			SyncRepCancelWait();
			break;
		}

		/*
		 * If the postmaster dies, we'll probably never get an
		 * acknowledgement, because all the wal sender processes will exit. So
		 * just bail out.
		 */
		if (!PostmasterIsAlive())
		{
			ProcDiePending = true;
			whereToSendOutput = DestNone;
			SyncRepCancelWait();
			break;
		}

		/*
		 * Wait on latch.  Any condition that should wake us up will set the
		 * latch, so no need for timeout.
		 */
		WaitLatch(MyLatch, WL_LATCH_SET | WL_POSTMASTER_DEATH, -1);
	}

	/*
	 * WalSender has checked our LSN and has removed us from queue. Clean up
	 * state and leave.  It's OK to reset these shared memory fields without
	 * holding SyncRepLock, because any walsenders will ignore us anyway when
	 * we're not on the queue.
	 */
	Assert(SHMQueueIsDetached(&(MyProc->syncRepLinks)));
	MyProc->syncRepState = SYNC_REP_NOT_WAITING;
	MyProc->waitLSN = 0;

	if (new_status)
	{
		/* Reset ps display */
		set_ps_display(new_status, false);
		pfree(new_status);
	}
}

/*
 * Insert MyProc into the specified SyncRepQueue, maintaining sorted invariant.
 *
 * Usually we will go at tail of queue, though it's possible that we arrive
 * here out of order, so start at tail and work back to insertion point.
 */
static void
SyncRepQueueInsert(int mode)
{
	PGPROC	   *proc;

	Assert(mode >= 0 && mode < NUM_SYNC_REP_WAIT_MODE);
	proc = (PGPROC *) SHMQueuePrev(&(WalSndCtl->SyncRepQueue[mode]),
								   &(WalSndCtl->SyncRepQueue[mode]),
								   offsetof(PGPROC, syncRepLinks));

	while (proc)
	{
		/*
		 * Stop at the queue element that we should after to ensure the queue
		 * is ordered by LSN.
		 */
		if (proc->waitLSN < MyProc->waitLSN)
			break;

		proc = (PGPROC *) SHMQueuePrev(&(WalSndCtl->SyncRepQueue[mode]),
									   &(proc->syncRepLinks),
									   offsetof(PGPROC, syncRepLinks));
	}

	if (proc)
		SHMQueueInsertAfter(&(proc->syncRepLinks), &(MyProc->syncRepLinks));
	else
		SHMQueueInsertAfter(&(WalSndCtl->SyncRepQueue[mode]), &(MyProc->syncRepLinks));
}

/*
 * Acquire SyncRepLock and cancel any wait currently in progress.
 */
static void
SyncRepCancelWait(void)
{
	LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
	if (!SHMQueueIsDetached(&(MyProc->syncRepLinks)))
		SHMQueueDelete(&(MyProc->syncRepLinks));
	MyProc->syncRepState = SYNC_REP_NOT_WAITING;
	LWLockRelease(SyncRepLock);
}

void
SyncRepCleanupAtProcExit(void)
{
	if (!SHMQueueIsDetached(&(MyProc->syncRepLinks)))
	{
		LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
		SHMQueueDelete(&(MyProc->syncRepLinks));
		LWLockRelease(SyncRepLock);
	}
}

/*
 * ===========================================================
 * Synchronous Replication functions for wal sender processes
 * ===========================================================
 */

/*
 * Take any action required to initialise sync rep state from config
 * data. Called at WALSender startup and after each SIGHUP.
 */
void
SyncRepInitConfig(void)
{
	int			priority;

	/*
	 * Determine if we are a potential sync standby and remember the result
	 * for handling replies from standby.
	 */
	priority = SyncRepGetStandbyPriority();
	if (MyWalSnd->sync_standby_priority != priority)
	{
		LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
		MyWalSnd->sync_standby_priority = priority;
		LWLockRelease(SyncRepLock);
		ereport(DEBUG1,
			(errmsg("standby \"%s\" now has synchronous standby priority %u",
					application_name, priority)));
	}
}

/*
 * Find the WAL sender servicing the synchronous standby with the lowest
 * priority value, or NULL if no synchronous standby is connected. If there
 * are multiple standbys with the same lowest priority value, the first one
 * found is selected. The caller must hold SyncRepLock.
 */
WalSnd *
SyncRepGetSynchronousStandby(void)
{
	WalSnd	   *result = NULL;
	int			result_priority = 0;
	int			i;

	for (i = 0; i < max_wal_senders; i++)
	{
		/* Use volatile pointer to prevent code rearrangement */
		volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
		int			this_priority;

		/* Must be active */
		if (walsnd->pid == 0)
			continue;

		/* Must be streaming */
		if (walsnd->state != WALSNDSTATE_STREAMING)
			continue;

		/* Must be synchronous */
		this_priority = walsnd->sync_standby_priority;
		if (this_priority == 0)
			continue;

		/* Must have a lower priority value than any previous ones */
		if (result != NULL && result_priority <= this_priority)
			continue;

		/* Must have a valid flush position */
		if (XLogRecPtrIsInvalid(walsnd->flush))
			continue;

		result = (WalSnd *) walsnd;
		result_priority = this_priority;

		/*
		 * If priority is equal to 1, there cannot be any other WAL senders
		 * with a lower priority, so we're done.
		 */
		if (this_priority == 1)
			return result;
	}

	return result;
}

/*
 * Update the LSNs on each queue based upon our latest state. This
 * implements a simple policy of first-valid-standby-releases-waiter.
 *
 * Other policies are possible, which would change what we do here and what
 * perhaps also which information we store as well.
 */
void
SyncRepReleaseWaiters(void)
{
	volatile WalSndCtlData *walsndctl = WalSndCtl;
	WalSnd	   *syncWalSnd;
	int			numwrite = 0;
	int			numflush = 0;

	/*
	 * If this WALSender is serving a standby that is not on the list of
	 * potential standbys then we have nothing to do. If we are still starting
	 * up, still running base backup or the current flush position is still
	 * invalid, then leave quickly also.
	 */
	if (MyWalSnd->sync_standby_priority == 0 ||
		MyWalSnd->state < WALSNDSTATE_STREAMING ||
		XLogRecPtrIsInvalid(MyWalSnd->flush))
		return;

	/*
	 * We're a potential sync standby. Release waiters if we are the highest
	 * priority standby.
	 */
	LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);
	syncWalSnd = SyncRepGetSynchronousStandby();

	/* We should have found ourselves at least */
	Assert(syncWalSnd != NULL);

	/*
	 * If we aren't managing the highest priority standby then just leave.
	 */
	if (syncWalSnd != MyWalSnd)
	{
		LWLockRelease(SyncRepLock);
		announce_next_takeover = true;
		return;
	}

	/*
	 * Set the lsn first so that when we wake backends they will release up to
	 * this location.
	 */
	if (walsndctl->lsn[SYNC_REP_WAIT_WRITE] < MyWalSnd->write)
	{
		walsndctl->lsn[SYNC_REP_WAIT_WRITE] = MyWalSnd->write;
		numwrite = SyncRepWakeQueue(false, SYNC_REP_WAIT_WRITE);
	}
	if (walsndctl->lsn[SYNC_REP_WAIT_FLUSH] < MyWalSnd->flush)
	{
		walsndctl->lsn[SYNC_REP_WAIT_FLUSH] = MyWalSnd->flush;
		numflush = SyncRepWakeQueue(false, SYNC_REP_WAIT_FLUSH);
	}

	LWLockRelease(SyncRepLock);

	elog(DEBUG3, "released %d procs up to write %X/%X, %d procs up to flush %X/%X",
		 numwrite, (uint32) (MyWalSnd->write >> 32), (uint32) MyWalSnd->write,
	   numflush, (uint32) (MyWalSnd->flush >> 32), (uint32) MyWalSnd->flush);

	/*
	 * If we are managing the highest priority standby, though we weren't
	 * prior to this, then announce we are now the sync standby.
	 */
	if (announce_next_takeover)
	{
		announce_next_takeover = false;
		ereport(LOG,
				(errmsg("standby \"%s\" is now the synchronous standby with priority %u",
						application_name, MyWalSnd->sync_standby_priority)));
	}
}

/*
 * Check if we are in the list of sync standbys, and if so, determine
 * priority sequence. Return priority if set, or zero to indicate that
 * we are not a potential sync standby.
 *
 * Compare the parameter SyncRepStandbyNames against the application_name
 * for this WALSender, or allow any name if we find a wildcard "*".
 */
static int
SyncRepGetStandbyPriority(void)
{
	char	   *rawstring;
	List	   *elemlist;
	ListCell   *l;
	int			priority = 0;
	bool		found = false;

	/*
	 * Since synchronous cascade replication is not allowed, we always set the
	 * priority of cascading walsender to zero.
	 */
	if (am_cascading_walsender)
		return 0;

	/* Need a modifiable copy of string */
	rawstring = pstrdup(SyncRepStandbyNames);

	/* Parse string into list of identifiers */
	if (!SplitIdentifierString(rawstring, ',', &elemlist))
	{
		/* syntax error in list */
		pfree(rawstring);
		list_free(elemlist);
		/* GUC machinery will have already complained - no need to do again */
		return 0;
	}

	foreach(l, elemlist)
	{
		char	   *standby_name = (char *) lfirst(l);

		priority++;

		if (pg_strcasecmp(standby_name, application_name) == 0 ||
			pg_strcasecmp(standby_name, "*") == 0)
		{
			found = true;
			break;
		}
	}

	pfree(rawstring);
	list_free(elemlist);

	return (found ? priority : 0);
}

/*
 * Walk the specified queue from head.  Set the state of any backends that
 * need to be woken, remove them from the queue, and then wake them.
 * Pass all = true to wake whole queue; otherwise, just wake up to
 * the walsender's LSN.
 *
 * Must hold SyncRepLock.
 */
static int
SyncRepWakeQueue(bool all, int mode)
{
	volatile WalSndCtlData *walsndctl = WalSndCtl;
	PGPROC	   *proc = NULL;
	PGPROC	   *thisproc = NULL;
	int			numprocs = 0;

	Assert(mode >= 0 && mode < NUM_SYNC_REP_WAIT_MODE);
	Assert(SyncRepQueueIsOrderedByLSN(mode));

	proc = (PGPROC *) SHMQueueNext(&(WalSndCtl->SyncRepQueue[mode]),
								   &(WalSndCtl->SyncRepQueue[mode]),
								   offsetof(PGPROC, syncRepLinks));

	while (proc)
	{
		/*
		 * Assume the queue is ordered by LSN
		 */
		if (!all && walsndctl->lsn[mode] < proc->waitLSN)
			return numprocs;

		/*
		 * Move to next proc, so we can delete thisproc from the queue.
		 * thisproc is valid, proc may be NULL after this.
		 */
		thisproc = proc;
		proc = (PGPROC *) SHMQueueNext(&(WalSndCtl->SyncRepQueue[mode]),
									   &(proc->syncRepLinks),
									   offsetof(PGPROC, syncRepLinks));

		/*
		 * Set state to complete; see SyncRepWaitForLSN() for discussion of
		 * the various states.
		 */
		thisproc->syncRepState = SYNC_REP_WAIT_COMPLETE;

		/*
		 * Remove thisproc from queue.
		 */
		SHMQueueDelete(&(thisproc->syncRepLinks));

		/*
		 * Wake only when we have set state and removed from queue.
		 */
		SetLatch(&(thisproc->procLatch));

		numprocs++;
	}

	return numprocs;
}

/*
 * The checkpointer calls this as needed to update the shared
 * sync_standbys_defined flag, so that backends don't remain permanently wedged
 * if synchronous_standby_names is unset.  It's safe to check the current value
 * without the lock, because it's only ever updated by one process.  But we
 * must take the lock to change it.
 */
void
SyncRepUpdateSyncStandbysDefined(void)
{
	bool		sync_standbys_defined = SyncStandbysDefined();

	if (sync_standbys_defined != WalSndCtl->sync_standbys_defined)
	{
		LWLockAcquire(SyncRepLock, LW_EXCLUSIVE);

		/*
		 * If synchronous_standby_names has been reset to empty, it's futile
		 * for backends to continue to waiting.  Since the user no longer
		 * wants synchronous replication, we'd better wake them up.
		 */
		if (!sync_standbys_defined)
		{
			int			i;

			for (i = 0; i < NUM_SYNC_REP_WAIT_MODE; i++)
				SyncRepWakeQueue(true, i);
		}

		/*
		 * Only allow people to join the queue when there are synchronous
		 * standbys defined.  Without this interlock, there's a race
		 * condition: we might wake up all the current waiters; then, some
		 * backend that hasn't yet reloaded its config might go to sleep on
		 * the queue (and never wake up).  This prevents that.
		 */
		WalSndCtl->sync_standbys_defined = sync_standbys_defined;

		LWLockRelease(SyncRepLock);
	}
}

#ifdef USE_ASSERT_CHECKING
static bool
SyncRepQueueIsOrderedByLSN(int mode)
{
	PGPROC	   *proc = NULL;
	XLogRecPtr	lastLSN;

	Assert(mode >= 0 && mode < NUM_SYNC_REP_WAIT_MODE);

	lastLSN = 0;

	proc = (PGPROC *) SHMQueueNext(&(WalSndCtl->SyncRepQueue[mode]),
								   &(WalSndCtl->SyncRepQueue[mode]),
								   offsetof(PGPROC, syncRepLinks));

	while (proc)
	{
		/*
		 * Check the queue is ordered by LSN and that multiple procs don't
		 * have matching LSNs
		 */
		if (proc->waitLSN <= lastLSN)
			return false;

		lastLSN = proc->waitLSN;

		proc = (PGPROC *) SHMQueueNext(&(WalSndCtl->SyncRepQueue[mode]),
									   &(proc->syncRepLinks),
									   offsetof(PGPROC, syncRepLinks));
	}

	return true;
}
#endif

/*
 * ===========================================================
 * Synchronous Replication functions executed by any process
 * ===========================================================
 */

bool
check_synchronous_standby_names(char **newval, void **extra, GucSource source)
{
	char	   *rawstring;
	List	   *elemlist;

	/* Need a modifiable copy of string */
	rawstring = pstrdup(*newval);

	/* Parse string into list of identifiers */
	if (!SplitIdentifierString(rawstring, ',', &elemlist))
	{
		/* syntax error in list */
		GUC_check_errdetail("List syntax is invalid.");
		pfree(rawstring);
		list_free(elemlist);
		return false;
	}

	/*
	 * Any additional validation of standby names should go here.
	 *
	 * Don't attempt to set WALSender priority because this is executed by
	 * postmaster at startup, not WALSender, so the application_name is not
	 * yet correctly set.
	 */

	pfree(rawstring);
	list_free(elemlist);

	return true;
}

void
assign_synchronous_commit(int newval, void *extra)
{
	switch (newval)
	{
		case SYNCHRONOUS_COMMIT_REMOTE_WRITE:
			SyncRepWaitMode = SYNC_REP_WAIT_WRITE;
			break;
		case SYNCHRONOUS_COMMIT_REMOTE_FLUSH:
			SyncRepWaitMode = SYNC_REP_WAIT_FLUSH;
			break;
		default:
			SyncRepWaitMode = SYNC_REP_NO_WAIT;
			break;
	}
}