text:
namespace AE.Extensions.DependencyInjection.Builder
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using Conventions;

    using Microsoft.Extensions.DependencyInjection;

    public class ServiceDescriptorsBuilder
    {
        private readonly List<ITypesProvider> _typesProviders = new List<ITypesProvider>();

        private readonly List<ITypeSelectionConvention> _typesConventions;

        public ServiceDescriptorsBuilder()
        {
            _typesConventions = new List<ITypeSelectionConvention>
                                    {
                                        new InstanceClassTypeSelectionConvention(),
                                        new DependencyTypeSelectionConvention()
                                    };
        }

        public ServiceDescriptorsBuilder(IEnumerable<ITypeSelectionConvention> selectionConventions)
        {
            if ((selectionConventions == null) || (selectionConventions.Any() == false))
            {
                throw new ArgumentNullException(nameof(selectionConventions));
            }

            _typesConventions.AddRange(selectionConventions);
        }

        public ServiceDescriptorsBuilder AddTypesProvider(ITypesProvider typesProvider)
        {
            if (typesProvider == null)
            {
                throw new ArgumentNullException(nameof(typesProvider));
            }

            _typesProviders.Add(typesProvider);
            return this;
        }

        public ServiceDescriptorsBuilder AddTypesConvention(ITypeSelectionConvention selectionConvention)
        {
            if (selectionConvention == null)
            {
                throw new ArgumentNullException(nameof(selectionConvention));
            }

            _typesConventions.Add(selectionConvention);
            return this;
        }

        public IEnumerable<ServiceDescriptor> Build()
        {
            var typesToRegistration = GetTypesToRegistration();
            return ServicesDescriber.Describe(typesToRegistration);
        }

        private IEnumerable<Type> GetTypesToRegistration()
        {
            var unionConvention = new UnionSelectionConvention(_typesConventions);
            var potentialTypes = SelectPotentialTypes(_typesProviders, unionConvention);
            return GetTypesToRegistration(potentialTypes, unionConvention);
        }

        private static IEnumerable<Type> SelectPotentialTypes(IEnumerable<ITypesProvider> typesProviders, ITypeSelector convention)
        {
            try
            {
                var potentialTypes = typesProviders.AsParallel().SelectMany(provider => provider.RetrieveTypes(convention));
                return potentialTypes.ToList();
            }
            catch (AggregateException e)
            {
                throw e.FlattenTryBubbleUp();
            }
        }

        private static IEnumerable<Type> GetTypesToRegistration(IEnumerable<Type> potentialTypesToRegister, ITypeSelectionConvention convention)
        {
            try
            {
                var typesToregistration = potentialTypesToRegister.AsParallel().Where(convention.DoesPostSelect);
                return typesToregistration.ToList();
            }
            catch (AggregateException e)
            {
                throw e.FlattenTryBubbleUp();
            }
        }

        private class UnionSelectionConvention : ITypeSelectionConvention
        {
            private readonly IEnumerable<ITypeSelectionConvention> _conventionsToUnion;

            internal UnionSelectionConvention(IEnumerable<ITypeSelectionConvention> conventionsToUnion)
            {
                _conventionsToUnion = conventionsToUnion;
            }

            public bool DoesSelect(Type type)
            {
                return _conventionsToUnion.AsParallel().All(x => x.DoesSelect(type));
            }

            public bool DoesPostSelect(Type type)
            {
                return _conventionsToUnion.AsParallel().All(x => x.DoesPostSelect(type));
            }
        }
    }
}


text:
package server

import (
	"math/big"
	"testing"
	"time"

	"github.com/stellar/go/services/bifrost/database"
	"github.com/stellar/go/services/bifrost/ethereum"
	"github.com/stellar/go/services/bifrost/queue"
	"github.com/stellar/go/services/bifrost/sse"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/suite"
)

var weiInEth = new(big.Int).Exp(new(big.Int).SetInt64(10), new(big.Int).SetInt64(18), nil)

type EthereumRailTestSuite struct {
	suite.Suite
	Server        *Server
	MockDatabase  *database.MockDatabase
	MockQueue     *queue.MockQueue
	MockSSEServer *sse.MockServer
}

func (suite *EthereumRailTestSuite) SetupTest() {
	suite.MockDatabase = &database.MockDatabase{}
	suite.MockQueue = &queue.MockQueue{}
	suite.MockSSEServer = &sse.MockServer{}

	suite.Server = &Server{
		Database:          suite.MockDatabase,
		TransactionsQueue: suite.MockQueue,
		SSEServer:         suite.MockSSEServer,
		minimumValueWei:   big.NewInt(1000000000000000000), // 1 ETH
	}
	suite.Server.initLogger()
}

func (suite *EthereumRailTestSuite) TearDownTest() {
	suite.MockDatabase.AssertExpectations(suite.T())
	suite.MockQueue.AssertExpectations(suite.T())
	suite.MockSSEServer.AssertExpectations(suite.T())
}

func (suite *EthereumRailTestSuite) TestInvalidValue() {
	transaction := ethereum.Transaction{
		Hash:     "0x0a190d17ba0405bce37fafd3a7a7bef51264ea4083ffae3b2de90ed61ee5264e",
		ValueWei: big.NewInt(500000000000000000), // 0.5 ETH
		To:       "0x80D3ee1268DC1A2d1b9E73D49050083E75Ef7c2D",
	}
	suite.MockDatabase.AssertNotCalled(suite.T(), "AddProcessedTransaction")
	suite.MockQueue.AssertNotCalled(suite.T(), "QueueAdd")
	err := suite.Server.onNewEthereumTransaction(transaction)
	suite.Require().NoError(err)
}

func (suite *EthereumRailTestSuite) TestAssociationNotExist() {
	transaction := ethereum.Transaction{
		Hash:     "0x0a190d17ba0405bce37fafd3a7a7bef51264ea4083ffae3b2de90ed61ee5264e",
		ValueWei: weiInEth,
		To:       "0x80D3ee1268DC1A2d1b9E73D49050083E75Ef7c2D",
	}
	suite.MockDatabase.
		On("GetAssociationByChainAddress", database.ChainEthereum, "0x80D3ee1268DC1A2d1b9E73D49050083E75Ef7c2D").
		Return(nil, nil)
	suite.MockDatabase.AssertNotCalled(suite.T(), "AddProcessedTransaction")
	suite.MockQueue.AssertNotCalled(suite.T(), "QueueAdd")
	err := suite.Server.onNewEthereumTransaction(transaction)
	suite.Require().NoError(err)
}

func (suite *EthereumRailTestSuite) TestAssociationAlreadyProcessed() {
	transaction := ethereum.Transaction{
		Hash:     "0x0a190d17ba0405bce37fafd3a7a7bef51264ea4083ffae3b2de90ed61ee5264e",
		ValueWei: weiInEth,
		To:       "0x80D3ee1268DC1A2d1b9E73D49050083E75Ef7c2D",
	}
	association := &database.AddressAssociation{
		Chain:            database.ChainEthereum,
		AddressIndex:     1,
		Address:          "0x80D3ee1268DC1A2d1b9E73D49050083E75Ef7c2D",
		StellarPublicKey: "GDULKYRRVOMASFMXBYD4BYFRSHAKQDREEVVP2TMH2CER3DW2KATIOASB",
		CreatedAt:        time.Now(),
	}
	suite.MockDatabase.
		On("GetAssociationByChainAddress", database.ChainEthereum, transaction.To).
		Return(association, nil)
	suite.MockDatabase.
		On("AddProcessedTransaction", database.ChainEthereum, transaction.Hash, transaction.To).
		Return(true, nil)
	suite.MockQueue.AssertNotCalled(suite.T(), "QueueAdd")
	err := suite.Server.onNewEthereumTransaction(transaction)
	suite.Require().NoError(err)
}

func (suite *EthereumRailTestSuite) TestAssociationSuccess() {
	transaction := ethereum.Transaction{
		Hash:     "0x0a190d17ba0405bce37fafd3a7a7bef51264ea4083ffae3b2de90ed61ee5264e",
		ValueWei: weiInEth,
		To:       "0x80D3ee1268DC1A2d1b9E73D49050083E75Ef7c2D",
	}
	association := &database.AddressAssociation{
		Chain:            database.ChainEthereum,
		AddressIndex:     1,
		Address:          "0x80D3ee1268DC1A2d1b9E73D49050083E75Ef7c2D",
		StellarPublicKey: "GDULKYRRVOMASFMXBYD4BYFRSHAKQDREEVVP2TMH2CER3DW2KATIOASB",
		CreatedAt:        time.Now(),
	}
	suite.MockDatabase.
		On("GetAssociationByChainAddress", database.ChainEthereum, transaction.To).
		Return(association, nil)
	suite.MockDatabase.
		On("AddProcessedTransaction", database.ChainEthereum, transaction.Hash, transaction.To).
		Return(false, nil)
	suite.MockQueue.
		On("QueueAdd", mock.AnythingOfType("queue.Transaction")).
		Return(nil).
		Run(func(args mock.Arguments) {
			queueTransaction := args.Get(0).(queue.Transaction)
			suite.Assert().Equal(transaction.Hash, queueTransaction.TransactionID)
			suite.Assert().Equal("ETH", string(queue.AssetCodeETH))
			suite.Assert().Equal(queue.AssetCodeETH, queueTransaction.AssetCode)
			suite.Assert().Equal("1.0000000", queueTransaction.Amount)
			suite.Assert().Equal(association.StellarPublicKey, queueTransaction.StellarPublicKey)
		})
	suite.MockSSEServer.
		On("BroadcastEvent", transaction.To, sse.TransactionReceivedAddressEvent, []byte(nil))
	err := suite.Server.onNewEthereumTransaction(transaction)
	suite.Require().NoError(err)
}

func TestEthereumRailTestSuite(t *testing.T) {
	suite.Run(t, new(EthereumRailTestSuite))
}

redpajama_set_name: RedPajamaGithub


text:
.rotate {

    /* Safari */
    -webkit-transform: rotate(-90deg);

    /* Firefox */
    -moz-transform: rotate(-90deg);

    /* IE */
    -ms-transform: rotate(-90deg);

    /* Opera */
    -o-transform: rotate(-90deg);

    /* Internet Explorer */
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);

}


text:
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
import Nav from './Nav';

class Home extends Component {

  render() {
    return (
      <div>
        <Nav />
        Everyone can access home page.
      </div>
    );
  }
}

export default Home;


text:
import json
import sys
import os
import pscheduler
import math

'''
print float
'''
def format_float(label, value, units="", default="Not Reported"):
    prefix_length=22
    output = label + " ..."
    prefix_length -= len(output)
    for i in range(0, prefix_length):
        output += "."

    if value:
        output += " %.2f %s\n" % (value, units)
    else:
        output += " %s\n" % default

    return output

'''
Percentile: Used by histogram class to calculate percentiles using the NIST
algorithm (http://www.itl.nist.gov/div898/handbook/prc/section2/prc252.htm)
'''
class Percentile(object):

    def __init__(self, percentile, sample_size):
        self.value = None
        self.is_calculated = False
        self.percentile = percentile
        self.sample_size = sample_size
        self.n = (self.percentile/100.0)*(sample_size + 1)
        self.k = math.floor(self.n)
        self.d = self.n - self.k

        if percentile == 50:
            self.key = "median"
        else:
            self.key = "percentile-%d" % percentile

    def findvalue(self, count, hist_value):
        if self.value is not None:
            self.value += (self.d * (hist_value - self.value))
            self.is_calculated = True
        elif self.k == 0:
            self.value = hist_value
            self.is_calculated = True
        elif count >= self.sample_size and self.k >= self.sample_size:
            self.value = hist_value
            self.is_calculated = True
        elif (self.k + self.d) < count:
            self.value = hist_value
            self.is_calculated = True
        else:
            self.value = hist_value

'''
Histogram class used to calculate common histogram metrics
'''
class Histogram(object):

    def __init__(self, hist_dict):
        self.hist_dict = hist_dict

    def get_stats(self):
        #pass one: mode, mean and sample size
        stats = {}
        mean_num = 0
        sample_size = 0
        for k in self.hist_dict:
            #only can do statistics for histograms with numeric buckets
            try:
                float(k)
            except ValueError:
                return {}

            # update calculation values
            if 'mode' not in stats or self.hist_dict[k] > self.hist_dict[stats['mode'][0]]:
               stats['mode'] = [ k ]
            elif self.hist_dict[k] == self.hist_dict[stats['mode'][0]]:
                stats['mode'].append(k)
            mean_num += (float(k) * self.hist_dict[k])
            sample_size += self.hist_dict[k]
        if sample_size == 0:
            return {}
        stats['mean'] = (mean_num/(1.0*sample_size))

        #sort items. make sure sort as numbers not strings
        sorted_hist = sorted(self.hist_dict.iteritems(), key=lambda k: float(k[0]))

        #make mode floats.
        stats['mode'] = map(lambda x: float(x), stats['mode'])
        #get min and max
        stats['minimum'] = float(sorted_hist[0][0])
        stats['maximum'] = float(sorted_hist[len(sorted_hist)-1][0])

        #pass two: get quantiles, variance, and std deviation
        stddev = 0
        quantiles = [25, 50, 75, 95]
        percentiles = [Percentile(q, sample_size) for q in quantiles]
        percentile = percentiles.pop(0)
        curr_count = 0
        for hist_item in sorted_hist:
            #stddev/variance
            stddev += (math.pow(float(hist_item[0]) - stats['mean'], 2)*hist_item[1])
            #quantiles
            curr_count += hist_item[1]
            while percentile is not None and curr_count >= percentile.k:
                percentile.findvalue(curr_count, float(hist_item[0]))
                #some percentiles require next item in list, so may have to wait until next iteration
                if percentile.is_calculated:
                    #calculated so add to dict
                    stats[percentile.key] = percentile.value
                else:
                    #unable to calculate this pass, so break loop
                    break

                #get next percentile
                if len(percentiles) > 0:
                    percentile = percentiles.pop(0)
                else:
                    percentile = None

        #set standard deviation
        stats['variance'] = stddev/sample_size
        stats['standard-deviation'] = math.sqrt(stats['variance'])
        return stats


text:
TZDateTimeField = {
	data: null,

	initialise : function () {
		this.timezoneSelector = jQuery(this).find(':input[name$="\[timezone\]"]')[0];
		this.dateInput = jQuery(this).find(':input[name$="\[date\]"]')[0];
		this.timeInput = jQuery(this).find(':input[name$="\[time\]"]')[0];
		this.pastValue = this.timezoneSelector.options[this.timezoneSelector.selectedIndex].value;
		this.timezoneSelector.onchange = this.convert.bind(this);
	},

	convert: function() {
		if (!this.dateInput.value) return false;

		var self = this;

		// TODO Support more than NZ date formats
		var dateUser = this.dateInput.value.split('/');
		var dateISO = dateUser[2]+'-'+dateUser[1]+'-'+dateUser[0];

		var metadata = jQuery(this).metadata({type: 'class'});
		var url = metadata.convertURL;
		url += '?' + jQuery.param({
			fromTz: this.pastValue,
			toTz: jQuery(this.timezoneSelector).val(),
			datetime: dateISO + ' ' + this.timeInput.value
		});

		jQuery(this.timezoneSelector).attr('disabled', 'disabled');
		jQuery(this.timeInput).attr('disabled', 'disabled');
		jQuery(this.dateInput).attr('disabled', 'disabled');
		jQuery.ajax({
			url: url,
			dataType: 'json',
			success: function(data) {
				// TODO Fixed date format assumptions
				jQuery(self.dateInput).val(data.popupdatetime.split(' ')[0]);
				jQuery(self.timeInput).val(data.popupdatetime.split(' ')[1]);
			},
			complete: function() {
				jQuery(self.timezoneSelector).removeAttr('disabled');
				jQuery(self.timeInput).removeAttr('disabled');
				jQuery(self.dateInput).removeAttr('disabled');
			}
		});

		this.pastValue = jQuery(this.timezoneSelector).val();

		return false;
	}
};

Behaviour.register({
	'div.tzdatetime' : TZDateTimeField
});


text:
package org.oscm.app.vmware.business;

import java.text.DecimalFormat;
import java.util.List;

import org.oscm.app.v2_0.exceptions.APPlatformException;
import org.oscm.app.vmware.business.VMwareValue.Unit;
import org.oscm.app.vmware.business.balancer.LoadBalancerConfiguration;
import org.oscm.app.vmware.business.model.VMwareHost;
import org.oscm.app.vmware.business.model.VMwareStorage;
import org.oscm.app.vmware.i18n.Messages;
import org.oscm.app.vmware.remote.vmware.ManagedObjectAccessor;
import org.oscm.app.vmware.remote.vmware.VMwareClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vmware.vim25.CustomizationAdapterMapping;
import com.vmware.vim25.CustomizationDhcpIpGenerator;
import com.vmware.vim25.CustomizationFixedIp;
import com.vmware.vim25.CustomizationGlobalIPSettings;
import com.vmware.vim25.CustomizationGuiRunOnce;
import com.vmware.vim25.CustomizationGuiUnattended;
import com.vmware.vim25.CustomizationIPSettings;
import com.vmware.vim25.CustomizationIdentification;
import com.vmware.vim25.CustomizationLinuxOptions;
import com.vmware.vim25.CustomizationLinuxPrep;
import com.vmware.vim25.CustomizationPassword;
import com.vmware.vim25.CustomizationSpec;
import com.vmware.vim25.CustomizationSysprep;
import com.vmware.vim25.CustomizationUserData;
import com.vmware.vim25.CustomizationVirtualMachineName;
import com.vmware.vim25.CustomizationWinOptions;
import com.vmware.vim25.DatastoreHostMount;
import com.vmware.vim25.DynamicProperty;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.TaskInfo;
import com.vmware.vim25.VimPortType;
import com.vmware.vim25.VirtualDevice;
import com.vmware.vim25.VirtualMachineCloneSpec;
import com.vmware.vim25.VirtualMachineConfigInfo;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VirtualMachineRelocateSpec;

public class Template {

    private static final Logger logger = LoggerFactory
            .getLogger(Template.class);
    private static final int DEFAULT_TIMEZONE = 110;
    protected VMwareClient vmw;

    /**
     * Creates a new VMware instance based on a given template.
     *
     * @param vmw
     *            connected VMware client entity
     * @param paramHandler
     *            entity which holds all properties of the instance.
     * @return name of the created instance
     */
    public TaskInfo cloneVM(VMPropertyHandler paramHandler) throws Exception {
        logger.info("cloneVMFromTemplate() template: "
                + paramHandler.getTemplateName());

        String datacenter = paramHandler.getTargetDatacenter();
        String cluster = paramHandler.getTargetCluster();
        String template = paramHandler.getTemplateName();
        logger.debug("Datacenter: " + datacenter + " Cluster: " + cluster
                + " Template: " + template);

        ManagedObjectReference vmDataCenter = vmw.getServiceUtil()
                .getDecendentMoRef(null, "Datacenter", datacenter);
        if (vmDataCenter == null) {
            logger.error("Datacenter not found. dataCenter: " + datacenter);
            throw new APPlatformException(Messages.get(
                    paramHandler.getLocale(), "error_invalid_datacenter",
                    new Object[] { datacenter }));
        }

        ManagedObjectReference vmTpl = vmw.getServiceUtil().getDecendentMoRef(
                vmDataCenter, "VirtualMachine", template);
        if (vmTpl == null) {
            logger.error("Template not found in datacenter. datacenter: "
                    + datacenter + " template: " + template);
            throw new APPlatformException(Messages.get(
                    paramHandler.getLocale(), "error_invalid_template",
                    new Object[] { template }));
        }

        Long templateDiskSpace = (Long) vmw.getServiceUtil()
                .getDynamicProperty(vmTpl, "summary.storage.unshared");
        if (templateDiskSpace == null) {
            logger.error("Missing disk size in template. template: " + template);
            throw new APPlatformException(Messages.get(
                    paramHandler.getLocale(), "error_missing_template_size"));
        }

        VirtualMachineConfigInfo configSpec = (VirtualMachineConfigInfo) vmw
                .getServiceUtil().getDynamicProperty(vmTpl, "config");

        double tplDiskSpace = VMwareValue.fromBytes(
                templateDiskSpace.longValue()).getValue(Unit.MB);
        if (paramHandler.getConfigDiskSpaceMB() != .0) {
            double requestedDiskSpace = paramHandler.getConfigDiskSpaceMB();
            List<VirtualDevice> devices = configSpec.getHardware().getDevice();
            long capacityInKB = DiskManager.getSystemDiskCapacity(devices,
                    configSpec.getName());
            double requestedDiskSpaceKB = requestedDiskSpace * 1024.0;
            logger.debug("Requested disk space: " + requestedDiskSpaceKB
                    + "Template disk space: " + capacityInKB + " template: "
                    + template);
            if (requestedDiskSpaceKB < capacityInKB) {
                String minValExp = new DecimalFormat("#0.#")
                        .format(VMwareValue
                                .fromMegaBytes(capacityInKB / 1024.0).getValue(
                                        Unit.GB));
                logger.error("Requested disk space is smaller than template disk space. template: "
                        + template);
                throw new APPlatformException(Messages.get(
                        paramHandler.getLocale(), "error_invalid_diskspace",
                        new Object[] { minValExp }));
            }

            paramHandler.setTemplateDiskSpaceMB(requestedDiskSpace);
        } else {
            logger.debug("Use template disk space. template: " + template);
            paramHandler.setTemplateDiskSpaceMB(tplDiskSpace);
        }

        VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
        VirtualMachineRelocateSpec relocSpec = setHostAndStorage(vmw,
                paramHandler, vmDataCenter, datacenter, cluster);
        cloneSpec.setLocation(relocSpec);
        cloneSpec.setPowerOn(false);
        cloneSpec.setTemplate(false);

        CustomizationSpec custSpec = getCustomizationSpec(configSpec,
                paramHandler);
        cloneSpec.setCustomization(custSpec);

        VirtualMachineConfigSpec vmConfSpec = new VirtualMachineConfigSpec();

        String respPerson = paramHandler
                .getServiceSetting(VMPropertyHandler.TS_RESPONSIBLE_PERSON);

        String reqUser = paramHandler
                .getServiceSetting(VMPropertyHandler.REQUESTING_USER);

        String systemvariante = "";

        String comment = Messages.get(paramHandler.getLocale(), "vm_comment",
                new Object[] {
                        paramHandler.getSettings().getOrganizationName(),
                        paramHandler.getSettings().getSubscriptionId(),
                        reqUser, respPerson, systemvariante });
        vmConfSpec.setAnnotation(comment);
        cloneSpec.setConfig(vmConfSpec);

        String targetFolder = paramHandler.getTargetFolder();
        ManagedObjectReference moRefTargetFolder = null;

        if (targetFolder != null) {
            moRefTargetFolder = vmw.getServiceUtil().getDecendentMoRef(null,
                    "Folder", targetFolder);
        } else {
            moRefTargetFolder = (ManagedObjectReference) vmw.getServiceUtil()
                    .getDynamicProperty(vmTpl, "parent");
        }

        if (moRefTargetFolder == null) {
            logger.error("Target folder " + targetFolder + " not found.");
            throw new APPlatformException(Messages.get(
                    paramHandler.getLocale(), "error_invalid_target_folder",
                    new Object[] { targetFolder }));
        }

        String newInstanceName = paramHandler.getInstanceName();
        logger.debug("Call vSphere API: cloneVMTask() instancename: "
                + newInstanceName + " targetfolder: "
                + paramHandler.getTargetFolder());
        VimPortType service = vmw.getConnection().getService();
        ManagedObjectReference cloneTask = service.cloneVMTask(vmTpl,
                moRefTargetFolder, newInstanceName, cloneSpec);

        return (TaskInfo) vmw.getServiceUtil().getDynamicProperty(cloneTask,
                "info");
    }

    /**
     * Generates customization specification for OS specific deployment.
     *
     * @param custProps
     *            customization specific parameters
     * @return filled VMware customization block
     */
    private CustomizationSpec getCustomizationSpec(
            VirtualMachineConfigInfo configSpec, VMPropertyHandler paramHandler)
            throws APPlatformException {

        String guestid = configSpec.getGuestId();
        if (guestid == null) {
            throw new APPlatformException(
                    "Operatingsystem not defined in Guest-Id.");
        }

        boolean isLinux = guestid.startsWith("cent")
                || guestid.startsWith("debian")
                || guestid.startsWith("freebsd")
                || guestid.startsWith("oracle")
                || guestid.startsWith("other24xLinux")
                || guestid.startsWith("other26xLinux")
                || guestid.startsWith("otherLinux")
                || guestid.startsWith("coreos") || guestid.startsWith("redhat")
                || guestid.startsWith("rhel") || guestid.startsWith("sles")
                || guestid.startsWith("suse") || guestid.startsWith("ubuntu");
        boolean isWindows = guestid.startsWith("win");

        logger.debug("isLinux: " + isLinux + " isWindows: " + isWindows
                + " guestid: " + configSpec.getGuestId() + " OS: "
                + configSpec.getGuestFullName());

        if (!isLinux && !isWindows) {
            logger.error("GuestId cannot be interpreted. guestid: "
                    + configSpec.getGuestId() + " OS: "
                    + configSpec.getGuestFullName());
            throw new APPlatformException("Unsupported operating system "
                    + configSpec.getGuestFullName());
        }

        CustomizationSpec cspec = new CustomizationSpec();
        CustomizationGlobalIPSettings gIP = new CustomizationGlobalIPSettings();
        cspec.setGlobalIPSettings(gIP);

        if (isLinux) {
            String[] dnsserver = paramHandler.getDNSServer(1).split(",");
            for (String server : dnsserver) {
                logger.debug("Linux -> CustomizationGlobalIPSettings -> DNS server: "
                        + server);
                gIP.getDnsServerList().add(server.trim());
            }

            String[] dnssuffix = paramHandler.getDNSSuffix(1).split(",");
            for (String suffix : dnssuffix) {
                logger.debug("Linux -> CustomizationGlobalIPSettings -> DNS suffix: "
                        + suffix);
                gIP.getDnsSuffixList().add(suffix.trim());
            }

            CustomizationLinuxPrep sprep = new CustomizationLinuxPrep();

            String domain = paramHandler
                    .getServiceSetting(VMPropertyHandler.TS_DOMAIN_NAME);
            logger.debug("Linux domain name: " + domain);
            if (domain != null) {
                sprep.setDomain(domain);
            }

            sprep.setHostName(new CustomizationVirtualMachineName());
            sprep.setTimeZone("363");

            sprep.setHwClockUTC(Boolean.TRUE);
            cspec.setIdentity(sprep);
            cspec.setOptions(new CustomizationLinuxOptions());
        }

        if (isWindows) {
            CustomizationSysprep sprep = new CustomizationSysprep();
            CustomizationGuiUnattended guiUnattended = new CustomizationGuiUnattended();
            guiUnattended.setAutoLogon(false);
            guiUnattended.setAutoLogonCount(0);
            guiUnattended.setTimeZone(DEFAULT_TIMEZONE);

            if (paramHandler
                    .isServiceSettingTrue(VMPropertyHandler.TS_WINDOWS_DOMAIN_JOIN)) {
                CustomizationIdentification identification = new CustomizationIdentification();
                String domainName = paramHandler
                        .getServiceSettingValidated(VMPropertyHandler.TS_DOMAIN_NAME);
                String domainAdmin = paramHandler
                        .getServiceSettingValidated(VMPropertyHandler.TS_WINDOWS_DOMAIN_ADMIN);
                String domainAdminPwd = paramHandler
                        .getServiceSettingValidated(VMPropertyHandler.TS_WINDOWS_DOMAIN_ADMIN_PWD);

                logger.debug("Join Domain " + domainName + " admin: "
                        + domainAdmin + " pwd: " + domainAdminPwd);

                identification.setJoinDomain(domainName);
                identification.setDomainAdmin(domainAdmin);
                CustomizationPassword password = new CustomizationPassword();
                password.setValue(domainAdminPwd);
                password.setPlainText(true);
                identification.setDomainAdminPassword(password);
                sprep.setIdentification(identification);
            } else {
                CustomizationIdentification identification = new CustomizationIdentification();
                String workgroup = paramHandler
                        .getServiceSettingValidated(VMPropertyHandler.TS_WINDOWS_WORKGROUP);
                identification.setJoinWorkgroup(workgroup);
                sprep.setIdentification(identification);
                logger.debug("Create workgroup " + workgroup);
            }

            String adminPwd = paramHandler
                    .getServiceSetting(VMPropertyHandler.TS_WINDOWS_LOCAL_ADMIN_PWD);

            if ((adminPwd == null || adminPwd.length() == 0)
                    && !paramHandler
                            .isServiceSettingTrue(VMPropertyHandler.TS_WINDOWS_DOMAIN_JOIN)) {
                logger.error("The VM is not joining a Windows domain. A local administrator password is required but not set.");
                throw new APPlatformException(
                        "The VM is not joining a Windows domain. A local administrator password is required but not set.");
            } else if (adminPwd != null && adminPwd.length() > 0) {
                CustomizationPassword password = new CustomizationPassword();
                password.setValue(adminPwd);
                password.setPlainText(true);
                guiUnattended.setPassword(password);
                logger.debug("Set Windows local administrator pwd: " + adminPwd);
            }

            sprep.setGuiUnattended(guiUnattended);

            String command = paramHandler
                    .getServiceSetting(VMPropertyHandler.TS_SYSPREP_RUNONCE_COMMAND);

            if (command != null) {
                logger.debug("sysprep runonce command: " + command);
                CustomizationGuiRunOnce guiRunOnce = new CustomizationGuiRunOnce();
                guiRunOnce.getCommandList().add(command);
                sprep.setGuiRunOnce(guiRunOnce);
            }

            CustomizationUserData userData = new CustomizationUserData();
            userData.setComputerName(new CustomizationVirtualMachineName());

            String fullname = paramHandler
                    .getResponsibleUserAsString(paramHandler.getLocale());
            if (fullname == null) {
                fullname = "No responsible user defined";
            }
            logger.debug("CustomizationUserData.fullName: " + fullname);

            userData.setFullName(fullname);
            userData.setOrgName("Created by OSCM");

            String licenseKey = paramHandler
                    .getServiceSetting(VMPropertyHandler.TS_WINDOWS_LICENSE_KEY);

            if (licenseKey != null && licenseKey.trim().length() > 0) {
                userData.setProductId(licenseKey);
            } else {
                userData.setProductId("");
            }

            sprep.setUserData(userData);

            cspec.setIdentity(sprep);

            CustomizationWinOptions options = new CustomizationWinOptions();
            options.setChangeSID(true);
            options.setDeleteAccounts(false);
            cspec.setOptions(options);
        }

        int numberOfNICs = Integer.parseInt(paramHandler
                .getServiceSetting(VMPropertyHandler.TS_NUMBER_OF_NICS));
        logger.debug("Number of NICs in template: " + numberOfNICs);
        for (int i = 1; i <= numberOfNICs; i++) {
            CustomizationAdapterMapping networkAdapter = new CustomizationAdapterMapping();
            CustomizationIPSettings ipSettings = new CustomizationIPSettings();
            if (paramHandler.isAdapterConfiguredByDhcp(i)) {
                CustomizationDhcpIpGenerator publicDhcpIp = new CustomizationDhcpIpGenerator();
                ipSettings.setIp(publicDhcpIp);
            } else {
                logger.debug("NIC" + i + " IP:" + paramHandler.getIpAddress(i));
                CustomizationFixedIp newip = new CustomizationFixedIp();
                newip.setIpAddress(paramHandler.getIpAddress(i));
                ipSettings.setIp(newip);

                String[] gateways = paramHandler.getGateway(i).split(",");
                for (String gw : gateways) {
                    logger.debug("NIC" + i + " Gateway:" + gw);
                    ipSettings.getGateway().add(gw.trim());
                }

                if (isWindows) {
                    String[] dnsserver = paramHandler.getDNSServer(i)
                            .split(",");
                    for (String server : dnsserver) {
                        logger.debug("NIC" + i + " DNS server:" + server);
                        ipSettings.getDnsServerList().add(server.trim());
                    }
                }

                logger.debug("NIC" + i + " Subnetmask:"
                        + paramHandler.getSubnetMask(i));
                ipSettings.setSubnetMask(paramHandler.getSubnetMask(i).trim());
            }
            networkAdapter.setAdapter(ipSettings);
            cspec.getNicSettingMap().add(networkAdapter);
        }

        return cspec;
    }

    /**
     * If host and storage are not defined as technical service parameter then
     * the load balancing mechanism is used to determine host and storage
     */
    private VirtualMachineRelocateSpec setHostAndStorage(VMwareClient vmw,
            VMPropertyHandler paramHandler,
            ManagedObjectReference vmDataCenter, String datacenter,
            String cluster) throws Exception {
        logger.debug("datacenter: " + datacenter + " cluster: " + cluster);
        String xmlData = paramHandler.getHostLoadBalancerConfig();
        VirtualMachineRelocateSpec relocSpec = new VirtualMachineRelocateSpec();

        String storageName = paramHandler
                .getServiceSetting(VMPropertyHandler.TS_TARGET_STORAGE);
        String hostName = paramHandler
                .getServiceSetting(VMPropertyHandler.TS_TARGET_HOST);
        if (hostName == null || hostName.trim().length() == 0) {
            logger.debug("target host not set. get host and storage from loadbalancer");
            VMwareDatacenterInventory inventory = readDatacenterInventory(vmw,
                    datacenter, cluster);
            LoadBalancerConfiguration balancerConfig = new LoadBalancerConfiguration(
                    xmlData, inventory);
            VMwareHost host = balancerConfig.getBalancer().next(paramHandler);
            hostName = host.getName();
            paramHandler.setSetting(VMPropertyHandler.TS_TARGET_HOST, hostName);
            VMwareStorage storage = host.getNextStorage(paramHandler);
            storageName = storage.getName();
        } else {
            if (storageName == null || storageName.trim().length() == 0) {
                logger.debug("target storage not set. get host and storage from loadbalancer");
                VMwareDatacenterInventory inventory = readDatacenterInventory(
                        vmw, datacenter, cluster);
                VMwareHost host = inventory.getHost(hostName);
                VMwareStorage storage = host.getNextStorage(paramHandler);
                storageName = storage.getName();
            }
        }

        logger.info("Target Host: " + hostName + " Target Storage: "
                + storageName);
        ManagedObjectReference vmHost = vmw.getServiceUtil().getDecendentMoRef(
                vmDataCenter, "HostSystem", hostName);
        if (vmHost == null) {
            logger.error("Target host " + hostName + " not found");
            throw new APPlatformException(Messages.getAll("error_invalid_host",
                    new Object[] { hostName }));
        }

        ManagedObjectReference vmHostCluster = (ManagedObjectReference) vmw
                .getServiceUtil().getDynamicProperty(vmHost, "parent");
        ManagedObjectReference vmPool = vmw.getServiceUtil().getDecendentMoRef(
                vmHostCluster, "ResourcePool", "Resources");
        if (vmPool == null) {
            logger.error("Resourcepool not found");
            throw new APPlatformException(Messages.getAll("error_invalid_pool",
                    new Object[] { hostName }));
        }

        ManagedObjectReference vmDatastore = null;
        Object vmHostDatastores = vmw.getServiceUtil().getDynamicProperty(
                vmHost, "datastore");
        if (vmHostDatastores instanceof List<?>) {
            for (Object vmHostDatastore : (List<?>) vmHostDatastores) {
                if (vmHostDatastore instanceof ManagedObjectReference) {
                    String dsname = (String) vmw.getServiceUtil()
                            .getDynamicProperty(
                                    (ManagedObjectReference) vmHostDatastore,
                                    "summary.name");
                    if (dsname.equalsIgnoreCase(storageName)) {
                        vmDatastore = (ManagedObjectReference) vmHostDatastore;
                        break;
                    }
                } else {
                    logger.warn("Expected datastore information as 'ManagedObjectReference' but recieved object of type "
                            + (vmHostDatastore == null ? "[null]"
                                    : vmHostDatastore.getClass()
                                            .getSimpleName()));
                }
            }
        }
        if (vmDatastore == null) {
            logger.error("Target datastore " + storageName + " not found");
            throw new APPlatformException(Messages.getAll(
                    "error_invalid_datastore", new Object[] { storageName,
                            hostName }));
        }

        relocSpec.setDatastore(vmDatastore);
        relocSpec.setPool(vmPool);
        relocSpec.setHost(vmHost);
        return relocSpec;
    }

    @SuppressWarnings("unchecked")
    private VMwareDatacenterInventory readDatacenterInventory(
            VMwareClient appUtil, String datacenter, String cluster)
            throws Exception {
        logger.debug("datacenter: " + datacenter + " cluster: " + cluster);

        ManagedObjectAccessor serviceUtil = appUtil.getServiceUtil();

        ManagedObjectReference dcMoRef = serviceUtil.getDecendentMoRef(null,
                "Datacenter", datacenter);

        ManagedObjectReference clusterMoRef = serviceUtil.getDecendentMoRef(
                dcMoRef, "ClusterComputeResource", cluster);

        List<ManagedObjectReference> hostMoRefs = (List<ManagedObjectReference>) serviceUtil
                .getDynamicProperty(clusterMoRef, "host");

        VMwareDatacenterInventory inventory = new VMwareDatacenterInventory();
        for (ManagedObjectReference hostRef : hostMoRefs) {
            List<DynamicProperty> dps = serviceUtil.getDynamicProperty(hostRef,
                    new String[] { "name", "summary.hardware.memorySize",
                            "summary.hardware.numCpuCores" });
            String host = "";
            for (DynamicProperty dp : dps) {
                String key = dp.getName();
                if ("name".equals(key) && dp.getVal() != null) {
                    host = dp.getVal().toString();
                }
            }
            logger.debug("addHostSystem host: " + host);
            inventory.addHostSystem(dps);

            List<ManagedObjectReference> storageRefs = (List<ManagedObjectReference>) serviceUtil
                    .getDynamicProperty(hostRef, "datastore");
            for (ManagedObjectReference storageRef : storageRefs) {
                dps = serviceUtil.getDynamicProperty(storageRef,
                        new String[] { "summary.name", "summary.capacity",
                                "summary.freeSpace" });

                String storageName = "";
                for (DynamicProperty dp : dps) {
                    String key = dp.getName();
                    if ("summary.name".equals(key) && dp.getVal() != null) {
                        storageName = dp.getVal().toString();
                    }
                }

                List<DatastoreHostMount> hostMounts = (List<DatastoreHostMount>) serviceUtil
                        .getDynamicProperty(storageRef, "host");

                for (DatastoreHostMount hm : hostMounts) {
                    ManagedObjectReference hostMor = hm.getKey();
                    String hostThatLinksToThisStoarge = (String) serviceUtil
                            .getDynamicProperty(hostMor, "name");
                    if (host.equals(hostThatLinksToThisStoarge)
                            && hm.getMountInfo().isAccessible().booleanValue()
                            && hm.getMountInfo().isMounted().booleanValue()
                            && !hm.getMountInfo().getAccessMode()
                                    .equals("readOnly")) {

                        logger.debug("addStorage host: " + host + " storage: "
                                + storageName);
                        inventory.addStorage(host, dps);
                    }
                }
            }

            List<ManagedObjectReference> vmRefs = (List<ManagedObjectReference>) serviceUtil
                    .getDynamicProperty(hostRef, "vm");
            for (ManagedObjectReference vmRef : vmRefs) {
                dps = serviceUtil.getDynamicProperty(vmRef, new String[] {
                        "name", "summary.config.memorySizeMB",
                        "summary.config.numCpu", "runtime.host" });
                inventory.addVirtualMachine(dps, serviceUtil);
            }

        }
        inventory.initialize();
        return inventory;
    }

}


text:
<?php

declare(strict_types=1);

namespace Biplane\YandexDirect\Api\V5\Contract;

use AllowDynamicProperties;

/**
 * Auto-generated code.
 */
#[AllowDynamicProperties]
class ExceptionNotification
{
    protected $Code = null;

    protected $Message = null;

//    Can be omitted.
//    protected $Details = null;

    /**
     * @return static
     */
    public static function create()
    {
        return new static();
    }

    public function getCode(): int
    {
        return $this->Code;
    }

    /**
     * @return $this
     */
    public function setCode(int $value)
    {
        $this->Code = $value;

        return $this;
    }

    public function getMessage(): string
    {
        return $this->Message;
    }

    /**
     * @return $this
     */
    public function setMessage(string $value)
    {
        $this->Message = $value;

        return $this;
    }

    public function getDetails(): ?string
    {
        return $this->Details ?? null;
    }

    /**
     * @return $this
     */
    public function setDetails(?string $value = null)
    {
        $this->Details = $value;

        return $this;
    }
}


text:
"""DetCon-B implementation using Jaxline."""

import sys
from typing import Any, Mapping, Text, Tuple

from absl import flags
import haiku as hk
import jax
import jax.numpy as jnp
from jaxline import platform
import ml_collections
import numpy as np
import optax

from detcon import pretrain_common
from detcon.datasets import image_dataset
from detcon.utils import augmentations
from detcon.utils import helpers as byol_helpers
from detcon.utils import losses
from detcon.utils import networks
from detcon.utils import schedules

def featurewise_std(x: jnp.ndarray) -> jnp.ndarray:
  """Computes the featurewise standard deviation."""
  return jnp.mean(jnp.std(x, axis=0))

class PretrainExperiment(pretrain_common.BaseExperiment):
  """DetCon-B's training component definition."""

  def __init__(self, mode: Text, config: ml_collections.ConfigDict):
    """Constructs the experiment.

    Args:
      mode: A string, equivalent to FLAGS.mode when running normally.
      config: Experiment configuration.
    """
    super().__init__(mode, config)

    assert config.training_mode in ['self-supervised', 'supervised', 'both']

    if mode == 'train':
      self.forward = hk.transform_with_state(self._forward)

  def create_binary_mask(
      self,
      batch_size,
      num_pixels,
      masks,
      max_mask_id=256,
      downsample=(1, 32, 32, 1)):
    """Generates binary masks from the Felzenszwalb masks.

    From a FH mask of shape [batch_size, H,W] (values in range
    [0,max_mask_id], produces corresponding (downsampled) binary masks of
    shape [batch_size, max_mask_id, H*W/downsample].
    Args:
      batch_size: batch size of the masks
      num_pixels: Number of points on the spatial grid
      masks: Felzenszwalb masks
      max_mask_id: # unique masks in Felzenszwalb segmentation
      downsample: rate at which masks must be downsampled.
    Returns:
      binary_mask: Binary mask with specification above
    """
    fh_mask_to_use = self.config.model.fh_mask_to_use
    mask = masks[..., fh_mask_to_use:(fh_mask_to_use+1)]

    mask_ids = jnp.arange(max_mask_id).reshape(1, 1, 1, max_mask_id)
    binary_mask = jnp.equal(mask_ids, mask).astype('float32')

    binary_mask = hk.avg_pool(binary_mask, downsample, downsample, 'VALID')
    binary_mask = binary_mask.reshape(batch_size, num_pixels, max_mask_id)
    binary_mask = jnp.argmax(binary_mask, axis=-1)
    binary_mask = jnp.eye(max_mask_id)[binary_mask]
    binary_mask = jnp.transpose(binary_mask, [0, 2, 1])
    return binary_mask

  def sample_masks(self, binary_mask, batch_size, n_random_vectors=16):
    """Samples which binary masks to use in the loss."""
    mask_exists = jnp.greater(binary_mask.sum(-1), 1e-3)
    sel_masks = mask_exists.astype('float32') + 0.00000000001
    sel_masks = sel_masks / sel_masks.sum(1, keepdims=True)
    sel_masks = jnp.log(sel_masks)

    mask_ids = jax.random.categorical(
        hk.next_rng_key(), sel_masks, axis=-1,
        shape=tuple([n_random_vectors, batch_size]))
    mask_ids = jnp.transpose(mask_ids, [1, 0])

    smpl_masks = jnp.stack(
        [binary_mask[b][mask_ids[b]] for b in range(batch_size)])
    return smpl_masks, mask_ids

  def run_detcon_b_forward_on_view(
      self,
      view_encoder: Any,
      projector: Any,
      predictor: Any,
      classifier: Any,
      is_training: bool,
      images: jnp.ndarray,
      masks: jnp.ndarray,
      suffix: Text = '',
      ):
    outputs = {}
    images = self.dataset_adapter.normalize_images(images)

    embedding_local = view_encoder(images, is_training=is_training)
    embedding = jnp.mean(embedding_local, axis=[1, 2])

    bs, emb_h, emb_w, emb_d = embedding_local.shape
    emb_a = emb_h * emb_w

    if masks is not None and self.config.training_mode != 'supervised':
      binary_mask = self.create_binary_mask(bs, emb_a, masks)
      smpl_masks, mask_ids = self.sample_masks(binary_mask, bs)
      smpl_masks_area = smpl_masks.sum(axis=-1, keepdims=True)
      smpl_masks = smpl_masks / jnp.maximum(smpl_masks_area, 1.)

      embedding_local = embedding_local.reshape([bs, emb_a, emb_d])
      smpl_embedding = jnp.matmul(smpl_masks, embedding_local)

      proj_out = projector(smpl_embedding, is_training)
      pred_out = predictor(proj_out, is_training)

      outputs['projection' + suffix] = proj_out
      outputs['prediction' + suffix] = pred_out
      outputs['mask_ids' + suffix] = mask_ids

    # Note the stop_gradient: label information is not leaked into the
    # main network.
    if self.config.training_mode == 'self-supervised':
      embedding = jax.lax.stop_gradient(embedding)

    classif_out = classifier(embedding)
    outputs['logits' + suffix] = classif_out
    return outputs

  def _forward(
      self,
      inputs: image_dataset.Batch,
      is_training: bool,
  ) -> Mapping[Text, jnp.ndarray]:
    """Forward application of byol's architecture.

    Args:
      inputs: A batch of data, i.e. a dictionary, with either two keys,
        (`images` and `labels`) or three keys (`view1`, `view2`, `labels`).
      is_training: Training or evaluating the model? When True, inputs must
        contain keys `view1` and `view2`. When False, inputs must contain key
        `images`.

    Returns:
      All outputs of the model, i.e. a dictionary with projection, prediction
      and logits keys, for either the two views, or the image.
    """
    mlp_kwargs = dict(
        hidden_size=self.config.model.mlp_hidden_size,
        bn_config=self.config.model.norm_config,
        output_size=self.config.model.projection_size)

    encoder = getattr(networks, self.config.model.encoder)
    view_encoder = encoder(
        num_classes=None,  # Don't build the final linear layer
        resnet_v2=self.config.model.encoder_use_v2,
        bn_config=self.config.model.norm_config,
        width_multiplier=self.config.model.encoder_width_multiplier,
        final_mean_pool=False)

    projector = networks.MLP(name='projector', **mlp_kwargs)
    predictor = networks.MLP(name='predictor', **mlp_kwargs)
    classifier = hk.Linear(
        output_size=self.dataset_adapter.num_classes, name='classifier')

    if is_training:
      outputs_view1 = self.run_detcon_b_forward_on_view(
          view_encoder, projector, predictor, classifier, is_training,
          inputs['view1'], inputs['fh_segmentations1'], '_view1')
      outputs_view2 = self.run_detcon_b_forward_on_view(
          view_encoder, projector, predictor, classifier, is_training,
          inputs['view2'], inputs['fh_segmentations2'], '_view2')
      return {**outputs_view1, **outputs_view2}
    else:
      return self.run_detcon_b_forward_on_view(
          view_encoder, projector, predictor, classifier, is_training,
          inputs['images'], None, '')

  def loss_fn(
      self,
      online_params: hk.Params,
      target_params: hk.Params,
      online_state: hk.State,
      target_state: hk.Params,
      rng: jnp.ndarray,
      inputs: image_dataset.Batch,
  ) -> Tuple[jnp.ndarray, Tuple[Mapping[Text, hk.State],
                                pretrain_common.LogsDict]]:
    """Compute BYOL's loss function.

    Args:
      online_params: parameters of the online network (the loss is later
        differentiated with respect to the online parameters).
      target_params: parameters of the target network.
      online_state: internal state of online network.
      target_state: internal state of target network.
      rng: random number generator state.
      inputs: inputs, containing two batches of crops from the same images,
        view1 and view2 and labels

    Returns:
      BYOL's loss, a mapping containing the online and target networks updated
      states after processing inputs, and various logs.
    """
    inputs = self.dataset_adapter.maybe_transpose_on_device(inputs)

    inputs = augmentations.postprocess(inputs, rng)

    online_network_out, online_state = self.forward.apply(
        params=online_params,
        state=online_state,
        rng=rng,
        inputs=inputs,
        is_training=True)
    target_network_out, target_state = self.forward.apply(
        params=target_params,
        state=target_state,
        rng=rng,
        inputs=inputs,
        is_training=True)

    # Representation loss

    # The stop_gradient is not necessary as we explicitly take the gradient with
    # respect to online parameters only in `optax.apply_updates`. We leave it to
    # indicate that gradients are not backpropagated through the target network.

    repr_loss = 0.0
    if self.config.training_mode != 'supervised':
      repr_loss = losses.byol_nce_detcon(
          online_network_out['prediction_view1'],
          online_network_out['prediction_view2'],
          jax.lax.stop_gradient(target_network_out['projection_view1']),
          jax.lax.stop_gradient(target_network_out['projection_view2']),
          online_network_out['mask_ids_view1'],
          online_network_out['mask_ids_view2'],
          target_network_out['mask_ids_view1'],
          target_network_out['mask_ids_view2'],
          temperature=self.config.training.nce_loss_temperature)

    classif_loss, logs = self._classifier_loss(
        logits=online_network_out['logits_view1'], labels=inputs['labels'])
    loss = repr_loss + classif_loss

    if self.config.training_mode != 'supervised':
      logs.update(
          dict(
              loss=loss,
              repr_loss=repr_loss,
              proj_mean=online_network_out['projection_view1'].mean(),
              proj_std=featurewise_std(
                  online_network_out['projection_view1']),
              normalized_proj_std=featurewise_std(
                  byol_helpers.l2_normalize(
                      online_network_out['projection_view1'], axis=-1)),
              pred_mean=online_network_out['prediction_view1'].mean(),
              pred_std=featurewise_std(
                  online_network_out['prediction_view1']),
              normalized_pred_std=featurewise_std(
                  byol_helpers.l2_normalize(
                      online_network_out['prediction_view1'], axis=-1),)))
    else:
      logs.update(dict(loss=loss, repr_loss=repr_loss))

    return loss, (dict(online_state=online_state,
                       target_state=target_state), logs)

  def _update_fn(
      self,
      byol_state: pretrain_common.ExperimentState,
      global_step: jnp.ndarray,
      rng: jnp.ndarray,
      inputs: image_dataset.Batch,
  ) -> Tuple[pretrain_common.ExperimentState, pretrain_common.LogsDict]:
    """Update online and target parameters.

    Args:
      byol_state: current BYOL state.
      global_step: current training step.
      rng: current random number generator
      inputs: inputs, containing two batches of crops from the same images,
        view1 and view2 and labels

    Returns:
      Tuple containing the updated Byol state after processing the inputs, and
      various logs.
    """
    online_params = byol_state.online_params
    target_params = byol_state.target_params
    online_state = byol_state.online_state
    target_state = byol_state.target_state
    opt_state = byol_state.opt_state

    # update online network
    grad_fn = jax.grad(self.loss_fn, argnums=0, has_aux=True)
    grads, (net_states, logs) = grad_fn(online_params, target_params,
                                        online_state, target_state, rng, inputs)

    # cross-device grad and logs reductions
    grads = jax.tree_map(lambda v: jax.lax.pmean(v, axis_name='i'), grads)
    logs = jax.tree_multimap(lambda x: jax.lax.pmean(x, axis_name='i'), logs)

    lr = self.lr_schedule(global_step)
    updates, opt_state = self._optimizer(lr).update(grads, opt_state,
                                                    online_params)
    online_params = optax.apply_updates(online_params, updates)

    # update target network
    tau = schedules.target_ema(
        global_step,
        base_ema=self.config.training.base_target_ema,
        max_steps=self.config.training.max_steps)
    target_params = jax.tree_multimap(lambda x, y: x + (1 - tau) * (y - x),
                                      target_params, online_params)
    logs['tau'] = tau
    logs['lr'] = lr

    n_params = 0

    for key in online_params:
      for l in online_params[key]:
        n_params += np.prod(online_params[key][l].shape)

    logs['n_params'] = n_params

    return pretrain_common.ExperimentState(
        online_params=online_params,
        target_params=target_params,
        online_state=net_states['online_state'],
        target_state=net_states['target_state'],
        opt_state=opt_state), logs

  def _make_initial_state(
      self,
      rng: jnp.ndarray,
      dummy_input: image_dataset.Batch,
  ) -> pretrain_common.ExperimentState:
    """BYOL's _ExperimentState initialization.

    Args:
      rng: random number generator used to initialize parameters. If working in
        a multi device setup, this need to be a ShardedArray.
      dummy_input: a dummy image, used to compute intermediate outputs shapes.

    Returns:
      Initial Byol state.
    """
    rng_online, rng_target = jax.random.split(rng)

    dummy_input = self.dataset_adapter.maybe_transpose_on_device(dummy_input)

    # Online and target parameters are initialized using different rngs,
    # in our experiments we did not notice a significant different with using
    # the same rng for both.
    online_params, online_state = self.forward.init(
        rng_online,
        dummy_input,
        is_training=True,
    )
    target_params, target_state = self.forward.init(
        rng_target,
        dummy_input,
        is_training=True,
    )
    opt_state = self._optimizer(0).init(online_params)
    return pretrain_common.ExperimentState(
        online_params=online_params,
        target_params=target_params,
        opt_state=opt_state,
        online_state=online_state,
        target_state=target_state,
    )

if __name__ == '__main__':
  flags.mark_flag_as_required('config')
  platform.main(PretrainExperiment, sys.argv[1:])


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>me.vilsol</groupId>
    <artifactId>transformer</artifactId>
    <version>0.0.10-SNAPSHOT</version>

    <name>Transformer</name>
    <description>Easy to use world transformation plugin for Bukkit</description>
    <url>https://github.com/Vilsol/Transformer</url>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <repositories>
        <repository>
            <id>spigot-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.8.8-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>me.vilsol</groupId>
            <artifactId>menuengine</artifactId>
            <version>1.4.6</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
package com.sevenbridges.apiclient.impl.resource;

/**
 * This is a {@link Boolean} backed subclass of a {@link Property}.
 */
public class BooleanProperty extends Property<Boolean> {

  public BooleanProperty(String name) {
    super(name, Boolean.class);
  }
}


text:
package main

import (
	"crypto/rand"
	"encoding/hex"
	"time"

	"golang.org/x/crypto/bcrypt"
)

// APIKeyLength determines how large generated API keys are.
const APIKeyLength = 64

// Account is a user account.
type Account struct {
	Name           string `json:"name" bson:"_id"`
	HashedPassword []byte `json:"-" bson:"password"`
	Administrator  bool   `json:"admin" bson:"admin"`

	APIKeys []string `json:"-" bson:"api_keys"`

	CreatedAt int64 `json:"-" bson:"created_at"`
	UpdatedAt int64 `json:"-" bson:"updated_at"`
}

// NewAccount initializes a new Account given a username and password.
func NewAccount(name, password string) (*Account, error) {
	now := time.Now().UnixNano()
	account := &Account{
		Name:      name,
		CreatedAt: now,
		UpdatedAt: now,
	}

	hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return nil, err
	}
	account.HashedPassword = hashed

	if _, err = account.GenerateAPIKey(); err != nil {
		return account, err
	}

	return account, nil
}

// HasPassword returns true if the supplied password is correct for the existing account.
func (account *Account) HasPassword(password string) bool {
	return bcrypt.CompareHashAndPassword(account.HashedPassword, []byte(password)) == nil
}

// GenerateAPIKey securely creates an API key and attaches it to the associated account.
func (account *Account) GenerateAPIKey() (string, error) {
	b := make([]byte, APIKeyLength)
	_, err := rand.Read(b)
	if err != nil {
		return "", err
	}
	key := hex.EncodeToString(b)

	account.APIKeys = append(account.APIKeys, key)

	return key, nil
}


text:
SerialPort SDK (Windows, Linux, MAC OS)

SerialPort SDK is a professional Java serial port SDK. It provides a simple communication interface to connect any serial port devices.

* You can use it to implement or debug serial protocol.
* You can send and capture data.
* You can change communication channel's settings easily including the setting for non-standard baudrate.
* You can write Java code to automate some specific tasks.
* You can perform JavaScript to send command.

SerialPort SDK can be successfully used for:
* Interception and analysis of data transferring between any serial devices and Windows applications.
* Debugging any serial software or hardware.
* Development of serial peripheral hardware.
* Development of serial device drivers.
* Researching the functionality of any third-party software and hardware.
* Implementing, debugging or testing serial protocol between device and device driver.

SerialPort SDK can be used by:
* Software developers
* Hardware engineers
* Programmers
* Testers
* Science technicians
* Lab experts
* University students

This SDK includes the RXTX library.

###Setup
RXTX 2.1-7
-- Please uncompress rxtx-2.1-7-bins-r2.rar

Window32
- rxtx-2.1-7-bins-r2/Windows/i368-mingw32/rxtxSerial.dll copy to system path(e.g. c:\windows\system32\)

Window64
- [mfz-rxtx-2.2-20081207-win-x64](https://bitbucket.org/jlauer/mfz-cdn/downloads/mfz-rxtx-2.2-20081207-win-x64.zip)

Linux32
- rxtx-2.1-7-bins-r2/Linux/i686-unknown-linux-gnu/librxtxSerial.so copy to system path(e.g. /lib)

Linux64
- rxtx-2.1-7-bins-r2/Linux/x86_64-unknown-linux-gnu/librxtxSerial.so copy to system path(e.g. /lib)

Mac
- rxtx-2.1-7-bins-r2/Mac_OS_X/librxtxSerial.jnilib copy to system path

###Wiki
[Link](https://github.com/flylb1/JavaSerialPort/wiki)

### License
JavaSerialPort is licensed under the [Apache 2 License](http://www.apache.org/licenses/LICENSE-2.0.html), which means you can use it for free and without strings attached in commercial or non-commercial projects.

### Class Diagram
![Class Diagram](https://cloud.githubusercontent.com/assets/8717254/6818187/7a203752-d2e6-11e4-9618-9b077ad5461f.png)


text:
package eu.ehealth.controllers;

import java.util.ArrayList;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.util.resource.Labels;
import org.zkoss.zul.Button;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Row;
import org.zkoss.zul.Rows;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;
import eu.ehealth.ErrorDictionary;
import eu.ehealth.SystemDictionary;
import eu.ehealth.ws_client.StorageComponentImpl;
import eu.ehealth.ws_client.xsd.Carer;
import eu.ehealth.ws_client.xsd.Clinician;
import eu.ehealth.ws_client.xsd.Consulter;
import eu.ehealth.ws_client.xsd.GeneralPractitioner;
import eu.ehealth.ws_client.xsd.OperationResult;
import eu.ehealth.ws_client.xsd.Patient;
import eu.ehealth.ws_client.xsd.PersonData;
import eu.ehealth.ws_client.xsd.SocialWorker;
import eu.ehealth.ws_client.xsd.SocioDemographicData;
import eu.ehealth.ws_client.xsd.User;

/**
 * This class handles the creation and the events of the Patient questionnaire.
 *
 * @author Xavi Sarda (Atos Origin)
 */
public class PattientControllerWindow extends SDFormControllerWindow
{

	private static final long serialVersionUID = 3014122995824061686L;
	private CarerListWindowController clist = null;
	private String currentresp = null;
	private SocialWorker currentsocialworker = null;
	private Consulter currentconsulter = null;
	private GeneralPractitioner currentgeneralpracticioner = null;
	private Carer currentcarers = null;

	/**
	 * Default constructor
	 */
	public PattientControllerWindow()
	{
		isNewUser = true;
		this.buildForm(true);
	}

	/**
	 * Constructor to change the create form into an update form
	 *
	 * @param current Patient to be updated
	 */
	public PattientControllerWindow(Patient current)
	{
		isNewUser = false;

		this.currentid = current.getID();
		this.currentdata = current.getPersonData();
		this.currentsd = current.getSDData();
		this.currentresp = current.getResponsibleClinicianID();
		SystemDictionary.webguiLog("TRACE", "Social Worker: " + current.getSocialWorker().getName());
		this.currentsocialworker = current.getSocialWorker();
		SystemDictionary.webguiLog("TRACE", "Consulter: " + current.getConsulterInCharge().getName());
		this.currentconsulter = current.getConsulterInCharge();
		SystemDictionary.webguiLog("TRACE", "General Practicioner: " + current.getGeneralPractitioner().getName());
		this.currentgeneralpracticioner = current.getGeneralPractitioner();
		this.currentcarers = current.getPatientCarer();

		this.buildForm(false);

		this.addPersonFieldsValues();
		this.addAddressFieldsValues();
		this.addCommunicationFieldsValues();
		this.addSocioDemographicDataFieldsValue();
		this.addResponsibleClinicianFieldValues();
		this.addCarerFieldValues();
		this.addSocialWorkerConsulterAndGPFieldsValues();
		this.appendChild(this.createUpdateButton());
		this.getFellow("pat_uname").getParent().setVisible(false);
	}

	/**
	 * Build form instructions to be executed
	 */
	public void buildForm(boolean newPatient)
	{
		this.addErrorBox();
		this.addResponsibleClinicianField();
		this.addPersonFields(newPatient);
		this.addAddressFields();
		this.addCommunicationFields();
		this.addSocioDemographicDataFields();
		this.addCarerField();
		this.addSocialWorkerConsulterAndGPFields();
	}

	/**
	 * Submit function: Used on the view layer to create a new Patient (using
	 * the StorageComponentImpl).
	 *
	 * @return void but saves a new Patient on the server
	 */
	public void sendPatient(boolean newpatient)
	{
		if (!validateForm())
		{
			return;
		}

		OperationResult result = null;
		String resClinic = ((Textbox) getFellow("pat_respo")).getValue();
		String carerId = ((Textbox) getFellow("pat_carid")).getValue();

		// Getting information from form fields
		SocioDemographicData sdData = this.getSocioDemographicData();
		PersonData personData = this.getPersonData();
		SocialWorker socialw = this.getSocialWorkerData();
		Consulter consulter = this.getConsulterData();
		GeneralPractitioner gralprac = this.getGeneralPracticionerData();
		try
		{
			StorageComponentImpl proxy = SystemDictionary.getSCProxy();
			Session ses = Sessions.getCurrent();
			String id = (String) ses.getAttribute("userid");
			Carer car2set = proxy.getCarer(carerId, id);
			SystemDictionary.webguiLog("DEBUG", "Social worker: " + socialw.getName());
			SystemDictionary.webguiLog("DEBUG", "Consulter: " + consulter.getName());
			SystemDictionary.webguiLog("DEBUG", "General practicioner: " + gralprac.getName());

			Patient patient = new Patient("", personData, sdData, resClinic, socialw, consulter, gralprac, car2set);

			if (newpatient)
			{
				result = proxy.createPatient(patient, id);
				SystemDictionary.webguiLog("INFO", "Patient ID: " + result.getCode());
				String username = this.getUsername();

				User user = createNewUser(SystemDictionary.USERTYPE_PATIENT, result.getCode(), username);
				result = proxy.createUser(user);
				if (!result.getDescription().equals("ok"))
				{
					SystemDictionary.webguiLog("TRACE", "Error creating user");
					Window win = (Window) getFellow("internalformerror");
					((Label) win.getFellow("errorlbl")).setValue("Username not valid");
					getFellow("internalformerror").setVisible(true);
					SystemDictionary.webguiLog("TRACE", "Deleting Patient...");
					OperationResult newresult = proxy.deletePatient(user.getPersonID(), id);
					SystemDictionary.webguiLog("TRACE", "Delete Patient result: " + newresult.getCode());
					return;
				}
				Executions.getCurrent().sendRedirect("/patients/index.zul");
			}
			else
			{
				patient.setID(this.currentid);
				result = proxy.updatePatient(patient, id);
				Executions.getCurrent().sendRedirect("/patients/index.zul");
			}
		}
		catch (Exception e)
		{
			ErrorDictionary.redirectWithError("/carers/?error=" + ErrorDictionary.UNKOW_ERROR);
		}
	}

	/**
	 * Creates a modal window to select a primary carer for the patient
	 *
	 * @throws InterruptedException
	 */
	public void createDialog() throws InterruptedException
	{
		if (this.clist == null)
		{
			this.clist = new CarerListWindowController(this);
			this.appendChild(this.clist);
			this.clist.doModal();
		}
		else
		{
			this.clist.doModal();
		}
	}

	/**
	 * This method creates a clinician list for the patient form. It is also in
	 * charge of attaching it to the form and showing it in a modal mode
	 *
	 * @throws InterruptedException
	 */
	public void createClinicianDialog() throws InterruptedException
	{
		if (this.getFellowIfAny("rclinlistwin") == null)
		{
			ClinicianListForPatients respolist =
					(ClinicianListForPatients) Executions.getCurrent().createComponents("/patients/clinlist.zul", this, null);
			respolist.doModal();
		}
	}

	/**
	 * This method is used to set Carer form fields with information from the
	 * modal dialog fields
	 *
	 * @param carerID
	 * @param carerName
	 */
	public void setCarer(String carerID, String carerName)
	{
		((Textbox) this.getFellow("pat_carid")).setValue(carerID);
		((Textbox) this.getFellow("pat_carname")).setValue(carerName);
	}

	/**
	 * This method is used to set responsible clinician form fields with
	 * information from the modal dialog fields
	 *
	 * @param clinID Id of the responsible clinician
	 * @param clinName Name of the responsible clinician
	 */
	public void setResponsibleClinician(String clinID, String clinName)
	{
		((Textbox) this.getFellow("pat_respo")).setValue(clinID);
		((Textbox) this.getFellow("pat_respo_lbl")).setValue(clinName);
	}

	/**
	 * Protected function to add a responsible clinician field to the window.
	 */
	protected void addResponsibleClinicianField()
	{
		String respo = Labels.getLabel("patients.form.responsible");

		ArrayList<SimpleFieldData> rowsA = new ArrayList<SimpleFieldData>();
		rowsA.add(new SimpleFieldData(respo, "pat_respo_lbl"));

		Grid pgrid = new Grid();
		pgrid.setSclass("grid");
		this.appendColumns(pgrid);

		Rows rows = new Rows();

		Row rowhidf = new Row();
		Label lbl_ins = new Label(respo);
		rowhidf.appendChild(lbl_ins);
		Hbox hbox1 = new Hbox();
		Textbox tbox1 = new Textbox();
		tbox1.setId("pat_respo_lbl");
		tbox1.setReadonly(true);
		tbox1.addEventListener("onClick", new EventListener() {
			public void onEvent(Event arg0) throws Exception
			{
				createClinicianDialog();
			}
		});

		Textbox tbox2 = new Textbox();
		tbox2.setVisible(false);
		tbox2.setId("pat_respo");

		hbox1.appendChild(tbox1);
		hbox1.appendChild(tbox2);
		rowhidf.appendChild(hbox1);
		rows.appendChild(rowhidf);

		pgrid.appendChild(rows);
		this.appendChild(pgrid);
	}

	/**
	 * This method sets the responsible clinician values when updating a form
	 */
	protected void addResponsibleClinicianFieldValues()
	{
		String id = (String) Sessions.getCurrent().getAttribute("userid");
		StorageComponentImpl proxy = new StorageComponentImpl();
		try
		{
			Clinician clinician = proxy.getClinician(this.currentresp, id);
			((Textbox) getFellow("pat_respo")).setValue(this.currentresp);
			((Textbox) getFellow("pat_respo_lbl")).setValue(clinician.toString());
		}
		catch (Exception re)
		{
			((Textbox) getFellow("pat_respo_lbl")).setValue("Not available");
		}
	}

	/**
	 * This method appends a carer field to the window. Button will open a modal
	 * dialog to select a carer
	 *
	 * @see CarerListWindowController
	 */
	protected void addCarerField()
	{
		String carertitle = Labels.getLabel("patients.carer.title");
		String carerlabel = Labels.getLabel("patients.carer.label");

		Grid pgrid = new Grid();
		pgrid.setSclass("grid");
		this.appendColumns(pgrid);

		Rows rows = new Rows();

		this.appendSubFormTitleRow(carertitle, rows);

		Row row = new Row();
		Label lab = new Label();
		lab.setValue(carerlabel);
		row.appendChild(lab);

		Hbox hbox01 = new Hbox();

		Textbox tbox = new Textbox();
		tbox.setId("pat_carname");
		tbox.setReadonly(true);

		Textbox tbox2 = new Textbox();
		tbox2.setId("pat_carid");
		tbox2.setVisible(false);
		tbox2.setReadonly(true);

		tbox.addEventListener("onClick", new EventListener() {
			public void onEvent(Event arg0) throws Exception
			{
				createDialog();
			}
		});

		hbox01.appendChild(tbox);
		hbox01.appendChild(tbox2);
		row.appendChild(hbox01);

		rows.appendChild(row);

		pgrid.appendChild(rows);
		this.appendChild(pgrid);
	}

	/**
	 * This method sets the carer values when updating a patient
	 */
	protected void addCarerFieldValues()
	{
		((Textbox) getFellow("pat_carid")).setValue(this.currentcarers.getID());
		((Textbox) getFellow("pat_carname")).setValue(
				this.currentcarers.getPersonData().getName() + ", " + this.currentcarers.getPersonData().getSurname());
	}

	/**
	 * This method adds the social worker, consulter and general practicioner
	 * fields in the form
	 */
	protected void addSocialWorkerConsulterAndGPFields()
	{
		Grid pgrid1 = new Grid();
		Grid pgrid2 = new Grid();
		Grid pgrid3 = new Grid();
		pgrid1.setSclass("grid");
		pgrid2.setSclass("grid");
		pgrid3.setSclass("grid");
		this.appendColumns(pgrid1);
		this.appendColumns(pgrid2);
		this.appendColumns(pgrid3);

		Rows rows1 = new Rows();
		Rows rows2 = new Rows();
		Rows rows3 = new Rows();

		this.appendSubFormTitleRow("Social Workrer Info", rows1);
		this.appendSubFormTitleRow("Consulter Info", rows2);
		this.appendSubFormTitleRow("General Practicioner Info", rows3);

		ArrayList<SimpleFieldData> rowsA = new ArrayList<SimpleFieldData>();
		rowsA.add(new SimpleFieldData("Name", "pat_swname"));
		rowsA.add(new SimpleFieldData("E-mail", "pat_swmail"));
		rowsA.add(new SimpleFieldData("Phone", "pat_swphone"));

		ArrayList<SimpleFieldData> rowsB = new ArrayList<SimpleFieldData>();
		rowsB.add(new SimpleFieldData("Name", "pat_consname"));
		rowsB.add(new SimpleFieldData("E-mail", "pat_consmail"));
		rowsB.add(new SimpleFieldData("Phone", "pat_consphone"));

		ArrayList<SimpleFieldData> rowsC = new ArrayList<SimpleFieldData>();
		rowsC.add(new SimpleFieldData("Name", "pat_gpname"));
		rowsC.add(new SimpleFieldData("E-mail", "pat_gpmail"));
		rowsC.add(new SimpleFieldData("Phone", "pat_gpphone"));

		this.appendTextboxFields(rowsA, rows1);
		this.appendTextboxFields(rowsB, rows2);
		this.appendTextboxFields(rowsC, rows3);

		pgrid1.appendChild(rows1);
		pgrid2.appendChild(rows2);
		pgrid3.appendChild(rows3);
		this.appendChild(pgrid1);
		this.appendChild(pgrid2);
		this.appendChild(pgrid3);
	}

	/**
	 * This method adds the social worker, consulter and general practicioner
	 * values when updating a patient
	 */
	protected void addSocialWorkerConsulterAndGPFieldsValues()
	{
		SystemDictionary.webguiLog("DEBUG", "this.currentsocialworker.getName()");
		((Textbox) getFellow("pat_swname")).setValue(this.currentsocialworker.getName());
		((Textbox) getFellow("pat_swmail")).setValue(this.currentsocialworker.getEmail());
		((Textbox) getFellow("pat_swphone")).setValue(this.currentsocialworker.getPhone());
		SystemDictionary.webguiLog("DEBUG", "this.currentconsulter.getName()");
		((Textbox) getFellow("pat_consname")).setValue(this.currentconsulter.getName());
		((Textbox) getFellow("pat_consmail")).setValue(this.currentconsulter.getEmail());
		((Textbox) getFellow("pat_consphone")).setValue(this.currentconsulter.getPhone());
		SystemDictionary.webguiLog("DEBUG", "this.currentgeneralpracticioner.getName()");
		((Textbox) getFellow("pat_gpname")).setValue(this.currentgeneralpracticioner.getName());
		((Textbox) getFellow("pat_gpmail")).setValue(this.currentgeneralpracticioner.getEmail());
		((Textbox) getFellow("pat_gpphone")).setValue(this.currentgeneralpracticioner.getPhone());
	}

	/**
	 * Method to retrieve a SocialWorker from the form
	 *
	 * @return SocialWorker defined on the patient form
	 */
	protected SocialWorker getSocialWorkerData()
	{
		String name = ((Textbox) getFellow("pat_swname")).getValue();
		String mail = ((Textbox) getFellow("pat_swmail")).getValue();
		String phone = ((Textbox) getFellow("pat_swphone")).getValue();
		return new SocialWorker(name, phone, mail);
	}

	/**
	 * Method to retrieve the consulter from the form
	 *
	 * @return Consulter defined on the patient form
	 */
	protected Consulter getConsulterData()
	{
		String name = ((Textbox) getFellow("pat_consname")).getValue();
		String mail = ((Textbox) getFellow("pat_consmail")).getValue();
		String phone = ((Textbox) getFellow("pat_consphone")).getValue();
		return new Consulter(name, phone, mail);
	}

	/**
	 * Method to retrieve a GeneralPracticioner from the form
	 *
	 * @return GeneralPracticioner defined on the patient form
	 */
	protected GeneralPractitioner getGeneralPracticionerData()
	{
		String name = ((Textbox) getFellow("pat_gpname")).getValue();
		String mail = ((Textbox) getFellow("pat_gpmail")).getValue();
		String phone = ((Textbox) getFellow("pat_gpphone")).getValue();
		return new GeneralPractitioner(name, phone, mail);
	}

	/**
	 * Method in charge of creating update button for patients updates
	 * operations
	 *
	 * @return Button to be added to the form
	 */
	public Button createUpdateButton()
	{
		Button btn = new Button();
		String text = Labels.getLabel("patients.update.title");
		btn.setLabel(text);
		btn.addEventListener("onClick", new EventListener() {
			public void onEvent(Event arg0) throws Exception
			{
				sendPatient(false);
			}
		});

		return btn;
	}

	/**
	 *
	 * @return
	 */
	private boolean validateForm() {
		try {
			// check common fields
			if (!validateFormCommonFields())
				return false;

			if (((Textbox) getFellow("pat_respo")).getValue() == null || ((Textbox) getFellow("pat_respo")).getValue().trim().equals(""))
			{
				Window win = (Window) getFellow("internalformerror");
				((Label) win.getFellow("errorlbl")).setValue("You must select some clinician");
				getFellow("internalformerror").setVisible(true);

				return false;
			}
			else if (((Textbox) getFellow("pat_carid")).getValue() == null || ((Textbox) getFellow("pat_carid")).getValue().trim().equals(""))
			{
				Window win = (Window) getFellow("internalformerror");
				((Label) win.getFellow("errorlbl")).setValue("You must select some carer");
				getFellow("internalformerror").setVisible(true);

				return false;
			}

			return true;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			SystemDictionary.webguiLog("ERROR", e.getMessage());

			String errorMsj = e.getMessage();
			try {
				Window win = (Window) getFellow("internalformerror");
				((Label) win.getFellow("errorlbl")).setValue(errorMsj);
				getFellow("internalformerror").setVisible(true);
				((Label) win.getFellow("errorlbl")).setFocus(true);
				return false;
			}
			catch (Exception ex) {}

			return false;
		}
	}

}


text:
Twig Bridge
===========

The Twig bridge provides integration for [Twig](https://twig.symfony.com/) with
various Symfony components.

Resources
---------

  * [Contributing](https://symfony.com/doc/current/contributing/index.html)
  * [Report issues](https://github.com/symfony/symfony/issues) and
    [send Pull Requests](https://github.com/symfony/symfony/pulls)
    in the [main Symfony repository](https://github.com/symfony/symfony)


text:
/// <reference path="../types/types.ts"/>

/* @ngInject */
function appConfig(
  $urlRouterProvider: ng.ui.IUrlRouterProvider,
  $locationProvider: ng.ILocationProvider
) {
  $urlRouterProvider.otherwise("/");
}

angular
  .module("kcalc", [
    "templates",
    "kcalc.calc",
    "highcharts-ng",
    "ui.router.state"
  ])
  .config(appConfig);


text:
#ifndef PHYSXBODYDESC_H
#define PHYSXBODYDESC_H

#include "pandabase.h"
#include "luse.h"

#include "physxEnums.h"
#include "physx_includes.h"

/**
 * Descriptor for the optional rigid body dynamic state of PhysxActor.
 */
class EXPCL_PANDAPHYSX PhysxBodyDesc : public PhysxEnums {

PUBLISHED:
  INLINE PhysxBodyDesc();
  INLINE ~PhysxBodyDesc();

  INLINE void set_to_default();
  INLINE bool is_valid() const;

  void set_mass(float mass);
  void set_linear_damping(float damping);
  void set_angular_damping(float damping);
  void set_linear_velocity(const LVector3f &velocity);
  void set_angular_velocity(const LVector3f &velocity);
  void set_max_angular_velocity(float maximum);
  void set_sleep_linear_velocity(float velocity);
  void set_sleep_angular_velocity(float velocity);
  void set_solver_iteration_count(unsigned int count);
  void set_sleep_energy_threshold(float threshold);
  void set_sleep_damping(float damping);
  void set_mass_local_mat(const LMatrix4f &mat);
  void set_mass_space_inertia(const LVector3f &inertia);
  void set_flag(PhysxBodyFlag flag, bool value);
  void set_ccd_motion_threshold(float threshold);
  void set_wake_up_counter(float value);
  void set_contact_report_threshold(float threshold);

  float get_mass() const;
  float get_linear_damping() const;
  float get_angular_damping() const;
  LVector3f get_linear_velocity() const;
  LVector3f get_angular_velocity() const;
  float get_max_angular_velocity() const;
  float get_sleep_linear_velocity() const;
  float get_sleep_angular_velocity() const;
  unsigned int get_solver_iteration_count() const;
  float get_sleep_energy_threshold() const;
  float get_sleep_damping() const;
  LMatrix4f get_mass_local_mat() const;
  LVector3f get_mass_space_inertia() const;
  bool get_flag(PhysxBodyFlag flag) const;
  float get_ccd_motion_threshold() const;
  float get_wake_up_counter() const;
  float get_contact_report_threshold() const;

public:
  NxBodyDesc _desc;
};

#include "physxBodyDesc.I"

#endif // PHYSXBODYDESC_H


text:
"""
    werkzeug.testsuite
    ~~~~~~~~~~~~~~~~~~

    Contains all test Werkzeug tests.

    :copyright: (c) 2011 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""

from __future__ import with_statement

import unittest
from werkzeug.utils import import_string, find_modules

def iter_suites(package):
    """Yields all testsuites."""
    for module in find_modules(package, include_packages=True):
        mod = import_string(module)
        if hasattr(mod, 'suite'):
            yield mod.suite()

def find_all_tests(suite):
    """Yields all the tests and their names from a given suite."""
    suites = [suite]
    while suites:
        s = suites.pop()
        try:
            suites.extend(s)
        except TypeError:
            yield s, '%s.%s.%s' % (
                s.__class__.__module__,
                s.__class__.__name__,
                s._testMethodName
            )

class WerkzeugTestCase(unittest.TestCase):
    """Baseclass for all the tests that Werkzeug uses.  Use these
    methods for testing instead of the camelcased ones in the
    baseclass for consistency.
    """

    def setup(self):
        pass

    def teardown(self):
        pass

    def setUp(self):
        self.setup()

    def tearDown(self):
        unittest.TestCase.tearDown(self)
        self.teardown()

    def assert_equal(self, x, y):
        return self.assertEqual(x, y)

    def assert_not_equal(self, x, y):
        return self.assertNotEqual(x, y)

    def assert_raises(self, exc_type, callable=None, *args, **kwargs):
        catcher = _ExceptionCatcher(self, exc_type)
        if callable is None:
            return catcher
        with catcher:
            callable(*args, **kwargs)

class _ExceptionCatcher(object):

    def __init__(self, test_case, exc_type):
        self.test_case = test_case
        self.exc_type = exc_type

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, tb):
        exception_name = self.exc_type.__name__
        if exc_type is None:
            self.test_case.fail('Expected exception of type %r' %
                                exception_name)
        elif not issubclass(exc_type, self.exc_type):
            raise exc_type, exc_value, tb
        return True

class BetterLoader(unittest.TestLoader):
    """A nicer loader that solves two problems.  First of all we are setting
    up tests from different sources and we're doing this programmatically
    which breaks the default loading logic so this is required anyways.
    Secondly this loader has a nicer interpolation for test names than the
    default one so you can just do ``run-tests.py ViewTestCase`` and it
    will work.
    """

    def getRootSuite(self):
        return suite()

    def loadTestsFromName(self, name, module=None):
        root = self.getRootSuite()
        if name == 'suite':
            return root

        all_tests = []
        for testcase, testname in find_all_tests(root):
            if testname == name or \
               testname.endswith('.' + name) or \
               ('.' + name + '.') in testname or \
               testname.startswith(name + '.'):
                all_tests.append(testcase)

        if not all_tests:
            raise LookupError('could not find test case for "%s"' % name)

        if len(all_tests) == 1:
            return all_tests[0]
        rv = unittest.TestSuite()
        for test in all_tests:
            rv.addTest(test)
        return rv

def suite():
    """A testsuite that has all the Flask tests.  You can use this
    function to integrate the Flask tests into your own testsuite
    in case you want to test that monkeypatches to Flask do not
    break it.
    """
    suite = unittest.TestSuite()
    for other_suite in iter_suites(__name__):
        suite.addTest(other_suite)
    return suite

def main():
    """Runs the testsuite as command line application."""
    try:
        unittest.main(testLoader=BetterLoader(), defaultTest='suite')
    except Exception, e:
        print 'Error: %s' % e


text:
"""Support for BMW car locks with BMW ConnectedDrive."""
import logging

from bimmer_connected.state import LockState

from homeassistant.components.lock import LockEntity
from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED

from . import DOMAIN as BMW_DOMAIN, BMWConnectedDriveBaseEntity
from .const import CONF_ACCOUNT, DATA_ENTRIES

DOOR_LOCK_STATE = "door_lock_state"
_LOGGER = logging.getLogger(__name__)

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the BMW ConnectedDrive binary sensors from config entry."""
    account = hass.data[BMW_DOMAIN][DATA_ENTRIES][config_entry.entry_id][CONF_ACCOUNT]
    entities = []

    if not account.read_only:
        for vehicle in account.account.vehicles:
            device = BMWLock(account, vehicle, "lock", "BMW lock")
            entities.append(device)
    async_add_entities(entities, True)

class BMWLock(BMWConnectedDriveBaseEntity, LockEntity):
    """Representation of a BMW vehicle lock."""

    def __init__(self, account, vehicle, attribute: str, sensor_name):
        """Initialize the lock."""
        super().__init__(account, vehicle)

        self._attribute = attribute
        self._name = f"{self._vehicle.name} {self._attribute}"
        self._unique_id = f"{self._vehicle.vin}-{self._attribute}"
        self._sensor_name = sensor_name
        self._state = None
        self.door_lock_state_available = (
            DOOR_LOCK_STATE in self._vehicle.available_attributes
        )

    @property
    def unique_id(self):
        """Return the unique ID of the lock."""
        return self._unique_id

    @property
    def name(self):
        """Return the name of the lock."""
        return self._name

    @property
    def extra_state_attributes(self):
        """Return the state attributes of the lock."""
        vehicle_state = self._vehicle.state
        result = self._attrs.copy()

        if self.door_lock_state_available:
            result["door_lock_state"] = vehicle_state.door_lock_state.value
            result["last_update_reason"] = vehicle_state.last_update_reason
        return result

    @property
    def is_locked(self):
        """Return true if lock is locked."""
        if self.door_lock_state_available:
            result = self._state == STATE_LOCKED
        else:
            result = None
        return result

    def lock(self, **kwargs):
        """Lock the car."""
        _LOGGER.debug("%s: locking doors", self._vehicle.name)
        # Optimistic state set here because it takes some time before the
        # update callback response
        self._state = STATE_LOCKED
        self.schedule_update_ha_state()
        self._vehicle.remote_services.trigger_remote_door_lock()

    def unlock(self, **kwargs):
        """Unlock the car."""
        _LOGGER.debug("%s: unlocking doors", self._vehicle.name)
        # Optimistic state set here because it takes some time before the
        # update callback response
        self._state = STATE_UNLOCKED
        self.schedule_update_ha_state()
        self._vehicle.remote_services.trigger_remote_door_unlock()

    def update(self):
        """Update state of the lock."""
        _LOGGER.debug("%s: updating data for %s", self._vehicle.name, self._attribute)
        vehicle_state = self._vehicle.state

        # Possible values: LOCKED, SECURED, SELECTIVE_LOCKED, UNLOCKED
        self._state = (
            STATE_LOCKED
            if vehicle_state.door_lock_state in [LockState.LOCKED, LockState.SECURED]
            else STATE_UNLOCKED
        )


text:
.. _str: https://docs.python.org/2/library/stdtypes.html

.. _vSphere API 4.0: ../../vim/version.rst#vimversionversion5

.. _vmodl.DynamicData: ../../vmodl/DynamicData.rst

.. _vmodl.KeyAnyValue: ../../vmodl/KeyAnyValue.rst

.. _vim.LicenseManager.LicenseInfo: ../../vim/LicenseManager/LicenseInfo.rst

vim.LicenseAssignmentManager.LicenseAssignment
==============================================

:extends: vmodl.DynamicData_
:since: `vSphere API 4.0`_

Attributes:
    entityId (`str`_):

       Id for the entity
    scope (`str`_, optional):

       Scope of the entityId
    entityDisplayName (`str`_, optional):

       Display name of the entity
    assignedLicense (`vim.LicenseManager.LicenseInfo`_):

       License assigned to the entity
    properties ([`vmodl.KeyAnyValue`_], optional):

       Additional properties associated with this assignment Some of the properties are: "inUseFeatures" -- Features in the license key that are being used by the entity "ProductName" -- Name of the entity. Should match the product name of the assigned license. "ProductVersion" -- Version of the entity. Should match the product version of the assigned license. "Evaluation" -- EvaluationInfo object representing the evaluation left for the entity.


text:
import {Component, OnInit, OnDestroy, AfterViewInit, ElementRef} from "@angular/core";
import {Router} from "@angular/router";
import {FileEncryptionService} from "../service/file-encryption.service";
import {CryptConfiguringService} from "./service/crypt-configuring.service";
import {FormControl, FormGroup, FormBuilder, Validators} from "@angular/forms";

@Component({
  selector: 'crypt-configuring',
  templateUrl: './crypt-configuring.component.html',
  providers: []
})
export class CryptConfiguringComponent implements OnInit, OnDestroy, AfterViewInit {
  public manualConfiguringForm: FormGroup;
  public keyStorageConfiguringForm: FormGroup;
  public algorithm: FormControl;
  public typeOfForm: string = 'manual';
  public manualPassword: FormControl;
  public manualSalt: FormControl;

  constructor(private _router: Router,
              private _fb: FormBuilder,
              private _el: ElementRef,
              public fileEncryptionService: FileEncryptionService,
              public cryptConfiguringService: CryptConfiguringService) {
  }

  ngOnInit() {
    this.initForm();
  }

  ngAfterViewInit() {
    $('div.file-info').popup();
    $('.menu .item').tab();
    $('.ui.dropdown').dropdown();
  }

  ngOnDestroy() {

  }

  private initForm() {
    this.algorithm = new FormControl("aes-256-gcm");

    this.manualPassword = new FormControl("", [Validators.required, Validators.minLength(6)]);
    this.manualSalt = new FormControl("", [Validators.required, Validators.minLength(32)]);

    this.manualConfiguringForm = this._fb.group({
      password: this.manualPassword,
      salt: this.manualSalt
    });
  }

  public hidePassword(event) {
    event.stopPropagation();
    let target = this._el.nativeElement.getElementsByClassName('password');
    _.forEach(target, (item) => {
      if(item.getAttribute('type') === 'text') {
        item.setAttribute('type', 'password');
      } else {
        item.setAttribute('type', 'text');
      }
    });
  }

  public generatePassword(event) {
    event.stopPropagation();
    this.manualPassword.patchValue(this.cryptConfiguringService.generatePassword());
  }

  public generateSalt(event) {
    event.stopPropagation();
    this.manualSalt.patchValue(this.cryptConfiguringService.generateSalt());
  }

  public cancel(event) {
    event.stopPropagation();
    this._router.navigate(['file-encryption']);
  }

  public setConfig(event) {
    event.preventDefault();
    event.stopPropagation();
    this.fileEncryptionService.config.algorithm = this.algorithm.value;
    if(this.typeOfForm === 'manual') {
      this.fileEncryptionService.config.password = this.manualConfiguringForm.value.password;
      this.fileEncryptionService.config.salt = this.manualConfiguringForm.value.salt;
    } else {

    }
    this._router.navigate(['file-encryption', 'progress']);
  }
}


text: JiraIssueFieldUpdater can be used to update custom JIRA issue field.


text:
package gobblin.runtime;

/**
 * @deprecated This class has been moved to {@link gobblin.util.limiter.BaseLimiterType}.
 */
@Deprecated
public enum BaseLimiterType {

  /**
   * For {@link RateBasedLimiter}.
   */
  RATE_BASED("rate"),

  /**
   * For {@link TimeBasedLimiter}.
   */
  TIME_BASED("time"),

  /**
   * For {@link CountBasedLimiter}.
   */
  COUNT_BASED("count"),

  /**
   * For {@link PoolBasedLimiter}.
   */
  POOL_BASED("pool");

  private final String name;

  BaseLimiterType(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    return this.name;
  }

  /**
   * Get a {@link BaseLimiterType} for the given name.
   *
   * @param name the given name
   * @return a {@link BaseLimiterType} for the given name
   */
  public static BaseLimiterType forName(String name) {
    if (name.equalsIgnoreCase(RATE_BASED.name)) {
      return RATE_BASED;
    }
    if (name.equalsIgnoreCase(TIME_BASED.name)) {
      return TIME_BASED;
    }
    if (name.equalsIgnoreCase(COUNT_BASED.name)) {
      return COUNT_BASED;
    }
    if (name.equalsIgnoreCase(POOL_BASED.name)) {
      return POOL_BASED;
    }
    throw new IllegalArgumentException("No Limiter implementation available for name: " + name);
  }
}


text:
import mapObj from 'map-obj';

const newObject: Object = mapObj({ foo: 'bar' }, function(key: string, value: any, object: Object) {
  // first element is the new key and second is the new value
  // here we reverse the order
  return [value, key];
});

// $ExpectError
mapObj({a: 1}, (key, value, obj) => { obj.b; });

// $ExpectError
mapObj({a: 1}, (key, value, obj) => { obj.a = 'asdf'; });

// $ExpectError
(mapObj({a: 1}, (key, value, obj) => { return {b: 'asdf'}; }): {[key: string]: number});


text:
Baekjun, HackerRank, etc

## Baekjun
- 1065(한수):
  [Problem](https://www.acmicpc.net/problem/1065),
  (Swift) [Solution](https://github.com/NicholasWon/algorithmStudy/blob/master/Baekjun/1065.swift)
- 1110(더하기 사이클):
  [Problem](https://www.acmicpc.net/problem/1110),
  (Swift) [Solution](https://github.com/NicholasWon/algorithmStudy/blob/master/Baekjun/1110.swift)
- 2231(분해합):
  [Problem](https://www.acmicpc.net/problem/2231),
  (Swift) [Solution](https://github.com/NicholasWon/algorithmStudy/blob/master/Baekjun/2231.swift)
- 2309(일곱 난쟁이):
  [Problem](https://www.acmicpc.net/problem/2309),
  (Swift) [Solution](https://github.com/NicholasWon/algorithmStudy/blob/master/Baekjun/2309.swift)
- 2747(피보나치 수):
  [Problem](https://www.acmicpc.net/problem/2747),
  (Swift) [Solution](https://github.com/NicholasWon/algorithmStudy/blob/master/Baekjun/2747.swift)
- 2839(설탕배달):
  [Problem](https://www.acmicpc.net/problem/2839),
  (Swift) [Solution](https://github.com/NicholasWon/algorithmStudy/blob/master/Baekjun/2839.swift)
- 4673(셀프 넘버):
  [Problem](https://www.acmicpc.net/problem/4673),
  (Swift) [Solution](https://github.com/NicholasWon/algorithmStudy/blob/master/Baekjun/4673.swift)

## HackerRnak
- Solve Me First:
  [Problem](https://www.hackerrank.com/challenges/solve-me-first/problem),
  (Swift) [Solution](https://github.com/NicholasWon/algorithmStudy/blob/master/HackerRank/Solve_Me_First.swift)


text:
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' http://localhost:35729; style-src 'self' 'unsafe-inline';">
    <title>Package-tools</title>
    <link rel="stylesheet" href="main.css"/>
  </head>
  <body>
   <script src="app.js"></script>
  </body>
</html>