text:
package org.onosproject.incubator.store.virtual.impl;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.util.KryoNamespace;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.Leadership;
import org.onosproject.cluster.LeadershipAdminService;
import org.onosproject.cluster.LeadershipEvent;
import org.onosproject.cluster.LeadershipEventListener;
import org.onosproject.cluster.LeadershipService;
import org.onosproject.cluster.NodeId;
import org.onosproject.cluster.RoleInfo;
import org.onosproject.incubator.net.virtual.NetworkId;
import org.onosproject.incubator.net.virtual.VirtualNetworkMastershipStore;
import org.onosproject.mastership.MastershipEvent;
import org.onosproject.mastership.MastershipStoreDelegate;
import org.onosproject.mastership.MastershipTerm;
import org.onosproject.net.DeviceId;
import org.onosproject.net.MastershipRole;
import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
import org.onosproject.store.cluster.messaging.MessageSubject;
import org.onosproject.store.serializers.KryoNamespaces;
import org.onosproject.store.service.Serializer;
import org.slf4j.Logger;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.mastership.MastershipEvent.Type.BACKUPS_CHANGED;
import static org.onosproject.mastership.MastershipEvent.Type.MASTER_CHANGED;
import static org.onosproject.mastership.MastershipEvent.Type.SUSPENDED;
import static org.slf4j.LoggerFactory.getLogger;

import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import static com.google.common.base.Preconditions.checkArgument;

@Component(immediate = true, enabled = false)
@Service
public class ConsistentVirtualDeviceMastershipStore
        extends AbstractVirtualStore<MastershipEvent, MastershipStoreDelegate>
        implements VirtualNetworkMastershipStore {

    private final Logger log = getLogger(getClass());

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected LeadershipService leadershipService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected LeadershipAdminService leadershipAdminService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected ClusterService clusterService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected ClusterCommunicationService clusterCommunicator;

    private NodeId localNodeId;

    private static final MessageSubject ROLE_RELINQUISH_SUBJECT =
            new MessageSubject("virtual-mastership-store-device-role-relinquish");

    private static final Pattern DEVICE_MASTERSHIP_TOPIC_PATTERN =
            Pattern.compile("vnet:(.*),device:(.*)");

    private ExecutorService eventHandler;
    private ExecutorService messageHandlingExecutor;
    private ScheduledExecutorService transferExecutor;
    private final LeadershipEventListener leadershipEventListener =
            new InternalDeviceMastershipEventListener();

    private static final String NODE_ID_NULL = "Node ID cannot be null";
    private static final String NETWORK_ID_NULL = "Network ID cannot be null";
    private static final String DEVICE_ID_NULL = "Device ID cannot be null";
    private static final int WAIT_BEFORE_MASTERSHIP_HANDOFF_MILLIS = 3000;

    public static final Serializer SERIALIZER = Serializer.using(
            KryoNamespace.newBuilder()
                    .register(KryoNamespaces.API)
                    .register(MastershipRole.class)
                    .register(MastershipEvent.class)
                    .register(MastershipEvent.Type.class)
                    .register(VirtualDeviceId.class)
                    .build("VirtualMastershipStore"));

    @Activate
    public void activate() {
        eventHandler = Executors.newSingleThreadExecutor(
                groupedThreads("onos/store/virtual/mastership", "event-handler", log));

        messageHandlingExecutor =
                Executors.newSingleThreadExecutor(
                        groupedThreads("onos/store/virtual/mastership", "message-handler", log));
        transferExecutor =
                Executors.newSingleThreadScheduledExecutor(
                        groupedThreads("onos/store/virtual/mastership", "mastership-transfer-executor", log));
        clusterCommunicator.addSubscriber(ROLE_RELINQUISH_SUBJECT,
                                          SERIALIZER::decode,
                                          this::relinquishLocalRole,
                                          SERIALIZER::encode,
                                          messageHandlingExecutor);
        localNodeId = clusterService.getLocalNode().id();
        leadershipService.addListener(leadershipEventListener);

        log.info("Started");
    }

    @Deactivate
    public void deactivate() {
        clusterCommunicator.removeSubscriber(ROLE_RELINQUISH_SUBJECT);
        leadershipService.removeListener(leadershipEventListener);
        messageHandlingExecutor.shutdown();
        transferExecutor.shutdown();
        eventHandler.shutdown();
        log.info("Stopped");
    }

    @Override
    public CompletableFuture<MastershipRole> requestRole(NetworkId networkId,
                                                         DeviceId deviceId) {
        checkArgument(networkId != null, NETWORK_ID_NULL);
        checkArgument(deviceId != null, DEVICE_ID_NULL);

        String leadershipTopic = createDeviceMastershipTopic(networkId, deviceId);
        Leadership leadership = leadershipService.runForLeadership(leadershipTopic);
        return CompletableFuture
                .completedFuture(localNodeId.equals(leadership.leaderNodeId()) ?
                                         MastershipRole.MASTER : MastershipRole.STANDBY);
    }

    @Override
    public MastershipRole getRole(NetworkId networkId, NodeId nodeId, DeviceId deviceId) {
        checkArgument(networkId != null, NETWORK_ID_NULL);
        checkArgument(nodeId != null, NODE_ID_NULL);
        checkArgument(deviceId != null, DEVICE_ID_NULL);

        String leadershipTopic = createDeviceMastershipTopic(networkId, deviceId);
        Leadership leadership = leadershipService.getLeadership(leadershipTopic);
        NodeId leader = leadership == null ? null : leadership.leaderNodeId();
        List<NodeId> candidates = leadership == null ?
                ImmutableList.of() : ImmutableList.copyOf(leadership.candidates());
        return Objects.equal(nodeId, leader) ?
                MastershipRole.MASTER : candidates.contains(nodeId) ?
                MastershipRole.STANDBY : MastershipRole.NONE;
    }

    @Override
    public NodeId getMaster(NetworkId networkId, DeviceId deviceId) {
        checkArgument(deviceId != null, DEVICE_ID_NULL);

        return leadershipService.getLeader(createDeviceMastershipTopic(networkId, deviceId));
    }

    @Override
    public RoleInfo getNodes(NetworkId networkId, DeviceId deviceId) {
        checkArgument(networkId != null, NETWORK_ID_NULL);
        checkArgument(deviceId != null, DEVICE_ID_NULL);

        Map<NodeId, MastershipRole> roles = Maps.newHashMap();
        clusterService.getNodes()
                .forEach((node) -> roles.put(node.id(),
                                             getRole(networkId, node.id(), deviceId)));

        NodeId master = null;
        final List<NodeId> standbys = Lists.newLinkedList();

        List<NodeId> candidates = leadershipService
                .getCandidates(createDeviceMastershipTopic(networkId, deviceId));

        for (Map.Entry<NodeId, MastershipRole> entry : roles.entrySet()) {
            if (entry.getValue() == MastershipRole.MASTER) {
                master = entry.getKey();
            } else if (entry.getValue() == MastershipRole.STANDBY) {
                standbys.add(entry.getKey());
            }
        }

        List<NodeId> sortedStandbyList = candidates.stream()
                .filter(standbys::contains).collect(Collectors.toList());

        return new RoleInfo(master, sortedStandbyList);
    }

    @Override
    public Set<DeviceId> getDevices(NetworkId networkId, NodeId nodeId) {
        checkArgument(networkId != null, NETWORK_ID_NULL);
        checkArgument(nodeId != null, NODE_ID_NULL);

        // FIXME This result contains REMOVED device.
        // MastershipService cannot listen to DeviceEvent to GC removed topic,
        // since DeviceManager depend on it.
        // Reference count, etc. at LeadershipService layer?
        return leadershipService
                .ownedTopics(nodeId)
                .stream()
                .filter(this::isVirtualMastershipTopic)
                .map(this::extractDeviceIdFromTopic)
                .collect(Collectors.toSet());
    }

    @Override
    public CompletableFuture<MastershipEvent> setMaster(NetworkId networkId,
                                                        NodeId nodeId, DeviceId deviceId) {
        checkArgument(networkId != null, NETWORK_ID_NULL);
        checkArgument(nodeId != null, NODE_ID_NULL);
        checkArgument(deviceId != null, DEVICE_ID_NULL);

        String leadershipTopic = createDeviceMastershipTopic(networkId, deviceId);
        if (leadershipAdminService.promoteToTopOfCandidateList(leadershipTopic, nodeId)) {
            transferExecutor.schedule(() -> leadershipAdminService.transferLeadership(leadershipTopic, nodeId),
                                      WAIT_BEFORE_MASTERSHIP_HANDOFF_MILLIS, TimeUnit.MILLISECONDS);
        }
        return CompletableFuture.completedFuture(null);
    }

    @Override
    public MastershipTerm getTermFor(NetworkId networkId, DeviceId deviceId) {
        checkArgument(networkId != null, NETWORK_ID_NULL);
        checkArgument(deviceId != null, DEVICE_ID_NULL);

        String leadershipTopic = createDeviceMastershipTopic(networkId, deviceId);
        Leadership leadership = leadershipService.getLeadership(leadershipTopic);
        return leadership != null && leadership.leaderNodeId() != null ?
                MastershipTerm.of(leadership.leaderNodeId(),
                                  leadership.leader().term()) : null;
    }

    @Override
    public CompletableFuture<MastershipEvent> setStandby(NetworkId networkId,
                                                         NodeId nodeId,
                                                         DeviceId deviceId) {
        checkArgument(networkId != null, NETWORK_ID_NULL);
        checkArgument(nodeId != null, NODE_ID_NULL);
        checkArgument(deviceId != null, DEVICE_ID_NULL);

        NodeId currentMaster = getMaster(networkId, deviceId);
        if (!nodeId.equals(currentMaster)) {
            return CompletableFuture.completedFuture(null);
        }

        String leadershipTopic = createDeviceMastershipTopic(networkId, deviceId);
        List<NodeId> candidates = leadershipService.getCandidates(leadershipTopic);

        NodeId newMaster = candidates.stream()
                .filter(candidate -> !Objects.equal(nodeId, candidate))
                .findFirst()
                .orElse(null);
        log.info("Transitioning to role {} for {}. Next master: {}",
                 newMaster != null ? MastershipRole.STANDBY : MastershipRole.NONE,
                 deviceId, newMaster);

        if (newMaster != null) {
            return setMaster(networkId, newMaster, deviceId);
        }
        return relinquishRole(networkId, nodeId, deviceId);
    }

    @Override
    public CompletableFuture<MastershipEvent> relinquishRole(NetworkId networkId,
                                                             NodeId nodeId,
                                                             DeviceId deviceId) {
        checkArgument(networkId != null, NETWORK_ID_NULL);
        checkArgument(nodeId != null, NODE_ID_NULL);
        checkArgument(deviceId != null, DEVICE_ID_NULL);

        if (nodeId.equals(localNodeId)) {
            return relinquishLocalRoleByNetwork(networkId, deviceId);
        }

        log.debug("Forwarding request to relinquish "
                          + "role for vnet {} device {} to {}", deviceId, nodeId);
        return clusterCommunicator.sendAndReceive(
                new VirtualDeviceId(networkId, deviceId),
                ROLE_RELINQUISH_SUBJECT,
                SERIALIZER::encode,
                SERIALIZER::decode,
                nodeId);
    }

    private CompletableFuture<MastershipEvent> relinquishLocalRoleByNetwork(NetworkId networkId,
                                                                   DeviceId deviceId) {
        checkArgument(networkId != null, NETWORK_ID_NULL);
        checkArgument(deviceId != null, DEVICE_ID_NULL);

        String leadershipTopic = createDeviceMastershipTopic(networkId, deviceId);
        if (!leadershipService.getCandidates(leadershipTopic).contains(localNodeId)) {
            return CompletableFuture.completedFuture(null);
        }
        MastershipEvent.Type eventType = localNodeId.equals(leadershipService.getLeader(leadershipTopic)) ?
                MastershipEvent.Type.MASTER_CHANGED : MastershipEvent.Type.BACKUPS_CHANGED;
        leadershipService.withdraw(leadershipTopic);
        return CompletableFuture.completedFuture(new MastershipEvent(eventType,
                                                                     deviceId,
                                                                     getNodes(networkId, deviceId)));
    }

    private CompletableFuture<MastershipEvent>
    relinquishLocalRole(VirtualDeviceId virtualDeviceId) {
        return relinquishLocalRoleByNetwork(virtualDeviceId.networkId,
                                            virtualDeviceId.deviceId);
    }

    @Override
    public void relinquishAllRole(NetworkId networkId, NodeId nodeId) {
        // Noop. LeadershipService already takes care of detecting and purging stale locks.
    }

    private class InternalDeviceMastershipEventListener
            implements LeadershipEventListener {

        @Override
        public boolean isRelevant(LeadershipEvent event) {
            Leadership leadership = event.subject();
            return isVirtualMastershipTopic(leadership.topic());
        }

        @Override
        public void event(LeadershipEvent event) {
            eventHandler.execute(() -> handleEvent(event));
        }

        private void handleEvent(LeadershipEvent event) {
            Leadership leadership = event.subject();

            NetworkId networkId = extractNetworkIdFromTopic(leadership.topic());
            DeviceId deviceId = extractDeviceIdFromTopic(leadership.topic());

            RoleInfo roleInfo = event.type() != LeadershipEvent.Type.SERVICE_DISRUPTED ?
                    getNodes(networkId, deviceId) : new RoleInfo();

            switch (event.type()) {
                case LEADER_AND_CANDIDATES_CHANGED:
                    notifyDelegate(networkId, new MastershipEvent(BACKUPS_CHANGED,
                                                                  deviceId, roleInfo));
                    notifyDelegate(networkId, new MastershipEvent(MASTER_CHANGED,
                                                                  deviceId, roleInfo));
                    break;
                case LEADER_CHANGED:
                    notifyDelegate(networkId, new MastershipEvent(MASTER_CHANGED,
                                                                  deviceId, roleInfo));
                    break;
                case CANDIDATES_CHANGED:
                    notifyDelegate(networkId, new MastershipEvent(BACKUPS_CHANGED,
                                                                  deviceId, roleInfo));
                    break;
                case SERVICE_DISRUPTED:
                    notifyDelegate(networkId, new MastershipEvent(SUSPENDED,
                                                                  deviceId, roleInfo));
                    break;
                case SERVICE_RESTORED:
                    // Do nothing, wait for updates from peers
                    break;
                default:
            }
        }
    }

    private String createDeviceMastershipTopic(NetworkId networkId, DeviceId deviceId) {
        return String.format("vnet:%s,device:%s", networkId.toString(), deviceId.toString());
    }

    /**
     * Returns the virtual network identifier extracted from the topic.
     *
     * @param topic topic to extract virtual network identifier
     * @return an extracted virtual network identifier
     * @throws IllegalArgumentException the topic not match with the pattern
     * used for virtual network mastership store
     */
    private NetworkId extractNetworkIdFromTopic(String topic) {
        Matcher m = DEVICE_MASTERSHIP_TOPIC_PATTERN.matcher(topic);
        if (m.matches()) {
            return NetworkId.networkId(Long.getLong(m.group(1)));
        } else {
            throw new IllegalArgumentException("Invalid virtual mastership topic: "
                                                       + topic);
        }
    }

    /**
     * Returns the device identifier extracted from the topic.
     *
     * @param topic topic to extract device identifier
     * @return an extracted virtual device identifier
     * @throws IllegalArgumentException the topic not match with the pattern
     * used for virtual network mastership store
     */
    private DeviceId extractDeviceIdFromTopic(String topic) {
        Matcher m = DEVICE_MASTERSHIP_TOPIC_PATTERN.matcher(topic);
        if (m.matches()) {
            return DeviceId.deviceId(m.group(2));
        } else {
            throw new IllegalArgumentException("Invalid virtual mastership topic: "
                                                       + topic);
        }
    }

    /**
     * Returns whether the topic is matched with virtual mastership store topic.
     *
     * @param topic topic to match
     * @return True when the topic matched with virtual network mastership store
     */
    private boolean isVirtualMastershipTopic(String topic) {
        Matcher m = DEVICE_MASTERSHIP_TOPIC_PATTERN.matcher(topic);
        return m.matches();
    }

    /**
     * A wrapper class used for the communication service.
     */
    private class VirtualDeviceId {
        NetworkId networkId;
        DeviceId deviceId;

        public VirtualDeviceId(NetworkId networkId, DeviceId deviceId) {
            this.networkId = networkId;
            this.deviceId = deviceId;
        }

        public int hashCode() {
            return Objects.hashCode(networkId, deviceId);
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj instanceof VirtualDeviceId) {
                final VirtualDeviceId that = (VirtualDeviceId) obj;
                return this.getClass() == that.getClass() &&
                        Objects.equal(this.networkId, that.networkId) &&
                        Objects.equal(this.deviceId, that.deviceId);
            }
            return false;
        }
    }
}


text:
<?php

namespace Oro\Bundle\ApiBundle\Tests\Unit;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\ORMException;
use Oro\Bundle\ApiBundle\Util\DoctrineHelper;
use Oro\Component\TestUtils\ORM\Mocks\EntityManagerMock;
use Oro\Component\TestUtils\ORM\OrmTestCase;

class OrmRelatedTestCase extends OrmTestCase
{
    /** @var EntityManagerMock */
    protected $em;

    /** @var \PHPUnit\Framework\MockObject\MockObject|ManagerRegistry */
    protected $doctrine;

    /** @var DoctrineHelper */
    protected $doctrineHelper;

    /** @var string[] */
    protected $notManageableClassNames = [];

    protected function setUp()
    {
        $reader         = new AnnotationReader();
        $metadataDriver = new AnnotationDriver(
            $reader,
            'Oro\Bundle\ApiBundle\Tests\Unit\Fixtures\Entity'
        );

        $this->em = $this->getTestEntityManager();
        $this->em->getConfiguration()->setMetadataDriverImpl($metadataDriver);
        $this->em->getConfiguration()->setEntityNamespaces(
            [
                'Test' => 'Oro\Bundle\ApiBundle\Tests\Unit\Fixtures\Entity'
            ]
        );

        $this->doctrine = $this->createMock(ManagerRegistry::class);
        $this->doctrine->expects(self::any())
            ->method('getManagerForClass')
            ->willReturnCallback(
                function ($class) {
                    return !in_array($class, $this->notManageableClassNames, true)
                        ? $this->em
                        : null;
                }
            );
        $this->doctrine->expects(self::any())
            ->method('getAliasNamespace')
            ->willReturnCallback(
                function ($alias) {
                    if ('Test' !== $alias) {
                        throw ORMException::unknownEntityNamespace($alias);
                    }

                    return 'Oro\Bundle\ApiBundle\Tests\Unit\Fixtures\Entity';
                }
            );

        $this->doctrineHelper = new DoctrineHelper($this->doctrine);
    }
}

redpajama_set_name: RedPajamaGithub


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

using System;
using System.Drawing.Imaging;
using System.IO;
using Bytescout.BarCodeReader;

namespace InspectDecodedBarcodes
{
    class Program
    {
        static int i = 0;
        const string ImageFile = "Code_39.png";

        static void Main()
        {
            Console.WriteLine("Reading barcode(s) from image {0}", Path.GetFullPath(ImageFile));

            Reader reader = new Reader();
            reader.RegistrationName = "demo";
			reader.RegistrationKey = "demo";

            // Set barcode type to find
            reader.BarcodeTypesToFind.Code39 = true;

            reader.InspectDecodedBarcodes += Reader_InspectDecodedBarcodes;

            // Read barcodes
            FoundBarcode[] barcodes = reader.ReadFrom(ImageFile);

            foreach (FoundBarcode barcode in barcodes)
            {
                Console.WriteLine("Found barcode with type '{0}' and value '{1}'", barcode.Type, barcode.Value);
            }

			// Cleanup
			reader.Dispose();

            Console.WriteLine("Press any key to exit..");
            Console.ReadKey();
        }

        /// <summary>
        /// Inspect decoded barcode event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="image"></param>
        private static void Reader_InspectDecodedBarcodes(object sender, System.Drawing.Image image)
        {
            var imageFile = $"page{++i}.png";
            image.Save(imageFile, ImageFormat.Png);

            Console.WriteLine($"Inspected image file saved as ${imageFile}");

            // You should explicitly dispose the image object to avoid resource leaks.
            image.Dispose();

        }
    }
}


text:
import { reverse } from './reverse';

describe('reverse function', () => {
  const inputArray = [1, 2, 3, 4, 5];
  const inputString = 'azertyuiop';

  test('is a pure function with array', () => {
    reverse()(inputArray);
    expect(inputArray).toMatchSnapshot();
  });

  test('is a pure function with string', () => {
    reverse()(inputString);
    expect(inputString).toMatchSnapshot();
  });

  test('[1, 2, 3, 4, 5] |> reverse === [5, 4, 3, 2, 1]', () => {
    expect(reverse()(inputArray)).toMatchSnapshot();
  });

  test('"azertyuiop" |> reverse === "poiuytreza"', () => {
    expect(reverse()(inputString)).toMatchSnapshot();
  });

  test('[] |> reverse === []', () => {
    expect(reverse()([])).toMatchSnapshot();
  });

  test('"" |> reverse === ""', () => {
    expect(reverse()('')).toMatchSnapshot();
  });
});


text:
@implementation MPNativeAdData

@end


text:
require 'chef/knife/ucs_base'

class Chef
  class Knife
    class UcsVsansList < Knife

      include Knife::UCSBase

      banner "knife ucs vsans list"

      def run
        $stdout.sync = true

        #Using Chef's UI (much better looking:)) instead of list methods provided by ucslib.

        vsans_list = [
          ui.color('ID',    :bold),
          ui.color('Name',  :bold)
        ]

        inventory.xpath("configResolveClasses/outConfigs/fabricVsan").each do |fabricvsan|
          vsans_list << "#{fabricvsan.attributes["id"]}"
          vsans_list << "#{fabricvsan.attributes["name"]}"
        end
        puts ui.list(vsans_list, :columns_across, 2)

      end
    end
  end
end


text:
import { CenterModule } from './center/center.module';
import { PublishedModule } from './published/published.module';
import { RegisterService } from './shared/services/register.service';
import { UserModule } from './user/user.module';
import { LoginService } from './shared/services/login.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { HttpModule } from '@angular/http';

// my modules
import { HomeModule } from './home/home.module';
import { AboutModule } from  './about/about.module';
import { EditModule } from './edit/edit.module';

import { AppComponent } from './app.component';

// routes config
import { routesConfig } from './routesConfig';
import { GLOBAL_CONSTANTS as G_C } from './shared/config/constants';

// service
import { QuestionnaireService } from './shared/services/questionnaire.service';
import { AuthGuardService } from './shared/services/auth-guard.service';
import { UserService } from './shared/services/user.service';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    HttpModule,
    RouterModule.forRoot(routesConfig, {useHash: true}),

    HomeModule,
    AboutModule,
    EditModule,
    UserModule,
    PublishedModule,
    CenterModule
  ],
  // gl -> gerrylon, 全局prefix
  // 注入全局常量, 方便修改配置
  providers: [
    { provide: 'glQuestionnaireState', useValue: G_C.QUESTIONNAIRE_STATE },
    { provide: 'glQuestionType', useValue: G_C.QUESTION_TYPE },
    QuestionnaireService,
    AuthGuardService,
    UserService,
    LoginService,
    RegisterService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
namespace pp {

namespace {

template <> const char* interface_name<PPB_VarArray_1_0>() {
  return PPB_VAR_ARRAY_INTERFACE_1_0;
}

}  // namespace

VarArray::VarArray() : Var(Null()) {
  if (has_interface<PPB_VarArray_1_0>())
    var_ = get_interface<PPB_VarArray_1_0>()->Create();
  else
    PP_NOTREACHED();
}

VarArray::VarArray(const Var& var) : Var(var) {
  if (!var.is_array()) {
    PP_NOTREACHED();

    // This takes care of releasing the reference that this object holds.
    Var::operator=(Var(Null()));
  }
}

VarArray::VarArray(const PP_Var& var) : Var(var) {
  if (var.type != PP_VARTYPE_ARRAY) {
    PP_NOTREACHED();

    // This takes care of releasing the reference that this object holds.
    Var::operator=(Var(Null()));
  }
}

VarArray::VarArray(const VarArray& other) : Var(other) {
}

VarArray::~VarArray() {
}

VarArray& VarArray::operator=(const VarArray& other) {
  Var::operator=(other);
  return *this;
}

Var& VarArray::operator=(const Var& other) {
  if (other.is_array()) {
    Var::operator=(other);
  } else {
    PP_NOTREACHED();
    Var::operator=(Var(Null()));
  }
  return *this;
}

Var VarArray::Get(uint32_t index) const {
  if (!has_interface<PPB_VarArray_1_0>())
    return Var();

  return Var(PASS_REF, get_interface<PPB_VarArray_1_0>()->Get(var_, index));
}

bool VarArray::Set(uint32_t index, const Var& value) {
  if (!has_interface<PPB_VarArray_1_0>())
    return false;

  return PP_ToBool(get_interface<PPB_VarArray_1_0>()->Set(var_, index,
                                                          value.pp_var()));
}

uint32_t VarArray::GetLength() const {
  if (!has_interface<PPB_VarArray_1_0>())
    return 0;

  return get_interface<PPB_VarArray_1_0>()->GetLength(var_);
}

bool VarArray::SetLength(uint32_t length) {
  if (!has_interface<PPB_VarArray_1_0>())
    return false;

  return PP_ToBool(get_interface<PPB_VarArray_1_0>()->SetLength(var_, length));
}

}  // namespace pp


text:
.edit-contentblock .hd {
	border: 2px solid #D6E0FF;
	border-top: none;
}
.edit-contentblock .actions {
	background: #D6E0FF;
}

/* boxes
----------------------------------------------- */
.djpcms-html-box {
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
}
.djpcms-html-box .bd {
	-moz-border-radius-bottomleft: 2px;
    -moz-border-radius-bottomright: 2px;
    -webkit-border-bottom-left-radius: 2px;
    -webkit-border-bottom-right-radius: 2px;
}
.djpcms-html-box {
    background:#148EA4;
}
.djpcms-html-box .hd h2 {
    color: #fff;
}
.djpcms-html-box .bd {
	background: #fff;
}

/* uniForm Inputs
----------------------------------------------*/
.uniForm .textInput, .uniForm select, .uniForm textarea {
	background:#FFFFFF none repeat scroll 0 0;
	border:2px solid #D6E0FF;
}


text:
import update from 'react/lib/update';
import notify from '~/helpers/notify';
import searchSites from '~/helpers/searchSites';

function Filtering(state, action) {
  switch (action.type) {
    case 'SITE_SEARCH': {
      if (action.filter === '') {
        return update(state, {
          Filtering: { searchedSites: { $set: state.sites } }
        });
      }
      const results = searchSites(state.sites, action.filter);
      return update(state, {
        Filtering: { searchedSites: { $set: results } }
      });
    }
    case 'SITE_SORT': {
      if (action.sortBy === state.Filtering.sortBy) {
        const order = (state.Filtering.order === 'DESCENDING') ? 'ASCENDING' : 'DESCENDING';
        return update(state, {
          Filtering: { order: { $set: order } }
        });
      }
      return update(state, {
        Filtering: { sortBy: { $set: action.sortBy } }
      });
    }
    case 'OPEN_MODAL': {
      $('#myModal').modal('show');
      return update(state, {
        Filtering: { modalObj: { $set: action.modalObj } }
      });
    }
    case 'SITE_DELETE_SUCCESSFUL': {
      notify('Record deletion successful');
      const sitesIndex = state.sites.findIndex(site => site.site === action.site);
      const searchedIndex = state.Filtering.searchedSites.findIndex(site =>
        site.site === action.site);
      return update(state, {
        sites: { $splice: [[sitesIndex, 1]] },
        Filtering: { searchedSites: { $splice: [[searchedIndex, 1]] } }
      });
    }
    case 'SAVE_CHANGES_MODAL_SUCCESSFUL': {
      notify('Record changes saved');
      const sitesIndex = state.sites.findIndex(site => site.site === action.site.site);
      const searchedIndex = state.Filtering.searchedSites.findIndex(site =>
        site.site === action.site.site);
      const newSites = update(state.sites, { [sitesIndex]: { $set: action.site } });
      const newSearchedSites = update(state.Filtering.searchedSites, {
        [searchedIndex]: { $set: action.site }
      });
      return {
        ...state,
        Filtering: {
          ...state.Filtering,
          sites: newSites,
          searchedSites: newSearchedSites
        }
      };
    }
    case 'SAVE_CHANGES_REGEX_SUCCESSFUL': {
      notify('Pattern changes saved');
      return update(state, {
        patterns: { $set: action.items }
      });
    }
    default:
      return state;
  }
}

export default Filtering;


text:
![](_readme/readme_convoy_000.png)
# CONVOY

This repository contains all things needed to build browser based binary websocket projects. It allows you to setup and configure (self) hosted platforms that might actually have a use in production environments. A custom 'framework' is part of the package, including a fairly optimized builder. Important to note that it currently requires the bundled Node.js server (which is written from scratch to have as few dependencies as possible). Feel free to rip out the parts that are of interest and apply to them to your own projects.

In short, websites (real ones) delivered over binary websockets.

( *as mentioned this is work in progress. expect updates* )

## what it does

The idea is to optimize the way we deliver websites and web content to the browser. Part of this is the traditional steps of inlining all the non-binary content into as few requests as possible. (by default the builder merges everything into a single request). In addition the idea is to use binary websockets to deliver any type of data we load at runtime. A, fairly hacky, protocol is included to parse and render a few different datatypes. (.js, .css and .jpg are currently supported).

The included JS framework is optinal. Feel free to rip it out and rewrite things into a traditional AMD structure or whatever you like. What this experiment does come with is a simple framework to write single-page apps in pthat requires zero building / monitoring steps during development, easy class-like imports and extensions, plus a custom builder that provides highly optimized deployable code and assets.

![](_readme/readme_convoy_001.png)
An example of the bundled site being loaded by the browser. The inital (pre-gzipped) request contains all html and js required to kick things off. Directly after a websocket connection is opened and data is streamed through. The browser interprets this as 'cached'. Which is obv. not the case, but it allows you to see (most of) the incoming data. Also note the '0kb' file sizes the inspector is reporting. Wrong again, but it does looks somewhat magical.

![](_readme/readme_convoy_002.png)
An example of a .jpg delivered as binary buffer packages and composed into a blob of data.

![](_readme/readme_convoy_003.png)
And a glance at the non-binary content that's been inlined during the build process.

## getting started

Getting up and running should be fairly straghtforward. Included are some screenshots detailing the process. More in depth instructions will follow in later updates to this repo.

![](_readme/readme_convoy_004.png)
Here we start the bundled node.js server (after logging into the Vagrant shell).

![](_readme/readme_convoy_005.png)
The bundled example site delivered in 'debug' mode. (non-minified).

![](_readme/readme_convoy_006.png)
The builder in action. See backend/server/configurations to adjusts paths etc.

![](_readme/readme_convoy_007.png)
And finally the bundled example site delivered in 'deploy' mode. (minified). After building simply restart the server with a 'deploy' flag to start serving this version instead of the 'debug' one.

## Requirements

- [Vagrant 1.7+](https://www.vagrantup.com/downloads.html)
- [VMware Fusion / Workstation 7+](http://www.vmware.com/products/fusion) (VirtualBox most likely works, but you'll have to update the Vagrantfile)

## Comments / feedback / support

If something isn't working or you're just plain confused, feel free to contact me.

**twitter:** [theundebruijn](https://twitter.com/theundebruijn)
**email:** theun.de.bruijn@b-reel.com


text:
// <copyright file="Tool.cs" company="Shkyrockett" >
//     Copyright © 2005 - 2020 Shkyrockett. All rights reserved.
// </copyright>
// <author id="shkyrockett">Shkyrockett</author>
// <license>
//     Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </license>
// <summary></summary>
// <remarks></remarks>

namespace Engine.Tools
{
    /// <summary>
    /// Base Tool class.
    /// </summary>
    public abstract class Tool
        : ITool
    {
        #region Callbacks
        /// <summary>
        /// Signal the canvas to provide feedback to finish the command.
        /// </summary>
        public event ToolFinishEvent Finish;

        /// <summary>
        /// The <see cref="ToolFinishEvent"/> type delegate.
        /// </summary>
        public delegate void ToolFinishEvent(object Sender, ToolStack e);
        #endregion Callbacks

        #region Fields
        /// <summary>
        /// Check to determine if the tool is in use.
        /// </summary>
        protected bool inUse;

        /// <summary>
        /// Check if first action of tool has taken place.
        /// </summary>
        protected bool started;
        #endregion Fields

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="Tool"/> class.
        /// </summary>
        public Tool()
        {
            inUse = false;
            started = false;
        }
        #endregion Constructors

        #region Properties
        /// <summary>
        /// Check if the tool is in use.
        /// </summary>
        public bool InUse
        {
            get { return inUse; }
            set { inUse = value; }
        }

        /// <summary>
        /// Check whether the first action of tool has taken place.
        /// </summary>
        public bool Started
        {
            get { return started; }
            set { started = value; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether
        /// </summary>
        public bool MouseUp { get; set; }
        #endregion Properties

        /// <summary>
        /// Signal the parent to provide feedback to finish the command.
        /// </summary>
        protected virtual void RaiseFinishEvent(ToolStack tools)
            => Finish?.Invoke(this, tools);

        /// <summary>
        /// Reset.
        /// </summary>
        public virtual void Reset()
        { }

        /// <summary>
        /// Update the tool with the keys that have been pressed.
        /// </summary>
        /// <param name="obj"></param>
        public virtual void KeyboardKeyDown(ToolStack obj)
        { }

        /// <summary>
        /// Update the tool with the keys that have been released.
        /// </summary>
        /// <param name="obj"></param>
        public virtual void KeyboardKeyUp(ToolStack obj)
        { }

        /// <summary>
        /// Update tool on mouse down.
        /// </summary>
        /// <param name="tools"></param>
        public virtual void MouseDownUpdate(ToolStack tools)
        { }

        /// <summary>
        /// Update Tool on Mouse Move.
        /// </summary>
        /// <param name="tools">The Mouse Move event arguments.</param>
        public virtual void MouseMoveUpdate(ToolStack tools)
        { }

        /// <summary>
        /// Update Tool on Mouse UP signal.
        /// </summary>
        /// <param name="tools"></param>
        public virtual void MouseUpUpdate(ToolStack tools)
        { }

        /// <summary>
        /// Update Tool on Mouse scroll signal.
        /// </summary>
        /// <param name="tools"></param>
        public virtual void MouseScrollUpdate(ToolStack tools)
        { }

        /// <summary>
        /// A string representing a string output of the tool.
        /// </summary>
        /// <returns>Returns a <see cref="string"/> representing the type of the tool.</returns>
        public override string ToString()
            => GetType().ToString();
    }
}


text:
'''URLconf for pubman

These are:
    /    Index of articles page. Good for a homepage.
    /mediaobject/*
    /article/*
    /story/*
    /copyright/*
    /feed/rss/
    /feed/atom/
    /i18n/*
    /accounts/*
    /comments/*
    /contact/
    /profiles/*
    /sitemap.xml
'''

from django.conf.urls.defaults import *
from pubman import settings

from django.views.generic import list_detail
from django.views.generic.simple import direct_to_template

from pubman.views import media_object_detail, search
from pubman.models import Story, Copyright
from pubman.feeds import LatestArticlesRSSFeed, LatestArticlesAtomFeed

from django.contrib.sitemaps import FlatPageSitemap
from contact_form.views import contact_form

from pubman.sitemap import ArticleSitemap, StorySitemap, TranslationSitemap
from pubman.forms import PubmanContactForm

import datetime

story_info = {
    "queryset" : Story.objects.filter(publication_stage='P').\
        filter(date_published__lte = datetime.datetime.now()).\
        order_by('-date_published'),
    "paginate_by" : settings.STORIES_PER_PAGE,
}

copyright_info = {
    "queryset" : Copyright.objects.all(),
}

sitemaps = {
    'flatpages': FlatPageSitemap,
    'article': ArticleSitemap,
    'story': StorySitemap,
    'translation': TranslationSitemap,
}

urlpatterns = patterns('pubman.views',
    (r'^$', 'index'),
    url(r'^mediaobject/(?P<slug>[a-zA-Z0-9-\s_]+)/$',
     media_object_detail,
     name='media_object_detail_view'),

    (r'^article/(?P<article_id>\d+)/$', 'article_detail_by_id'),
    url(r'^article/(?P<article_slug>[a-zA-Z0-9-_]+)/$',
        'article_detail', name='article_detail_view'),

    url(r'^article/translation/(?P<article_slug>[a-zA-Z0-9-_]+)/(?P<article_lang>[a-zA-Z0-9-_]+)/$',
        'article_detail', name='translated_article'),

    (r'^article/tag/(?P<tag_expression>[\"\^\'\~\&\|\(\)a-zA-Z0-9-\s_]+)/$', 'tag_view',
     {'model_name': 'article', },
    'article_tag'),

    (r'^story/$', list_detail.object_list, story_info),
    (r'^story/(?P<story_id>\d+)/$', 'story_detail_by_id'),
    (r'^story/(?P<story_slug>[a-zA-Z0-9-_]+)/$', 'story_detail'),
    url(r'^copyright/(?P<object_id>\d+)/$',
        list_detail.object_detail,
        copyright_info,
        name='copyright_view'),

    (r'^markdownpreview/$', 'markdownpreview'),
    (r'^clearcache/$', 'clear_cache')
)

if 'search' in settings.URLCONF_VIEWS:
    urlpatterns += patterns(settings.URLCONF_ROOT,
                        (r'^search/$', search),)

if 'rss' in settings.URLCONF_VIEWS:
    urlpatterns += patterns(settings.URLCONF_ROOT,
            url(r'^feed/rss/articles/$', LatestArticlesRSSFeed(), name='rss-feed-articles'),)

if 'atom' in settings.URLCONF_VIEWS:
    urlpatterns += patterns(settings.URLCONF_ROOT,
            url(r'^feed/atom/articles/$', LatestArticlesAtomFeed(), name='atom-feed-articles'),)

if 'i18n' in settings.URLCONF_VIEWS:
    urlpatterns += patterns(settings.URLCONF_ROOT,
            url(r'^i18n/setlangform/', direct_to_template,
            {'template': 'pubman/set_language.html'}, name='setlangform' ),
            (r'^i18n/', include('django.conf.urls.i18n')),)

if 'accounts' in settings.URLCONF_VIEWS:
    urlpatterns += patterns(settings.URLCONF_ROOT,
            (r'^accounts/', include('registration.urls')),)

if 'comments' in settings.URLCONF_VIEWS:
    urlpatterns += patterns(settings.URLCONF_ROOT,
            (r'^comments/', include('django.contrib.comments.urls')),)

if 'contact' in settings.URLCONF_VIEWS:
    urlpatterns += patterns(settings.URLCONF_ROOT,

    (r'^contact/$', contact_form, {'form_class': PubmanContactForm}),
    (r'^contact/', include('contact_form.urls')),)

if 'profiles' in  settings.URLCONF_VIEWS:
    urlpatterns += patterns(settings.URLCONF_ROOT,
            (r'^profiles/create/$', 'pubman.views.edit_profile'),
            (r'^profiles/edit/$', 'pubman.views.edit_profile'),
            (r'^profiles/', include('profiles.urls')),)

if 'sitemap' in settings.URLCONF_VIEWS:
    urlpatterns += patterns(settings.URLCONF_ROOT,
    (r'^sitemap\.xml', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),)

if 'filebrowser' in settings.URLCONF_VIEWS:
    urlpatterns += patterns(settings.URLCONF_ROOT,
    (r'^admin/filebrowser/', include('filebrowser.urls')),)


text:
class Application {
  public:
    Application();
    void start();

  private:
    sf::RenderWindow window_;
    sf::Font font_;
    sf::Clock clock_;
    long long spent_;
    short char_size_;
    sf::Text detail_;
    bool exit_,
         new_content_,
         passed_;
    BigInteger number_;

    void initialize();
    void initText(sf::Text &text);
    void loop();
    void handleEvents();
    void fulfillLogic();
    void renderContent();

    void onResize();
    void onClose();

    void toBase(char base);
    std::string toBaseString(char base);
    void result();
};

#endif // APPLICATION_HPP_INCLUDED


text:
layout: post
unique_id: pancakes_fixed
title: Pancakes Fixed
categories: []
locations:
---

YESTERDAY:
* Jackie made pancakes properly
* spent 6 hours in meetings q.q
* forgot what we did for dinner
* finished ice cream
* practiced guitar 3 times today

TODAY:
* made a sausage stew
* Jackie made a tasty chicken rice bake
* extracted my last roll of paper towels from the closet
* played a bit of Alienation

LEARNINGS:
* should have bought more ice cream q.q


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace RSMacroProgram
{
    class TextBoxWriter : TextWriter
    {
        TextBox _output = null;

        public TextBoxWriter(TextBox output)
        {
            _output = output;
        }

        public override void Write(char value)
        {
            base.Write(value);
            _output.AppendText(value.ToString());
        }

        public override Encoding Encoding
        {
            get { return System.Text.Encoding.UTF8; }
        }
    }

    class MultiTextWriter : TextWriter
    {
        private List<TextWriter> writers = new List<TextWriter>();

        public MultiTextWriter(params TextWriter[] writer)
        {
            foreach(TextWriter w in writers) writers.Add(w);
        }

        public override void Write(char value)
        {
            base.Write(value);
            foreach (TextWriter w in writers) w.Write(value);
        }

        public override Encoding Encoding
        {
            get { return System.Text.Encoding.UTF8; }
        }
    }
}


text:
require 'fileutils'                                 # Used to process filenames
require 'common/format'

require_relative '../dao/header_fields_dao'
require_relative '../services/team_name_analyzer'
require_relative '../services/swimmer_name_analyzer'

require_relative './filename_parser'
require_relative './meeting_date_parser'
require_relative './fin_result_parser'
require_relative './fin_result_phase2'
require_relative './fin_result_phase3'
require_relative './parse_result_converter'
require_relative './season_detect_utils'

require_relative '../services/meeting_header_year_checker'
require_relative '../services/meeting_notes_organization_checker'
require_relative '../services/data_import_entity_builder'
require_relative '../services/data_import_meeting_builder'
require_relative '../services/data_import_meeting_session_builder'

=begin

= DataImporter

  - Goggles framework vers.:  6.087
  - author: Steve A.

  Data-Import strategy class.
  Refactored from the old DataImportController implementation.

=end
class DataImporter < BaseTwiceLoggable

  include SeasonDetectUtils
  include FinResultPhase2
  include FinResultPhase3

  attr_reader   :flash, :data_import_session,
                :header_fields_dao,
                :meeting,                           # serialized meeting
                :result_hash

  attr_accessor :full_pathname,
                :season,
                :force_missing_meeting_creation,
                :force_team_or_swimmer_creation,
                :do_not_consume_file
  #-- -------------------------------------------------------------------------
  #++

  # Creates a new instance.
  # If the data_import_session is not given a new one will be created.
  #
  def initialize( current_admin_id, data_import_session = nil, flash = nil )
    super( 'data-importer' )
    @flash  = flash  || {}
    @current_admin_id    = current_admin_id
    @data_import_session = data_import_session || create_new_data_import_session()
                                                    # Batch parameters' default
    @season        = @data_import_session.season
    @full_pathname = @data_import_session.file_name
    header_fields_dao_init_from_filename if @full_pathname
    @force_missing_meeting_creation = false
    @force_team_or_swimmer_creation = false
    @do_not_consume_file            = false
  end

  # Sets the internal parameter/members using a block before execution.
  #
  # == Existing definable members/parameters:
  #
  #  - :full_pathname
  #  - :season
  #  - :force_missing_meeting_creation
  #  - :force_team_or_swimmer_creation
  #  - :do_not_consume_file
  #
  def set_up( options = {} )
    options.each do |key, value|
      send("#{key}=", value)
      # Force header_fields_dao init on filename change:
      header_fields_dao_init_from_filename if key == :full_pathname
    end
    # Synchronize any important member changes with the stored session:
    if options[:full_pathname] || options[:season]
      @data_import_session.file_name = @full_pathname
      @data_import_session.data_import_season_id = @season.id if @season.instance_of?( DataImportSeason )
      @data_import_session.season_id = @season.id if @season.instance_of?( Season )
      @data_import_session.save!
    end
  end
  #-- -------------------------------------------------------------------------
  #++

  # Destroys the current Data-import session, including its linked secondary entities.
  # After a successful execution the internal member linking to the session becomes
  # invalid (+nil+) and the current instance should be considered trashable.
  # (We do not force that because the log members could still prove useful.)
  #
  def destroy_data_import_session()
    if ( @data_import_session )                     # For a safety clean-up, check also if the file wasn't consumed properly after phase-1:
      unless @data_import_session.file_name.nil?
        fullpathname = File.join( Dir.pwd, @data_import_session.file_name )
        if ( FileTest.exists?(fullpathname) && !@do_not_consume_file )
          append_to_log_file( @data_import_session, "-- destroy_data_import_session(#{ @data_import_session.id }): the import file wasn't consumed properly after phase-1. Erasing it..." )
          FileUtils.rm( fullpathname )
        end
      end
                                                    # For all data_import_... tables, delete rows for the corresponding data_import_session.id
      DataImportMeetingIndividualResult.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportMeetingEntry.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportMeetingProgram.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportMeetingRelayResult.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportMeetingSession.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportMeetingTeamScore.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportMeeting.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportSeason.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportSwimmer.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportTeam.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportBadge.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportCity.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportTeamAnalysisResult.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportSwimmerAnalysisResult.where( data_import_session_id: @data_import_session.id ).delete_all
      DataImportSession.delete( @data_import_session.id )
      append_to_log_file(
        @data_import_session,
        "-- destroy_data_import_session(#{ @data_import_session.id }): data-import session clean-up done.\r\n"
      )
      @data_import_session = nil
    else
      append_to_log_file(
        @data_import_session,
        "-- destroy_data_import_session(#{ @data_import_session.id }): warning: unable to find the specified data-import session master record.\r\n"
      )
    end
  end
  #-- -------------------------------------------------------------------------
  #++

  # Data-import Phase #1: text parsing.
  #
  # Reads and parses the whole TXT file into a complex Hash result, stored in memory.
  # When all the data is transferred to the temporary tables, the file is consumed (killed)
  # from the upload directory.
  #
  # The #data_import_session member is required to be not +nil+ before invoking this
  # method.
  #
  # === Returns:
  # The currently used #data_import_session instance if successful; +nil+ otherwise.
  #
  def phase_1_parse()
    raise ArgumentError.new("The #full_pathname member must be set before invoking this method!") unless @full_pathname.instance_of?(String)
    return nil unless @data_import_session.instance_of?( DataImportSession )

    append_to_log_file( @data_import_session, "--------------------[Phase #1.0 - PARSE]--------------------" )
    append_to_log_file( @data_import_session, "Parsing file: #{@full_pathname}, force_missing_meeting_creation=#{@force_missing_meeting_creation}, force_team_or_swimmer_creation=#{@force_team_or_swimmer_creation}, do_not_consume_file=#{@do_not_consume_file}.\r\n" )
    header_fields_dao_init_from_filename()          # Make sure #header_fields_dao is defined
                                                    # Check if it's a "continuation session":
    if @data_import_session.phase > 0
      append_to_log_file( @data_import_session, "\r\n*** CONTINUING SESSION (after team name Analysis, stored in separate log file) ***" )
    end
                                                    # FILE TYPE DETECT => '<ris><date_header><code>.txt' for FIN results type
    unless @data_import_session.file_format
      case @header_fields_dao.prefix
      when 'ris'
        @data_import_session.file_format = 'fin-results'
      when /sta|stl/
        @data_import_session.file_format = 'fin-startlist'
      else
        @data_import_session.file_format = 'results?'
      end
      @data_import_session.save!
    end

    if @season.nil?                                 # SEASON DETECT
      try_detect_season_from_file_path
      try_detect_season_from_header_fields
      unless @season                                # (@season must be defined after this point)
        @flash[:error] = "#{ I18n.t('admin_import.season_not_found') })}\r\n#{ @header_fields_dao }"
        append_to_log_file( @data_import_session, "               *** Latest flash[:error]: ***\r\n#{@flash[:error] }\r\n-----------------------------------------------------------\r\n" )
        return nil
      end
    else
      append_to_log_file( @data_import_session, "Specified season ID=#{@season.id}. Parsing file..." )
    end
                                                    # Get the remaining default values from the season instance:
    @header_fields_dao.header_year     = @season.header_year
    @header_fields_dao.edition         = @season.edition
    @header_fields_dao.edition_type_id = @season.edition_type_id
    @header_fields_dao.timing_type_id  = @season.timing_type_id
    append_to_log_file( @data_import_session, "\r\nParsed header fields: #{@header_fields_dao}" )

    # Parse the file and store the results in memory, inside the @result_hash member.
    #
    # NOTE: @result_hash has the following structure:
    #     {
    #       parse_result: {
    #         :category_header => [
    #           { id: <category_header_id>, fields: <hash_of_category_header_fields_dao_with_values>,
    #             import_text: last_line_of_text_used_to_extract_all_fields }
    #           ... (one Hash for each <category_header_id>)
    #         ],
    #         :result_row      => [
    #           { id: <category_header_id>, fields: <hash_of_result_row_fields_with_values>,
    #             import_text: last_line_of_text_used_to_extract_all_fields }
    #           ... (one or more Hash for each <category_header_id>, which acts as a "context page index")
    #         ],
    #         ...
    #       },
    #       line_count: tot_file_lines_read,
    #       total_data_rows: sum_of_data_pages_sizes,
    #       full_text_file_contents: full_text_file_contents
    #     }
    #
    # > FinResultParser.field_list_for( context_sym )
    # returns the possible fields for either :category_header || :result_row
    #
    @result_hash = FinResultParser.parse_txt_file( @full_pathname ) # (=> show_progress = false)
                                                    # Make sure the :parse_result member is in 'standard' form:
    append_to_log_file( @data_import_session, "\r\nFile format detectd: #{@result_hash[:parsing_defs].describe}" )
    @result_hash[:parse_result] = ParseResultConverter.new.to_parse_result(
      @result_hash[:parse_result],
      @result_hash[:parsing_defs],
      @season
    )
    @stored_data_rows = 0
                                                    # Store the raw text file into the data-import session:
    @data_import_session.source_data            = @result_hash[:full_text_file_contents]
    @data_import_session.total_data_rows        = @result_hash[:total_data_rows]
    @data_import_session.data_import_season_id  = @season.instance_of?( DataImportSeason ) ? @season.id : nil
    @data_import_session.season_id              = @season.instance_of?( Season ) ? @season.id : nil
    @data_import_session.phase                  = 10 if @data_import_session.phase < 10
    @data_import_session.phase_3_log            = 'PHASE 1.0 PARSE'
    result = @data_import_session.save ? @data_import_session : nil
    append_to_log_file(
       @data_import_session,
      "\r\nPHASE #1.0 END, returning #{ result ? 'current session' : 'NIL'}."
    )
    result
  end
  #-- -------------------------------------------------------------------------
  #++

  # Data-import Phase #1.2: parsing result serialization phase.
  #
  # This should be called only after a successful Phase 1.0.
  # (It checks for the last completed phase indicator in session and it returns +nil+
  # unless everything is ok.)
  #
  # The current implementation is able to rebuild/import the results of only *one*
  # MeetingSession at a time.
  #
  # Returns +nil+ only on error; otherwise it returns the current #data_import_session
  # instance.
  #
  # After a successful execution, remember to check the actual completion by peeking
  # at the #data_import_session.phase and whether...
  #   @data_import_session.data_import_team_analysis_results.any?
  #   @data_import_session.data_import_swimmer_analysis_results.any?
  # ... Are both +true+.
  #
  # The "Phase #2" of the "data-import wizard" allows the user to manually review
  # the digested/serialized data from the support tables, so that any mistakes or
  # conflicts may be edited (and solved) before the final commit phase (which is phase #3).
  #
  def phase_1_2_serialize()
    return nil unless @data_import_session.instance_of?( DataImportSession ) &&
                      @result_hash.instance_of?(Hash) &&
                      @data_import_session.phase >= 10 && @data_import_session.phase < 12
                                                    # Create just one header row for each one of Meeting/Meeting Session entities:
    season_starting_year = 0                        # This is needed by the individual results
    meeting_header_row = meeting_dates = scheduled_date = nil
    append_to_log_file( @data_import_session, "\r\n\r\n--------------------[Phase #1.2 - DIGEST/SERIALIZE]--------------------" )
    append_to_log_file( @data_import_session, "Parsing of '#{full_pathname}' done.\r\nDigesting data..." )
                                                    # -- MEETING HEADER digest --
    if @season
      meeting_headers = @result_hash[:parse_result][:meeting_header]
      meeting_header_row = meeting_headers.first if meeting_headers
      if meeting_header_row                         # If the meeting_dates are found inside the data file, use them:
        append_to_log_file( @data_import_session, "meeting_header_row = #{meeting_header_row.inspect}" )
        meeting_dates = meeting_header_row[:fields][:meeting_dates]
        # TODO [Steve, 20140923]
        #      The new MeetingDateParser now supports multiple date extraction: this should be used
        #      to extract all meeting_session dates, when possible.
        #      (Marked as FUTUREDEV, since we assume all meeting sessions will be existing
        #       before each data-import execution.)
        scheduled_dates = MeetingDateParser.new.parse( meeting_dates )
        scheduled_date  = scheduled_dates.first if scheduled_dates.instance_of?( Array )
        append_to_log_file( @data_import_session, "meeting_dates = '#{meeting_dates}' => #{scheduled_dates.inspect} (USING ONLY: #{scheduled_date})" )
      end
                                                      # ...Otherwise, parse them from the filename/header:
      if scheduled_date.nil? && @header_fields_dao.header_date
        scheduled_date = @header_fields_dao.header_date
        append_to_log_file( @data_import_session, "scheduled_date=#{scheduled_date} (set to file name date)" )
      end
                                                      # If we still haven't found the scheduled date, fall back to some defaults:
      if scheduled_date.nil?
        scheduled_date = @season.begin_date.nil? ? Date.today : @season.begin_date
      end
    end

    is_ok = true
    if @season                                        # -- PRE-SCAN TEAM & SWIMMER Names --
      season_starting_year = @season.begin_date.year
      append_to_log_file( @data_import_session, "Found season '#{@season.inspect}'; #{@season.season_type.inspect}, season_starting_year=#{season_starting_year}" )
      # [Steve, 20150112] The existance of Season is the minimum requirement before
      # starting the Team & Swimmer name analysis sub-phases.
                                                    # Any required prescan will abort the rest of the procedure:
      are_team_names_ok = prescan_parse_result_for_unknown_team_names(
        @data_import_session,
        @season,
        @result_hash[:parse_result],
        @force_team_or_swimmer_creation
      )
      append_to_log_file( @data_import_session, "PHASE #1.1: Team name Analysis phase needed!" ) unless are_team_names_ok

      are_swimmer_names_ok = prescan_parse_result_for_unknown_swimmer_names(
        @data_import_session,
        @season,
        @result_hash[:parse_result],
        @force_team_or_swimmer_creation
      )
      append_to_log_file( @data_import_session, "PHASE #1.1: Swimmer name Analysis phase needed!" ) unless are_swimmer_names_ok
                                                    # Update is_ok status flag:
      is_ok = are_team_names_ok && are_swimmer_names_ok
    end

    @meeting = nil
    if is_ok && @season                             # -- MEETING (digest/serialization) --
      meeting_builder = DataImportMeetingBuilder.build_from_parameters(
        @data_import_session,
        @season,
        @header_fields_dao,
        meeting_header_row,
        meeting_dates,
        false # [Steve, 20170306] THIS SHOULD BE ALWAYS DISABLED
      )
      @meeting = meeting_builder.result_row
    end
                                                    # --- TEAM RANKING/SCORES (digest/serialization) --
    if @meeting
      # Meeting is surely defined at this point (either as Meeting or as DataImportMeeting)
      # We store its ID in the session phase-2 log, for quick reference:
      @data_import_session.phase_2_log = "#{ @meeting.class.name }: #{ @meeting.id }"
      @data_import_session.save!

      # Try to fix any possible date validation failures:
      append_to_log_file( @data_import_session, "PHASE #1.2: checking possible Meeting validation failures..." )
      sql_diff_for_header = MeetingHeaderYearChecker.check_and_fix( @meeting )
      if sql_diff_for_header.size > 0
        append_to_log_file( @data_import_session, "PHASE #1.2: associated Meeting corrected." )
        sql_diff_text_log << "\r\n-- Fixing Meeting header:\r\n"
        sql_diff_text_log << sql_diff_for_header
      end

      if meeting_header_row.instance_of?( Hash ) && meeting_header_row.has_key?(:fields)
        append_to_log_file( @data_import_session, "PHASE #1.2: checking possible missing Meeting notes/organization..." )
        sql_diff_for_notes = MeetingNotesOrganizationChecker.check_and_fix(
          @meeting,
          meeting_dates,
          meeting_header_row[:fields][:organization]
        )
        if sql_diff_for_notes.size > 0
          append_to_log_file( @data_import_session, "PHASE #1.2: associated Meeting#notes updated with missing value." )
          sql_diff_text_log << "\r\n-- Fixing Meeting notes:\r\n"
          sql_diff_text_log << sql_diff_for_notes
        end
      end
                                                    # Retrieve default meeting session: (used only for new/missing meeting events or programs)
      append_to_log_file( @data_import_session, "PHASE #1.2: processing TEAM RANKING/SCORES..." )
      ranking_details = @result_hash[:parse_result][:ranking_row]
      is_ok = process_team_ranking(
          @full_pathname,
          @data_import_session,
          @season,
          @meeting,
          ranking_details,
          @force_team_or_swimmer_creation
      )
    end
                                                    # -- MEETING SESSION (digest/serialization) --
    meeting_session = nil
    if @meeting                                     # Retrieve default meeting session: (used only for new/missing meeting events or programs)
      meeting_session_builder = DataImportMeetingSessionBuilder.build_from_parameters(
        @data_import_session,
        @meeting,
        @header_fields_dao,
        meeting_dates, # meeting_dates_text
        scheduled_date,
        @force_missing_meeting_creation
      )
      meeting_session = meeting_session_builder.result_row
    end
                                                    # --- CATEGORY (digest/serialization) --
    if is_ok && meeting_session
# DEBUG
      puts "\r\n----- BEFORE 1.2: CATEGORY headers --------"
      append_to_log_file( @data_import_session, "PHASE #1.2: processing CATEGORY headers..." )
      is_ok = process_category_headers(
          @full_pathname,
          @data_import_session,
          @season,
          season_starting_year,
          @meeting,
          meeting_session,
          @result_hash[:parse_result],
          scheduled_date,
          @force_team_or_swimmer_creation
      )
    end
                                                    # --- RELAY (digest/serialization) --
    if is_ok && meeting_session
# DEBUG
      puts "\r\n----- BEFORE 1.2: RELAY headers --------"
      append_to_log_file( @data_import_session, "PHASE #1.2: processing RELAY headers..." )
      is_ok = process_relay_headers(
          @full_pathname,
          @data_import_session,
          @season,
          season_starting_year,
          @meeting,
          meeting_session,
          @result_hash[:parse_result],
          scheduled_date,
          @force_team_or_swimmer_creation
      )
    end
# DEBUG
      puts "\r\n----- END 1.2 --------"
                                                    # After having successfully stored the contents, remove the file
    if is_ok
      append_to_log_file( @data_import_session, "-- phase_1_parse(#{ @full_pathname }): file processed and 'digested'(serialized) on support tables." )
      unless @do_not_consume_file
        append_to_log_file( @data_import_session, "Consuming it..." )
        FileUtils.rm( @full_pathname )
      end
      @data_import_session.phase = 12               # Update "last completed phase" indicator (12 = '1.2')
      @data_import_session.save!
      append_to_log_file(
        @data_import_session,
        "\r\nFile '#{File.basename( @full_pathname )}', created session ID: #{ @data_import_session.id }\r\n" <<
        "Total file lines .....: #{ @result_hash[:line_count] }\r\n" <<
        "Total data headers ...: #{ @result_hash[:total_data_rows] }\r\n" <<
        "Actual stored rows ...: #{ @stored_data_rows }\r\n" <<
        "Meeting ID:...........: #{ @meeting ? @meeting.id : '(nil)' }\r\n" <<
        "Season ID:............: #{ @season ? @season.id : '(nil)' }\r\n" <<
        "File processed.\r\nData-import PHASE #1.2 DONE."
      )
    end
                                                    # Update the global log with the whole phase 1 log
    append_to_log_file( @data_import_session, "\r\nPHASE #1.2 END, returning #{ is_ok ? '(current session)' : 'NIL'}." )
    append_to_log_file( @data_import_session, "               *** Latest flash[:error]: ***\r\n#{@flash[:error] }\r\n-----------------------------------------------------------\r\n" ) if @flash[:error]
    # Dump the SQL diff file only if no Analysis phase (1.1) is required:
# DEBUG
    puts "\r\n----- BEFORE save_diff_file --------"
    save_diff_file( @data_import_session ) if is_ok
    # Return the created/updated data-import session, or nil in case of errors:
    puts "\r\n----- END save_diff_file --------"
    is_ok ? @data_import_session : nil
  end
  #-- -------------------------------------------------------------------------
  #++

  # Data Import Wizard: phase #3 (Phase #2 is manual review of the parsed data)
  # On (editable) data grid final commit, do the actual data import into destination table,
  # logging every error or mismatch and finally displaying it on the dedicated view.
  #
  # === Returns:
  # true on success; false on error.
  #
  def phase_3_commit()
    @flash[:info] = I18n.t('admin_import.missing_session_parameter') if @data_import_session.nil?
    return false unless @data_import_session.instance_of?( DataImportSession ) &&
                        ( @data_import_session.phase == 12 )
                                                    # Check season integrity
    @flash[:info] = I18n.t('admin_import.season_not_saved_in_session') and return false unless @season

    append_to_log_file( @data_import_session, "\r\n\r\n--------------------[Phase #3 - COMMIT]--------------------" )
    append_to_log_file( @data_import_session, "\r\n-- phase_3_commit: session ID:#{ @data_import_session.id }, season ID: #{ @season.id }..." )
    @committed_data_rows = 0
                                                    # Bail out as soon as something is wrong:
    is_ok = commit_data_import_meeting( @data_import_session )
    is_ok = commit_data_import_meeting_session( @data_import_session ) if is_ok
    is_ok = commit_data_import_meeting_program( @data_import_session ) if is_ok
    is_ok = commit_data_import_cities( @data_import_session ) if is_ok
    is_ok = commit_data_import_teams( @data_import_session, @season ) if is_ok
    is_ok = commit_data_import_swimmers( @data_import_session ) if is_ok
    is_ok = commit_data_import_badges( @data_import_session ) if is_ok
    is_ok = commit_data_import_meeting_entries( @data_import_session ) if is_ok
    is_ok = commit_data_import_meeting_individual_results( @data_import_session ) if is_ok
    is_ok = commit_data_import_meeting_relay_results( @data_import_session ) if is_ok
    is_ok = commit_data_import_meeting_team_score( @data_import_session ) if is_ok
    @data_import_session.phase = 30                 # (30 = '3.0', but without successful ending, since the session in not nil)
    @data_import_session.save!
                                                    # *** SET 'results aquired' flag. This will return the committed/updated meeting:
    @meeting = DataImporter.get_serialized_meeting_from_data_import_session( @data_import_session )
    update_meeting_flags( @meeting ) if is_ok && @meeting

                                  # *** FIX/Re-esteem committed meeting program's begin times:
    # Do not esteem possible starting times if we don't met the optimal conditions:
    # - we should have a meeting defined
    # - everything should be ok
    # - no separate-category starting lists for any events
    unless (
        !@meeting.instance_of?( Meeting ) ||
        !is_ok ||
        @meeting.meeting_events.any?{ |me| me.has_separate_category_start_list? }
    )
      is_begin_time_fixed = BeginTimeCalculator.compute_for_all( @meeting, sql_diff_text_log )
      append_to_log_file(
        @data_import_session,
        "\r\nBegin time re-computed for all meeting programs and updated directly on committed entities.\r\n"
      ) if is_begin_time_fixed
    end

    if is_ok
      append_to_log_file(
        @data_import_session,
        "data-import PHASES #2 & #3 DONE.\r\n\r\nTotal committed rows: #{ @committed_data_rows }\r\n" <<
        "Data-import session destroyed successfully.\r\n" <<
        "===========================================================\r\n"
      )
    else                                            # Store data_import_session.phase_2_log if something goes awry:
      if $!
        append_to_log_file(
          @data_import_session,
          "\r\n*** #{ data_import_session.phase_3_log }: exception caught during save!\r\n*** #{ $!.to_s }\r\n"
        )
      end
      @flash[:error] = "#{ I18n.t(:something_went_wrong) } [#{ data_import_session.phase_3_log }]" + ( $! ? ": '#{ $!.to_s }'" : '' )
    end
                                                    # Rewrite the logs & return the result:
    if @meeting && is_ok
      save_diff_file( @data_import_session )
      # Store the final Meeting ID updated by the data-import in a dedicated column:
      @data_import_session.sql_diff = @meeting.id.to_s
      @data_import_session.save!
    end
    is_ok
  end
  #-- -------------------------------------------------------------------------
  #++

  # Returns the currently serialized Meeting instance from the data-import
  # session specified, or +nil+ when not found.
  #
  # When calling this method, it's assumed that the Meeting ID should be serialized
  # either into the phase_2_log of the session (together with the serialization class
  # name) or just as its Meeting.id in sql_diff. (This actually happens only after
  # a successful data-import, with some data to be imported.)
  #
  def self.get_serialized_meeting_from_data_import_session( data_import_session )
    return nil unless data_import_session.instance_of?( DataImportSession )
    meeting = nil

    if data_import_session.sql_diff.to_i > 0
      meeting = Meeting.find_by_id( data_import_session.sql_diff.to_i )

    elsif data_import_session.phase_2_log.to_s.size > 0
      meeting_serialized = data_import_session.phase_2_log.split(': ')
      # Search only instances of Meeting (not DataImportMeeting):
      if meeting_serialized.first == 'Meeting'
        meeting = Meeting.find_by_id( meeting_serialized.last )
      end
    end

    meeting
  end
  #-- -------------------------------------------------------------------------
  #++

  private

  # Creates a new data-import session returning its instance.
  #
  def create_new_data_import_session( full_pathname = nil, full_text_file_contents = nil,
                                      total_data_rows = 0, file_format = nil,
                                      season_id = nil )
    DataImportSession.create(
      phase:            0,
      file_format:      file_format,
      file_name:        full_pathname,
      source_data:      full_text_file_contents,
      total_data_rows:  total_data_rows,
      season_id:        season_id,
      phase_1_log:      '', # List of DB-diffs produced
      phase_2_log:      '', # Current meeting instance processed (with class name)
      phase_3_log:      '', # Latest data-import status
      sql_diff:         '', # Actual resulting, final Meeting.id (just the ID), after phase-3
      user_id:          @current_admin_id
    )
  end
  #-- -------------------------------------------------------------------------
  #++

  # Filename header digest.
  # This will initialize the internal #header_fields_dao member based on the current
  # value of the #full_pathname of the parsed file. The #result_hash member will
  # be set to +nil+.
  #
  # This method does nothing if called when the header_fields_dao is
  # already defined (it's non-destructive).
  #
  def header_fields_dao_init_from_filename()
    # Bail out if #header_fields_dao is already defined:
    return if @header_fields_dao.instance_of?( HeaderFieldsDAO )
    @header_fields_dao = FilenameParser.new( @full_pathname ).parse
    @result_hash = nil
  end
  #-- -------------------------------------------------------------------------
  #++
end
#-- ---------------------------------------------------------------------------
#++


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/monitoring/v3/service.proto

namespace Google\Cloud\Monitoring\V3\WindowsBasedSli;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * A `PerformanceThreshold` is used when each window is good when that window
 * has a sufficiently high `performance`.
 *
 * Generated from protobuf message google.monitoring.v3.WindowsBasedSli.PerformanceThreshold
 */
class PerformanceThreshold extends \Google\Protobuf\Internal\Message
{
    /**
     * If window `performance >= threshold`, the window is counted as good.
     *
     * Generated from protobuf field double threshold = 2;
     */
    private $threshold = 0.0;
    protected $type;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type \Google\Cloud\Monitoring\V3\RequestBasedSli $performance
     *           `RequestBasedSli` to evaluate to judge window quality.
     *     @type \Google\Cloud\Monitoring\V3\BasicSli $basic_sli_performance
     *           `BasicSli` to evaluate to judge window quality.
     *     @type float $threshold
     *           If window `performance >= threshold`, the window is counted as good.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Monitoring\V3\Service::initOnce();
        parent::__construct($data);
    }

    /**
     * `RequestBasedSli` to evaluate to judge window quality.
     *
     * Generated from protobuf field .google.monitoring.v3.RequestBasedSli performance = 1;
     * @return \Google\Cloud\Monitoring\V3\RequestBasedSli
     */
    public function getPerformance()
    {
        return $this->readOneof(1);
    }

    /**
     * `RequestBasedSli` to evaluate to judge window quality.
     *
     * Generated from protobuf field .google.monitoring.v3.RequestBasedSli performance = 1;
     * @param \Google\Cloud\Monitoring\V3\RequestBasedSli $var
     * @return $this
     */
    public function setPerformance($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Monitoring\V3\RequestBasedSli::class);
        $this->writeOneof(1, $var);

        return $this;
    }

    /**
     * `BasicSli` to evaluate to judge window quality.
     *
     * Generated from protobuf field .google.monitoring.v3.BasicSli basic_sli_performance = 3;
     * @return \Google\Cloud\Monitoring\V3\BasicSli
     */
    public function getBasicSliPerformance()
    {
        return $this->readOneof(3);
    }

    /**
     * `BasicSli` to evaluate to judge window quality.
     *
     * Generated from protobuf field .google.monitoring.v3.BasicSli basic_sli_performance = 3;
     * @param \Google\Cloud\Monitoring\V3\BasicSli $var
     * @return $this
     */
    public function setBasicSliPerformance($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Monitoring\V3\BasicSli::class);
        $this->writeOneof(3, $var);

        return $this;
    }

    /**
     * If window `performance >= threshold`, the window is counted as good.
     *
     * Generated from protobuf field double threshold = 2;
     * @return float
     */
    public function getThreshold()
    {
        return $this->threshold;
    }

    /**
     * If window `performance >= threshold`, the window is counted as good.
     *
     * Generated from protobuf field double threshold = 2;
     * @param float $var
     * @return $this
     */
    public function setThreshold($var)
    {
        GPBUtil::checkDouble($var);
        $this->threshold = $var;

        return $this;
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->whichOneof("type");
    }

}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(PerformanceThreshold::class, \Google\Cloud\Monitoring\V3\WindowsBasedSli_PerformanceThreshold::class);


text:
package in.krshandro.todamo.taskitem;

import java.util.ArrayList;
import java.util.List;

import in.krshandro.todamo.base.OnCrudListener;

/**
 * Created by krish on 11/9/16.
 */
public final class TaskItemController {

	final List<TaskItem> mTaskItemList = new ArrayList<>();
	OnCrudListener mOnCrudListener;

	public void setOnItemCrudListener(OnCrudListener mOnCrudListener) {
		this.mOnCrudListener = mOnCrudListener;
	}

	public List<TaskItem> getItemList() {
		return mTaskItemList;
	}

	public TaskItem insertItem(final String title, final String description) {
		final TaskItem taskItem = new TaskItem(mTaskItemList.size() + 1);
		taskItem.setTitle(title);
		taskItem.setDescription(description);

		mTaskItemList.add(taskItem);

		return taskItem;
	}

}


text:
________________________________________________________________________

This file is part of Logtalk <https://logtalk.org/>
Copyright 1998-2022 Paulo Moura <pmoura@logtalk.org>
SPDX-License-Identifier: Apache-2.0

Licensed 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.
________________________________________________________________________

`assertions`
============

The `assertions.lgt` file contains definitions for two meta-predicates,
`assertion/1-2`, which allows using of assertions on your source code to
print warning and error messages (using the message printing mechanism).
The `assertions_messages.lgt` file defines the default message translations
generated on assertions succeed, fail, or throw an exception.

API documentation
-----------------

This tool API documentation is available at:

[../../docs/library_index.html#assertions](../../docs/library_index.html#assertions)

Loading
-------

This tool can be loaded using the query:

	| ?- logtalk_load(assertions(loader)).

Testing
-------

To test this tool, load the `tester.lgt` file:

	| ?- logtalk_load(assertions(tester)).

Adding assertions to your source code
-------------------------------------

The `assertion/1` predicate takes a goal as argument. For example:

	foo(L) :-
		assertions::assertion(non_empty_list(L)),
		...

The `assertion/2` predicate takes as arguments a term for passing
context information and a goal. Using again a unit test as an example:

	foo(L) :-
		assertions::assertion(foo_list_alerts, non_empty_list(L)),
		...

When using a large number of assertions, you can use a lighter syntax
by adding a `uses/2` directive. For example:

	:- uses(assertions, [assertion/1, assertion/2]).

Automatically adding file and line context information to assertions
--------------------------------------------------------------------

The `assertions/1` parametric object can be used as a hook object to
automatically add file and line context information, represented by the
term `file_lines(File, BeginLine-EndLine)`, to calls to the `assertion/1`
predicate by goal-expanding it to calls to the `assertion/2` predicate
(the expansion assumes that a `uses/2` directive is being used in the code
that will be expanded to direct `assertion/1` calls to the `assertions`
object). For example, assuming the file using assertions is named `source`,
it would be compiled and loaded using the call:

	logtalk_load(source, [hook(assertions(debug))])

Suppressing assertion calls from source code
--------------------------------------------

The `assertions/1` parametric object can be used as a hook object to
suppress calls to the `assertion/1-2` predicates using goal-expansion
(the expansion assumes `assertions::assertion/1-2` messages). For example,
assuming the file using assertions is named `source`, it would be compiled
and loaded using the call:

	logtalk_load(source, [hook(assertions(production))])

Redirecting assertion failure messages
--------------------------------------

By default, assertion failures and errors are printed to the standard
output stream. These messages, however, can be intercepted by defining
the `logtalk::message_hook/4` multifile predicate. For example:

	:- category(redirect_assertions_messages).

		:- multifile(logtalk::message_hook/4).
		:- dynamic(logtalk::message_hook/4).

		logtalk::message_hook(Message, error, assertions, _) :-
			writeq(my_log_file, Message), write(my_log_file, '.\n').

	:- end_category.

Converting assertion failures into errors
-----------------------------------------

If you want an assertion failure to result in a failure or a runtime error,
you can intercept the assertion failure messages, optionally still printing
them, and throw an error. For example:

	:- category(assertions_failures_to_errors).

		:- multifile(logtalk::message_hook/4).
		:- dynamic(logtalk::message_hook/4).

		logtalk::message_hook(Message, error, assertions, Tokens) :-
			% uncomment the next two lines to also print the default message
			% logtalk::message_prefix_stream(error, assertions, Prefix, Stream),
			% logtalk::print_message_tokens(Stream, Prefix, Tokens),
			throw(error(Message, _)).

	:- end_category.

In alternative, if you want assertions to always trigger an exception, use
instead the `lgtunit` tool `assertions/1-2` public predicates.


text:
{% extends "base.html" %}
{% block title %}Categories - {{ SITENAME }}{% endblock %}
{% block content_body %}

Categories

{% for category, articles in categories %}

{{ category }}

{% endfor %}

{% endblock %}


text:
#ifndef VERSION_H
#define VERSION_H

#define KERNEL_VERSION_MAJOR 0
#define KERNEL_VERSION_MINOR 0
#define KERNEL_VERSION_PATCH 1

#endif  /* VERSION_H */


text:
package ch.heigvd.amt.gamy.web.controllers;

import ch.heigvd.amt.gamy.model.APIKey;
import ch.heigvd.amt.gamy.services.dao.ApplicationDAOLocal;

import java.io.IOException;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.EJB;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * RegisterApplicationServlet is the controller to create a new application.
 * This controller should check the data from the create application from
 * before to create a new app in Gamy.
 *
 * doGet show the form to create a new app with some auto-generated data.
 * doPost create the application with the information gave by the user.
 *
 * This servlet answer to the doGet() and doPost().
 */
@WebServlet(name = "RegisterApplicationServlet", urlPatterns = {"/RegisterApplicationServlet"})
public class RegisterApplicationServlet extends HttpServlet {

   @EJB
   ApplicationDAOLocal applicationDAO;

   /**
    * Processes requests for both HTTP GET and POST
    * methods.
    *
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
   protected void processRequest(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
      response.setContentType("text/html;charset=UTF-8");

      // Read the information from the form.
      String name = request.getParameter("name");
      String description = request.getParameter("description");
      String apiKey = request.getParameter("apikey");
      String status = request.getParameter("status");
      boolean state = status.equalsIgnoreCase("Enable");

      // Create a new application using the information from the form and the email
      // address of the user who is creating it.
      applicationDAO.createApp((String) request.getSession().getAttribute("principal"),
              name, description, state, apiKey);

      // Redirect the user to the homeapps
      // TODO: notify the client as the app is created
      response.sendRedirect("homeapps");
   }

   /**
    * Handles the HTTP GET method.
    *
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {

      // Read the email address of the user from the sessions.
      String email = (String) request.getSession().getAttribute("principal");
      request.setAttribute("acc", email);

      // Generate a new API key for the future application.
      APIKey apikey = new APIKey(email);
      request.setAttribute("key", apikey.getApikey());

      // For a new app there no end user.
      request.setAttribute("nbUser", "0");

      // Do a log and forward the request.
      Logger.getLogger(LoginServlet.class.getName()).log(Level.INFO, apikey.getApikey());
      request.getRequestDispatcher("/WEB-INF/pages/registerApp.jsp").forward(request, response);
   }

   /**
    * Handles the HTTP POST method.
    *
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
      processRequest(request, response);
   }

   /**
    * Returns a short description of the servlet.
    *
    * @return a String containing servlet description
    */
   @Override
   public String getServletInfo() {
      return "Short description";
   }
}


text:
<?php
include_once '_start.php';

use Bootstrapper\ButtonToolbar;

class ButtonToolbarTest extends BootstrapperWrapper
{
    public function testOpen()
    {
        $open = ButtonToolbar::open($this->testAttributes);
        $matcher = array(
            'tag' => 'div',
            'attributes' => array(
                'class' => 'foo btn-toolbar',
                'data-foo' => 'bar',
            ),
        );

        $this->assertHTML($matcher, $open);
    }

    public function testClose()
    {
        $close = ButtonToolbar::close();

        $this->assertEquals('</div>', $close);
    }
}