text:
package org.jboss.arquillian.persistence.core.configuration;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.config.descriptor.api.ExtensionDef;
import org.jboss.arquillian.persistence.core.exception.PersistenceExtensionInitializationException;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;

/**
 * Fetches persistence-related configuration from arquillian.xml or
 * property file and creates {@see PersistenceConfiguration} instance used
 * during tests execution.
 *
 * @author Bartosz Majsak
 */
public class ConfigurationImporter<T extends Configuration> {

    private static final Logger log = Logger.getLogger(ConfigurationImporter.class.getName());

    private final T configuration;

    public ConfigurationImporter(T configuration) {
        this.configuration = configuration;
    }

    public void loadFromArquillianXml(String arquillianXmlFilename) {
        final InputStream arqXmlStream =
            Thread.currentThread().getContextClassLoader().getResourceAsStream(arquillianXmlFilename);
        final ArquillianDescriptor arquillianDescriptor =
            Descriptors.importAs(ArquillianDescriptor.class).fromStream(arqXmlStream);
        from(arquillianDescriptor);
    }

    public void from(ArquillianDescriptor descriptor) {
        final Map<String, String> extensionProperties =
            extractPropertiesFromDescriptor(configuration.getQualifier(), descriptor);
        createConfiguration(extensionProperties);
    }

    public void loadFromPropertyFile(String propertyFilename) {
        final Properties properties = new Properties();
        InputStream propertiesStream = null;
        try {
            propertiesStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertyFilename);
            properties.load(propertiesStream);
            from(properties);
        } catch (Exception e) {
            throw new PersistenceExtensionInitializationException(
                "Unable to load Arquillian properties in container. Missing file " + propertyFilename, e);
        } finally {
            if (propertiesStream != null) {
                try {
                    propertiesStream.close();
                } catch (IOException e) {
                    throw new PersistenceExtensionInitializationException(
                        "Failed to close the stream for file " + propertyFilename, e);
                }
            }
        }
    }

    public void from(Properties properties) {
        Map<String, String> fieldsWithValues = convertKeys(properties);
        createConfiguration(fieldsWithValues);
    }

    private Map<String, String> convertKeys(Properties properties) {
        final Map<String, String> convertedFieldsWithValues = new HashMap<String, String>();
        for (Entry<Object, Object> property : properties.entrySet()) {
            final String key = String.valueOf(property.getKey());
            final String value = String.valueOf(property.getValue());
            convertedFieldsWithValues.put(convertFromPropertyKey(key), value);
        }
        return convertedFieldsWithValues;
    }

    private String convertFromPropertyKey(String key) {
        key = key.replaceAll(configuration.getPrefix(), "");
        final StringBuilder sb = new StringBuilder();
        for (int i = 0; i < key.length(); i++) {
            char c = key.charAt(i);
            if (c == '.') {
                c = Character.toUpperCase(key.charAt(++i));
            }
            sb.append(c);
        }
        return sb.toString();
    }

    private void createConfiguration(final Map<String, String> fieldsWithValues) {
        final ConfigurationTypeConverter typeConverter = new ConfigurationTypeConverter();
        final Collection<Field> fields = ReflectionHelper.getAccessibleFields(configuration.getClass());

        for (Field field : fields) {
            final String fieldName = field.getName();
            if (fieldsWithValues.containsKey(fieldName)) {
                final String value = fieldsWithValues.get(fieldName);
                fieldsWithValues.remove(fieldName);
                final Class<?> fieldType = field.getType();
                try {
                    final Class<?> boxedFieldType = typeConverter.box(fieldType);
                    final Object convertedValue = typeConverter.convert(value, boxedFieldType);
                    if (convertedValue != null && boxedFieldType.isAssignableFrom(convertedValue.getClass())) {
                        final Method setter =
                            new PropertyDescriptor(fieldName, configuration.getClass()).getWriteMethod();
                        setter.invoke(configuration, convertedValue);
                    }
                } catch (Exception e) {
                    throw new PersistenceExtensionInitializationException("Unable to create persistence configuration.",
                        e);
                }
            }
        }
        if (!fieldsWithValues.keySet().isEmpty()) {
            reportNonExistingFields(fieldsWithValues, fields);
        }
    }

    private void reportNonExistingFields(final Map<String, String> fieldsWithValues, final Collection<Field> fields) {
        String[] knownFields = extractFieldNames(fields);
        log.warning(configuration + " does not support properties provided '" + Arrays.toString(
            fieldsWithValues.keySet().toArray())
            + ". Possible values: " + Arrays.toString(knownFields) + "'. Please revise your arquillian.xml. "
            + "For more details you can refer to the official documentation https://docs.jboss.org/author/display/ARQ/Persistence");
    }

    private Map<String, String> extractPropertiesFromDescriptor(String extensionName, ArquillianDescriptor descriptor) {
        for (ExtensionDef extension : descriptor.getExtensions()) {
            if (extensionName.equals(extension.getExtensionName())) {
                return extension.getExtensionProperties();
            }
        }

        return Collections.emptyMap();
    }

    private String[] extractFieldNames(Collection<Field> fields) {
        final String[] knownFields = new String[fields.size()];
        int index = 0;
        for (Field field : fields) {
            knownFields[index++] = field.getName();
        }
        return knownFields;
    }
}


text:
var util = require('util');
var validators = require('./validators');
exports.defaultError = require('./defaultError');

var ValidatorError = exports.ValidatorError = function(msg) {
    Error.captureStackTrace(this, this);
    this.name = 'ValidatorError';
    this.message = msg;
};
util.inherits(ValidatorError, Error);

var Validator = exports.Validator = function() {}

Validator.prototype.error = function (msg) {
    throw new ValidatorError(msg);
};

Validator.prototype.check = function(str, fail_msg) {
    this.str = (str == null || (isNaN(str) && str.length == undefined)) ? '' : str;
    if (typeof this.str == 'number') {
        this.str += '';
    }
    this.msg = fail_msg;
    this._errors = this._errors || [];
    return this;
}

for (var key in validators) {
    if (validators.hasOwnProperty(key)) {
        (function (key) {
            Validator.prototype[key] = function() {
                var args = Array.prototype.slice.call(arguments);
                args.unshift(this.str);
                if(!validators[key].apply(this, args)) {
                    var msg = this.msg || exports.defaultError[key];
                    if (typeof msg === 'string') {
                        args.forEach(function(arg, i) { msg = msg.replace('%'+i, arg); });
                    }
                    return this.error(msg);
                }
                return this;
            };
        })(key);
    }
}

//Create some aliases - may help code readability
Validator.prototype.validate = Validator.prototype.check;
Validator.prototype.assert = Validator.prototype.check;
Validator.prototype.isFloat = Validator.prototype.isDecimal;
Validator.prototype.is = Validator.prototype.regex;
Validator.prototype.not = Validator.prototype.notRegex;

redpajama_set_name: RedPajamaGithub


text:
package com.fitbur.playground.hk2.aop.impl;

import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;

/**
 *
 * @author Sharmarke Aden
 */
@Retention(RUNTIME)
@Target({METHOD, CONSTRUCTOR})
public @interface Access {

    String value() default "";

}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="Widget.CardContent" parent="android:Widget">
        <item name="android:paddingLeft">16dp</item>
        <item name="android:paddingRight">16dp</item>
        <item name="android:paddingTop">24dp</item>
        <item name="android:paddingBottom">24dp</item>
        <item name="android:orientation">vertical</item>
    </style>

    <style name="SizeSpecificCollapsingToolbarLayout">
        <item name="layout_scrollFlags">scroll|exitUntilCollapsed</item>
        <item name="contentScrim">?attr/colorPrimary</item>
    </style>
    <style name="MenuButtonsStyle">
        <item name="fab_size">mini</item>
        <item name="fab_showAnimation">@anim/jump_from_down</item>
        <item name="fab_hideAnimation">@anim/jump_to_down</item>
        <item name="fab_shadowColor">#444</item>
        <item name="fab_colorNormal">#FFB805</item>
        <item name="fab_colorPressed">#F2AB00</item>
        <item name="fab_colorRipple">#D99200</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>


text:
<doctype html>

    <title>User Report</title>

Dropbox usage report for account: {{ accountName }}

Select user to show report for: <select required="true" v-model="selected" v-on:change="showBarChart(interactions[selected].interactions)">
          <option disabled="disabled" selected="true">Please select a user</option>
          <option v-for="user in users" v-bind:value="user.id">
            {{user.name}}
          </option>
        </select>


text:
package com.sun.jdmk.remote.cascading.proxy;

// java import
import java.util.Set;
import java.util.List;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Collections;
import java.util.ArrayList;
import java.io.IOException;

import java.lang.reflect.UndeclaredThrowableException;

// jdmk import
import javax.management.QueryExp;
import javax.management.ObjectName;
import javax.management.MBeanServer;
import javax.management.MBeanRegistration;
import javax.management.MBeanRegistrationException;
import javax.management.RuntimeMBeanException;
import javax.management.DynamicMBean;
import javax.management.MBeanServerNotification;
import javax.management.MBeanServerConnection;
import javax.management.ObjectInstance;
import javax.management.Notification;
import javax.management.MBeanNotificationInfo;
import javax.management.NotificationEmitter;
import javax.management.NotificationBroadcaster;
import javax.management.NotificationListener;
import javax.management.NotificationFilter;
import javax.management.NotificationBroadcasterSupport;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.ListenerNotFoundException;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanException;
import javax.management.ReflectionException;
import javax.management.Attribute;
import javax.management.InvalidAttributeValueException;
import javax.management.AttributeList;
import javax.management.MBeanInfo;
import javax.management.remote.JMXConnectionNotification;

import com.sun.jdmk.remote.cascading.CascadingAgent;
import com.sun.jdmk.remote.cascading.CascadingAgentMBean;
import com.sun.jdmk.remote.cascading.MBeanServerConnectionFactory;
import com.sun.jdmk.defaults.Utils;

/**
 * This class is used to proxy an MBean residing in a source
 * <tt>MBeanServer</tt>. Connections to that source <tt>MBeanServer</tt>
 * are obtained through an {@link MBeanServerConnectionFactory}.
 * The <tt>CascadingProxy</tt> is a {@link DynamicMBean} that forwards all
 * the calls it receive to a source MBean, residing in a source
 * <tt>MBeanServer</tt>. The <tt>CascadingProxy</tt> also makes it possible
 * for  {@link NotificationListener Notification Listeners} to register
 * for notifications emitted by the source MBeans.
 *
 * @since Java DMK 5.1
 **/
public class CascadingProxy
    implements DynamicMBean, MBeanRegistration, NotificationEmitter {

    /**
     * Creates a new <tt>CascadingProxy</tt>.
     * @param sourceMBeanName The <tt>ObjectName</tt> of the source MBean.
     * @param mbscf An <tt>MBeanServerConnectionFactory</tt> from which
     *        connections with the <tt>MBeanServer</tt> containing the
     *        source MBean can be obtained.
     *        The <tt>CascadingProxy</tt> will call {@link
     *        MBeanServerConnectionFactory#getMBeanServerConnection()
     *        mbscf.getMBeanServerConnection()} every time it needs to access
     *        the subagent.
     **/
    public CascadingProxy(ObjectName sourceMBeanName,
			  MBeanServerConnectionFactory mbscf) {
	connectionFactory = mbscf;
	source = sourceMBeanName;
	targetName = null;
	listenerList = Collections.EMPTY_LIST;
    }

    /**
     * Called by the <tt>CascadingProxy</tt> when an <tt>IOException</tt>
     * exception is caught while trying to talk with the source MBean.
     * Subclasses who need a more specific handling of such exceptions
     * (e.g. logging etc) can implement it by redefining this method.
     * The returned <tt>RuntimeException</tt> will be thrown by the calling
     * method.
     * @param x The <tt>IOException</tt> exception.
     * @param method The name of the method in which the exception
     *        <var>x</var> was caught.
     * @return An {@link UndeclaredThrowableException} wrapping the
     *         undeclared checked exception <var>x</var>.
     **/
    RuntimeException handleIOException(IOException x,
						 String method) {
	final RuntimeException r = new UndeclaredThrowableException(x);
	return r;
    }

    /**
     * Called by the <tt>CascadingProxy</tt> when an
     * <tt>InstanceNotFoundException</tt> exception is caught while
     * trying to talk with the source MBean.
     * Subclasses who need a more specific handling of such exceptions
     * (e.g. logging etc) can implement it by redefining this method.
     * The returned <tt>RuntimeException</tt> will be thrown by the calling
     * method.
     * @param x The <tt>InstanceNotFoundException</tt> exception.
     * @param method The name of the method in which the exception
     *        <var>x</var> was caught.
     * @return An {@link UndeclaredThrowableException} wrapping the
     *         undeclared checked exception <var>x</var>.
     **/
    RuntimeException handleInstanceNotFoundException(
						InstanceNotFoundException x,
						String method) {
	final RuntimeException r = new UndeclaredThrowableException(x);
	return r;
    }

    /**
     * Called by the <tt>CascadingProxy</tt> when an undeclared checked
     * exception is caught while trying to talk with the source MBean.
     * This method is not called for either <tt>IOException</tt>
     * (see {@link #handleIOException handleIOException(x,method)})
     * or <tt>InstanceNotFoundException</tt>
     * (see {@link #handleInstanceNotFoundException
     * handleInstanceNotFoundException(x,method)}).
     * Subclasses who need a more specific handling of such exceptions
     * (e.g. logging etc) can implement it by redefining this method.
     * The returned <tt>RuntimeException</tt> will be thrown by the calling
     * method.
     * @param x The undeclared checked exception.
     * @param method The name of the method in which the exception
     *        <var>x</var> was caught.
     * @return An {@link UndeclaredThrowableException} wrapping the
     *         undeclared checked exception <var>x</var>.
     **/
    RuntimeException handleCheckedException(Exception x, String method) {
	final RuntimeException r = new UndeclaredThrowableException(x);
	return r;
    }

    /**
     * Returns an <tt>MBeanServerConnection</tt> obtained from the underlying
     * {@link MBeanServerConnectionFactory}. This method is called
     * every time the cascading proxy needs to forward an operation
     * to the source MBean. Subclasses should not implement connection
     * caching by redefining this method. Connection caching, if needed,
     * should be delegated to the underlying
     * {@link MBeanServerConnectionFactory}.
     * @exception IOException if no <tt>MBeanServerConnection</tt> can be
     *            obtained.
     * @return An <tt>MBeanServerConnection</tt> to the <tt>MBeanServer</tt>
     *         in which the source MBean resides.
     **/
    private MBeanServerConnection connection()
	throws IOException {
	final MBeanServerConnection c =
	    connectionFactory.getMBeanServerConnection();
	if (c == null)
	    throw new IOException("MBeanServerConnection unavailable");
	return c;
    }

    /**
     * Obtain the value of a specific attribute from the source MBean.
     *
     * @param attribute The name of the attribute to be retrieved
     *
     * @return  The value of the attribute retrieved.
     *
     * @exception AttributeNotFoundException
     * @exception MBeanException
     *    Wraps a <tt>java.lang.Exception</tt> thrown by the MBean's getter.
     * @exception ReflectionException  Wraps a <tt>java.lang.Exception</tt>
     *    thrown while trying to invoke the getter.
     * @exception UndeclaredThrowableException if an
     *         <tt>InstanceNotFoundException</tt> or an <tt>IOException</tt>
     *        is raised while trying to forward the request to the source
     *        MBean.
     *
     * @see #setAttribute
     * @see DynamicMBean#getAttribute
     */
    public Object getAttribute(String attribute)
	throws AttributeNotFoundException,
	       MBeanException, ReflectionException {
	try {
	    return connection().getAttribute(source, attribute);
	} catch (IOException x) {
	    throw handleIOException(x,"getAttribute");
	} catch (InstanceNotFoundException x) {
	    throw handleInstanceNotFoundException(x,"getAttribute");
	}
    }

    /**
     * Set the value of a specific attribute on the source MBean.
     *
     * @param attribute The identification of the attribute to
     * be set and  the value it is to be set to.
     *
     * @exception AttributeNotFoundException
     * @exception InvalidAttributeValueException
     * @exception MBeanException Wraps a <tt>java.lang.Exception</tt> thrown
     *            by the MBean's setter.
     * @exception ReflectionException Wraps a <tt>java.lang.Exception</tt>
     *            thrown while trying to invoke the MBean's setter.
     * @exception UndeclaredThrowableException if an
     *         <tt>InstanceNotFoundException</tt> or an <tt>IOException</tt>
     *        is raised while trying to forward the request to the source
     *        MBean.
     *
     * @see #getAttribute
     * @see DynamicMBean#setAttribute
     */
    public void setAttribute(Attribute attribute)
	throws AttributeNotFoundException,
	       InvalidAttributeValueException, MBeanException,
	       ReflectionException {
	try {
	    connection().setAttribute(source, attribute);
	} catch (IOException x) {
	    throw handleIOException(x,"setAttribute");
	} catch (InstanceNotFoundException x) {
	    throw handleInstanceNotFoundException(x,"setAttribute");
	}
    }

    /**
     * Get the values of several attributes from the source MBean.
     *
     * @param attributes A list of the attributes to be retrieved.
     *
     * @return  The list of attributes retrieved.
     *
     * @exception UndeclaredThrowableException if an
     *        <tt>InstanceNotFoundException</tt>, an <tt>IOException</tt>,
     *        or a <tt>ReflectionException</tt>
     *        is raised while trying to forward the request to the source
     *        MBean.
     *
     * @see #setAttributes
     * @see DynamicMBean#getAttributes
     */
    public AttributeList getAttributes(String[] attributes) {
	try {
	    return connection().getAttributes(source, attributes);
	} catch (IOException x) {
	    throw handleIOException(x,"getAttributes");
	} catch (InstanceNotFoundException x) {
	    throw handleInstanceNotFoundException(x,"getAttributes");
	} catch (RuntimeException r) {
	    throw r;
	} catch (Exception x) {
	    throw handleCheckedException(x,"getAttributes");
	}
    }

    /**
     * Sets the values of several attributes in the source MBean.
     *
     * @param attributes A list of attributes: The identification of the
     * attributes to be set and  the values they are to be set to.
     *
     * @return  The list of attributes that were set, with their new values.
     *
     * @exception UndeclaredThrowableException if an
     *        <tt>InstanceNotFoundException</tt>, an <tt>IOException</tt>,
     *        or a <tt>ReflectionException</tt>
     *        is raised while trying to forward the request to the source
     *        MBean.
     *
     * @see #getAttributes
     * @see DynamicMBean#setAttributes
     */
    public AttributeList setAttributes(AttributeList attributes) {
	try {
	    return connection().setAttributes(source, attributes);
	} catch (IOException x) {
	    throw handleIOException(x,"setAttributes");
	} catch (InstanceNotFoundException x) {
	    throw handleInstanceNotFoundException(x,"setAttributes");
	} catch (RuntimeException r) {
	    throw r;
	} catch (Exception x) {
	    throw handleCheckedException(x,"setAttributes");
	}
    }

    /**
     * Allows an action to be invoked on the source MBean.
     *
     * @param actionName The name of the action to be invoked.
     * @param params An array containing the parameters to be set when
     *        the action is invoked.
     * @param signature An array containing the signature of the action.
     *
     * @return The object returned by the action, which represents the
     *         result of invoking the action on the MBean specified.
     *
     * @exception MBeanException  Wraps a <tt>java.lang.Exception</tt>
     *            thrown by the MBean's invoked method.
     * @exception ReflectionException  Wraps a <tt>java.lang.Exception</tt>
     *            thrown while trying to invoke the method
     * @exception UndeclaredThrowableException if an
     *         <tt>InstanceNotFoundException</tt> or an <tt>IOException</tt>
     *        is raised while trying to forward the request to the source
     *        MBean.
     *
     * @see DynamicMBean#invoke
     */
    public Object invoke(String actionName,Object params[],String signature[])
	throws MBeanException, ReflectionException {
	try {
	    return connection().invoke(source, actionName, params,
				       signature);
	} catch (IOException x) {
	    throw handleIOException(x,"invoke");
	} catch (InstanceNotFoundException x) {
	    throw handleInstanceNotFoundException(x,"invoke");
	}
    }

    /**
     * Returns the <tt>MBeanInfo</tt> of the source MBean.
     * This <tt>MBeanInfo</tt> is not cached by the proxy, which could
     * be considered as a suboptimal implementation for those
     * implementations in which it is known that the source
     * <tt>MBeanInfo</tt> will not change over time.
     *
Subclasses may therefore wish to redefine this method in order
     * to cache the returned <tt>MBeanInfo</tt>.
     * @return The source MBean <tt>MBeanInfo</tt>.
     * @exception UndeclaredThrowableException if an
     *        <tt>InstanceNotFoundException</tt>, an <tt>IOException</tt>,
     *        a <tt>ReflectionException</tt>, or an
     *        <tt>IntrospectionException</tt>
     *        is raised while trying to forward the request to the source
     *        MBean.
     **/
    public MBeanInfo getMBeanInfo() {
	try {
	    return connection().getMBeanInfo(source);
	} catch (IOException x) {
	    throw handleIOException(x,"getMBeanInfo");
	} catch (InstanceNotFoundException x) {
	    throw handleInstanceNotFoundException(x,"getMBeanInfo");
	} catch (RuntimeException r) {
	    throw r;
	} catch (Exception x) {
	    throw handleCheckedException(x,"getMBeanInfo");
	}
    }

    /**
     * Allows the MBean to perform any operations it needs before
     * being registered in the MBean server. This default implementation
     * simply checks that the given <var>name</var> is not null, and cache
     * it in the <tt>CascadingProxy</tt>. Once the <tt>CascadingProxy</tt>
     * is registered, its <tt>ObjectName</tt> can be later obtained by
     * calling {@link #getTargetName()}.
     *
     * @param server The MBean server in which the MBean will be registered.
     *
     * @param name The object name of the MBean. If <var>name</var>
     *        this method throws an <tt>IllegalArgumentException</tt>.
     *
     * @return The given <var>name</var>.
     *
     * @exception IllegalArgumentException if the parameter <var>name</var>
     *         is <tt>null</tt>
     * @see MBeanRegistration#preRegister
     */
    public ObjectName preRegister(MBeanServer server,
				  ObjectName name)
	throws java.lang.Exception {
	if (name == null)
	    throw new IllegalArgumentException("Illegal ObjectName: null");

	synchronized (this) { targetName = name ; }
	return targetName;
    }

    /**
     * Allows the MBean to perform any operations needed after having been
     * registered in the MBean server or after the registration has failed.
     * This default implementation does nothing.
     *
     * @param registrationDone Indicates whether or not the MBean has
     * been successfully registered in the MBean server. The value
     * false means that the registration phase has failed.
     * @see MBeanRegistration#postRegister
     */
    public void postRegister(Boolean registrationDone) {
    }

    /**
     * Allows the MBean to perform any operations it needs before
     * being unregistered by the MBean server.
     * This default implementation does nothing.
     *
     * @exception java.lang.Exception This exception will be caught by
     * the MBean server and re-thrown as an {@link
     * MBeanRegistrationException} or a {@link RuntimeMBeanException}.
     * @see MBeanRegistration#preDeregister
     */
    public void preDeregister() throws java.lang.Exception {
    }

    /**
     * Allows the MBean to perform any operations needed after having been
     * unregistered in the MBean server.
     * This default implementation does nothing.
     */
    public void postDeregister() { }

    /**
     * The <tt>ObjectName</tt> of the source MBean, as passed to this
     * Object's constructor.
     **/
    public final ObjectName getSourceMBeanName() {
	return source;
    }

    /**
     * The <tt>ObjectName</tt> of this cascading proxy. May be null if this
     * object has not been registered in an <tt>MBeanServer</tt> yet.
     * Otherwise, it is the <tt>ObjectName</tt> obtained from the
     * {@link #preRegister} method.
     **/
    public synchronized ObjectName getTargetName() {
	return targetName;
    }

    /**
     *
Returns an array indicating, for each notification this
     * MBean may send, the name of the Java class of the notification
     * and the notification type.

     *
     *
This method returns the notification information present
     *    in the source MBean's <tt>MBeanInfo</tt> - if any.
     *    Otherwise, it returns an empty array.

     *
     *
It is not illegal for the MBean to send notifications not
     * described in this array.  However, some clients of the MBean
     * server may depend on the array being complete for their correct
     * functioning.

     *
     * @return the array of possible notifications.
     * @see NotificationBroadcaster#getNotificationInfo
     */
    public MBeanNotificationInfo[] getNotificationInfo() {
	try {
	    final MBeanNotificationInfo[] info =
	    getMBeanInfo().getNotifications();
	    if (info == null) return new MBeanNotificationInfo[0];
	    else return info;
	} catch(Exception x) {
	    // OK.
	}
	return  new MBeanNotificationInfo[0];
    }

    /*
     * The following is a "close clone" of NotificationBroadcasterSupport,
     * that handles an internal list of ListenerWrapper.
     * The sole purpose of the listener wrapper is to modify the
     * source of the emitted notification.
     */

    /**
     * Adds a listener to the source MBean.
     *
     * @param listener The listener object which will handle the
     * notifications emitted by the broadcaster.
     * @param filter The filter object. If filter is null, no
     * filtering will be performed before handling notifications.
     * @param handback An opaque object to be sent back to the
     * listener when a notification is emitted. This object cannot be
     * used by the Notification broadcaster object. It should be
     * resent unchanged with the notification to the listener.
     *
     * @exception IllegalArgumentException Listener parameter is null.
     * @exception UndeclaredThrowableException if an
     *         <tt>InstanceNotFoundException</tt> or an <tt>IOException</tt>
     *        is raised while trying to forward the request to the source
     *        MBean.
     *
     * @see #removeNotificationListener
     * @see NotificationBroadcaster#addNotificationListener
     */
    public void addNotificationListener(NotificationListener listener,
					NotificationFilter filter,
					Object handback) {

        if (listener == null) {
            throw new IllegalArgumentException ("Listener can't be null") ;
        }

	/* Adding a new listener takes O(n) time where n is the number
	   of existing listeners.  If you have a very large number of
	   listeners performance could degrade.  That's a fairly
	   surprising configuration, and it is hard to avoid this
	   behavior while still retaining the property that the
	   listenerList is not synchronized while notifications are
	   being sent through it.  If this becomes a problem, a
	   possible solution would be a multiple-readers single-writer
	   setup, so any number of sendNotification() calls could run
	   concurrently but they would exclude an
	   add/removeNotificationListener.  A simpler but less
	   efficient solution would be to clone the listener list
	   every time a notification is sent.  */
	synchronized (this) {
	    ListenerWrapper w =
		new ListenerWrapper(listener, filter, handback);
	    try {
		connection().addNotificationListener(source,w,filter,
						     handback);
		List newList = new ArrayList(listenerList.size() + 1);
		newList.addAll(listenerList);
		newList.add(w);
		listenerList = newList;
	    } catch (IOException x) {
		throw handleIOException(x,"addNotificationListener");
	    } catch (InstanceNotFoundException x) {
		throw handleInstanceNotFoundException(x,
                      "addNotificationListener");
	    }
	}
    }

    /**
     * Removes a listener from the source MBean.  If the listener
     * has been registered with different handback objects or
     * notification filters, all entries corresponding to the listener
     * will be removed.
     *
     * @param listener A listener that was previously added to this
     * MBean.
     *
     * @exception ListenerNotFoundException The listener is not
     * registered with the MBean.
     * @exception UndeclaredThrowableException if an
     *         <tt>InstanceNotFoundException</tt> or an <tt>IOException</tt>
     *        is raised while trying to forward the request to the source
     *        MBean.
     *
     * @see #addNotificationListener
     * @see NotificationEmitter#removeNotificationListener
     */
    public void removeNotificationListener(NotificationListener listener)
        throws ListenerNotFoundException {

	synchronized (this) {
	    List newList = new ArrayList(listenerList);
	    /* We scan the list of listeners in reverse order because
	       in forward order we would have to repeat the loop with
	       the same index after a remove.  */
	    for (int i=newList.size()-1; i>=0; i--) {
		ListenerWrapper li = (ListenerWrapper)newList.get(i);

		if (li.listener == listener) {
		    try {
			connection().removeNotificationListener(source,li);
			newList.remove(i);
		    } catch (IOException x) {
			throw handleIOException(x,
			      "removeNotificationListener");
		    } catch (InstanceNotFoundException x) {
			throw handleInstanceNotFoundException(x,
                              "removeNotificationListener");
		    }
		}
	    }
	    if (newList.size() == listenerList.size())
	       throw new ListenerNotFoundException("Listener not registered");
	    listenerList = newList;
	}
    }

    /**
     *
Removes a listener from the source MBean.  The MBean must have a
     * listener that exactly matches the given listener,
     * filter, and handback parameters.  If
     * there is more than one such listener, only one is removed.

     *
     *
The filter and handback parameters
     * may be null if and only if they are null in a listener to be
     * removed.

     *
     * @param listener A listener that was previously added to this
     * MBean.
     * @param filter The filter that was specified when the listener
     * was added.
     * @param handback The handback that was specified when the listener was
     * added.
     *
     * @exception ListenerNotFoundException The listener is not
     * registered with the MBean, or it is not registered with the
     * given filter and handback.
     * @exception UndeclaredThrowableException if an
     *         <tt>InstanceNotFoundException</tt> or an <tt>IOException</tt>
     *        is raised while trying to forward the request to the source
     *        MBean.
     *
     * @see NotificationEmitter#removeNotificationListener
     */
    public void removeNotificationListener(NotificationListener listener,
					   NotificationFilter filter,
					   Object handback)
	    throws ListenerNotFoundException {

	boolean found = false;

	synchronized (this) {
	    List newList = new ArrayList(listenerList);
	    final int size = newList.size();
	    for (int i = 0; i < size; i++) {
		ListenerWrapper li = (ListenerWrapper) newList.get(i);

		if (li.listener == listener) {
		    found = true;
		    if (li.filter == filter
			&& li.handback == handback) {
			try {
			    connection().removeNotificationListener(source,
								    li,
								    filter,
								    handback);
			    newList.remove(i);
			} catch (IOException x) {
			    throw handleIOException(x,
				  "removeNotificationListener");
			} catch (InstanceNotFoundException x) {
			    throw handleInstanceNotFoundException(x,
                                  "removeNotificationListener");
			}
			newList.remove(i);
			listenerList = newList;
			return;
		    }
		}
	    }
	}

	if (found) {
	    /* We found this listener, but not with the given filter
	     * and handback.  A more informative exception message may
	     * make debugging easier.  */
	    throw new ListenerNotFoundException("Listener not registered " +
						"with this filter and " +
						"handback");
	} else {
	    throw new ListenerNotFoundException("Listener not registered");
	}
    }

    /**
     * Returns the <tt>MBeanServerConnectionFactory</tt>, as passed to this
     * object's constructor.
     **/
    public final MBeanServerConnectionFactory getConnectionFactory() {
	return connectionFactory;
    }

    /**
     * ListenerWrapper wraps a client NotificationListener - in order
     * to translate ObjectNames in the received notification before
     * forwarding it to the wrapped listener.
     **/
    private final class ListenerWrapper implements  NotificationListener {
	public final NotificationListener listener;
	final NotificationFilter filter;
	final Object handback;

	public ListenerWrapper(NotificationListener listener,
			    NotificationFilter   filter,
			    Object               handback) {
	    this.listener = listener;
	    this.filter = filter;
	    this.handback = handback;
	}
	public void handleNotification(Notification notif,
				       Object handback) {

	    // Only change the source if it's the object name of the
	    // source object.
	    //
	    listener.handleNotification(translate(notif),handback);
	}
    }

    /**
     * Translate the source <tt>ObjectName</tt> into this
     * <tt>CascadingProxy</tt>'s <tt>ObjectName</tt>.
     * This implementation simply substitute the notification source
     * by this <tt>CascadingProxy</tt>'s <tt>ObjectName</tt>, iff the
     * source is the <tt>ObjectName</tt> of the source MBean.
     * @return <var>notif</var>, after the source has been possibly
     *         substituted.
     **/
    protected Notification translate(Notification notif) {
	notif.setSource(makeSource(notif.getSource()));
	return notif;
    }

    private Object makeSource(Object source) {
	if (source != null && !source.equals(getSourceMBeanName()))
	    return source;
	final ObjectName name = getTargetName();
	if (name == null) return CascadingProxy.this;
	return name;
    }

    /**
     * Current list of listeners, a List of ListenerInfo.  The object
     * referenced by this field is never modified.  Instead, the field
     * is set to a new object when a listener is added or removed,
     * within a synchronized(this).  In this way, there is no need to
     * synchronize when traversing the list to send a notification to
     * the listeners in it.  That avoids potential deadlocks if the
     * listeners end up depending on other threads that are themselves
     * accessing this <tt>NotificationBroadcasterSupport</tt>.
     */
    private List listenerList;

    /**
     * The underlying MBeanServerConnectionFactory
     **/
    private final MBeanServerConnectionFactory connectionFactory;

    /**
     * The <tt>ObjectName</tt> of the source MBean.
     **/
    private final ObjectName source;

    /**
     * The <tt>ObjectName</tt> of the cascading proxy (this object's name).
     **/
    private         ObjectName targetName;
}


text:
#include "mbed_assert.h"
#include "analogout_api.h"

#if DEVICE_ANALOGOUT

#include "cmsis.h"
#include "pinmap.h"
#include "mbed_error.h"

#define DAC_RANGE (0xFFF) // 12 bits

static const PinMap PinMap_DAC[] = {
    {PA_4, DAC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // DAC1_OUT1
    {PA_5, DAC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // DAC1_OUT2
    {NC,   NC,    0}
};

static DAC_HandleTypeDef DacHandle;

void analogout_init(dac_t *obj, PinName pin)
{
    DAC_ChannelConfTypeDef sConfig;

    // Get the peripheral name from the pin and assign it to the object
    obj->dac = (DACName)pinmap_peripheral(pin, PinMap_DAC);
    MBED_ASSERT(obj->dac != (DACName)NC);

    // Configure GPIO
    pinmap_pinout(pin, PinMap_DAC);

    // Save the pin for future use
    obj->pin = pin;

    // Enable DAC clock
    __DAC1_CLK_ENABLE();

    // Configure DAC
    DacHandle.Instance = (DAC_TypeDef *)(obj->dac);

    sConfig.DAC_Trigger      = DAC_TRIGGER_NONE;
    sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_DISABLE;

    HAL_DAC_ConfigChannel(&DacHandle, &sConfig, DAC_CHANNEL_1);

    analogout_write_u16(obj, 0);
}

void analogout_free(dac_t *obj)
{
    // Reset DAC and disable clock
    __DAC1_FORCE_RESET();
    __DAC1_RELEASE_RESET();
    __DAC1_CLK_DISABLE();

    // Configure GPIO
    pin_function(obj->pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0));
}

static inline void dac_write(dac_t *obj, uint16_t value)
{
    HAL_DAC_SetValue(&DacHandle, DAC_CHANNEL_1, DAC_ALIGN_12B_R, value);
    HAL_DAC_Start(&DacHandle, DAC_CHANNEL_1);
}

static inline int dac_read(dac_t *obj)
{
    return (int)HAL_DAC_GetValue(&DacHandle, DAC_CHANNEL_1);
}

void analogout_write(dac_t *obj, float value)
{
    if (value < 0.0f) {
        dac_write(obj, 0); // Min value
    } else if (value > 1.0f) {
        dac_write(obj, (uint16_t)DAC_RANGE); // Max value
    } else {
        dac_write(obj, (uint16_t)(value * (float)DAC_RANGE));
    }
}

void analogout_write_u16(dac_t *obj, uint16_t value)
{
    if (value > (uint16_t)DAC_RANGE) {
        dac_write(obj, (uint16_t)DAC_RANGE); // Max value
    } else {
        dac_write(obj, value);
    }
}

float analogout_read(dac_t *obj)
{
    uint32_t value = dac_read(obj);
    return (float)((float)value * (1.0f / (float)DAC_RANGE));
}

uint16_t analogout_read_u16(dac_t *obj)
{
    return (uint16_t)dac_read(obj);
}

#endif // DEVICE_ANALOGOUT


text:
// Copyright 2015 ALRUX Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*
Package errors provides extended error handling.

When you need to retain more information about an error message than a single string allows, just substitute this package for the one in the standard library.

The `New` function still accepts a single string as argument, so no code will be broken. Where you need to include additional information, you can provide it to `New` in a `Desc` structure instead of the string, or you can add it to the error message using one of its setter methods.

The additional information can be used for smarter error handling and logging:
- `Level` differentiates between warnings, regular errors, panics converted to errors, and fatal errors;
- `Code` allows custom classification and prioritizing, by using ranges or bit-level masks;
- `Info` offers a store for arbitrary data and messages, besides the main error `Text`; the special string "debug.stack", if present as an element in the Info slice, is automatically replaced by a stack trace at the point the error message has been created.

*/
package errors

import (
	"fmt"
	"runtime"
)

// Error represents an error descriptor capable of storing more detailed
// information than possible with the standard errors package. It ensures that
// any implementation also satisfies the built-in `error` interface.
type Error interface {
	error
	Level() int8
	SetLevel(int8) Error
	Code() int
	SetCode(int) Error
	Text() string
	SetText(string) Error
	Info() []string
	AddInfo(...string) Error
	Log(Logger) Error
}

// Desc provides a means to convey detailed error information to New.
type Desc struct {
	Level int8
	Code  int
	Text  string
	Info  []string
}

// errorMessage stores information about one error occurrence. Pointers to it
// implement the Error interface.
type errorMessage struct {
	level int8
	code  int
	text  string
	info  []string
}

// New returns an error descriptor containing the given information. It accepts
// either a string or a Desc structure (or a pointer to either).
//
// It is a drop-in replacement for the corresponding function from the standard package.
func New(desc interface{}) Error {
	switch desc := desc.(type) {
	case string:
		return &errorMessage{level: ERROR, text: desc}
	case *string:
		return &errorMessage{level: ERROR, text: *desc}
	case Desc:
		return newFromE(&desc)
	case *Desc:
		return newFromE(desc)
	}
	return newFromE(&Desc{
		Code: ERR_NEW_ARG,
		Text: fmt.Sprintf("unsupported error descriptor type %T", desc),
		Info: []string{
			fmt.Sprintf("%T", desc),
			"debug.stack",
		},
	})
}

func newFromE(desc *Desc) Error {
	return (&errorMessage{
		level: ERROR,
		code:  desc.Code,
		text:  desc.Text,
	}).addInfo(3, desc.Info...).SetLevel(desc.Level)
}

// Log sends the error to the provided log, using the appropriate
// logging function: FATAL conditions are logged using Fatal(), PANIC using
// Panic(), and anything else using Print().
func (em *errorMessage) Log(log Logger) Error {
	switch em.level {
	case FATAL:
		log.Fatal(em)
	case PANIC:
		log.Panic(em)
	default:
		log.Print(em)
	}
	return em
}

// Level returns the error level.
func (em *errorMessage) Level() int8 {
	return em.level
}

// SetLevel sets the error level.
func (em *errorMessage) SetLevel(l int8) Error {
	if l >= minLevel && l <= maxLevel {
		em.level = l
	}
	return em
}

// Code returns the error code.
func (em *errorMessage) Code() int {
	return em.code
}

// SetCode sets the error code.
func (em *errorMessage) SetCode(c int) Error {
	em.code = c
	return em
}

// Text returns the error text.
func (em *errorMessage) Text() string {
	return em.text
}

// SetText sets the error text.
func (em *errorMessage) SetText(t string) Error {
	em.text = t
	return em
}

// Info returns the error info.
func (em *errorMessage) Info() []string {
	return em.info
}

// addInfo adds (more) error info.
func (em *errorMessage) addInfo(calldepth int, s ...string) Error {
	for i, line := range s {
		if line == "debug.stack" {
			calldepth *= 2
			buffer := make([]byte, 4096)
			buffer = buffer[:runtime.Stack(buffer, true)]
			var p1, p2, l int
			for j, c := range buffer {
				if c == 10 {
					if l == 0 {
						p1 = j + 1
					} else if l == calldepth {
						p2 = j + 1
						break
					}
					l++
				}
			}
			if p2 > 0 {
				s[i] = string(buffer[:p1]) + string(buffer[p2:])
			} else {
				s[i] = string(buffer)
			}
			break
		}
	}
	em.info = append(em.info, s...)
	return em
}

// AddInfo adds (more) error info.
func (em *errorMessage) AddInfo(s ...string) Error {
	return em.addInfo(2, s...)
}

// Error returns a text containing the error message and code;
// it is useful for satisfying the `error` interface.
func (em *errorMessage) Error() string {
	if em.code != 0 {
		return em.text + fmt.Sprintf(" (code: 0x%04x)", em.code)
	}
	return em.text
}


text:
<?php

error_reporting(E_ALL & ~E_NOTICE & ~8192);

define('THIS_SCRIPT', 'upgrade_360b2.php');
define('VERSION', '3.6.0 Beta 2');
define('PREV_VERSION', '3.6.0 Beta 1');

$phrasegroups = array();
$specialtemplates = array();

// #############################################################################
// require the code that makes it all work...
require_once('./upgradecore.php');

// #############################################################################
// welcome step
if ($vbulletin->GPC['step'] == 'welcome')
{
	if ($vbulletin->options['templateversion'] == PREV_VERSION)
	{
		echo "

";
		echo "$vbphrase[upgrade_start_message]";
		echo "

";
	}
	else
	{
		echo "

";
		echo "$vbphrase[upgrade_wrong_version]";
		echo "

";
		print_upgrade_footer();
	}
}

// #############################################################################
if ($vbulletin->GPC['step'] == 1)
{
	if (!$upgrade->field_exists('adminmessage', 'adminmessageid'))
	{
		require_once(DIR . '/includes/class_bitfield_builder.php');
		vB_Bitfield_Builder::save($db);

		// Make sure to zero out permissions from possible past usage
		$newperms = array(
			'genericpermissions' => array(
				$vbulletin->bf_ugp_genericpermissions['cangivearbinfraction'],
		));

		foreach ($newperms AS $permission => $permissions)
		{
			$upgrade->run_query(
				sprintf($vbphrase['update_table'], TABLE_PREFIX . "usergroup"),
				"UPDATE " . TABLE_PREFIX . "usergroup SET $permission = $permission & ~" . (array_sum($permissions))
			);
		}
		// give arbitrary infraction perms to admins
		$upgrade->run_query(
			sprintf($vbphrase['update_table'], TABLE_PREFIX . "usergroup"),
			"UPDATE " . TABLE_PREFIX . "usergroup
				SET genericpermissions = genericpermissions | " . $vbulletin->bf_ugp_genericpermissions['cangivearbinfraction'] ."
			WHERE adminpermissions & " . $vbulletin->bf_ugp_adminpermissions['cancontrolpanel']
		);
	}

	$upgrade->run_query(
		sprintf($vbphrase['create_table'], TABLE_PREFIX . "adminmessage"),
		"CREATE TABLE " . TABLE_PREFIX . "adminmessage (
			adminmessageid INT UNSIGNED NOT NULL AUTO_INCREMENT,
			varname varchar(250) NOT NULL DEFAULT '',
			dismissable SMALLINT UNSIGNED NOT NULL DEFAULT '0',
			script varchar(50) NOT NULL DEFAULT '',
			action varchar(20) NOT NULL DEFAULT '',
			execurl mediumtext NOT NULL,
			method enum('get','post') NOT NULL DEFAULT 'post',
			dateline INT UNSIGNED NOT NULL DEFAULT '0',
			status enum('undone','done','dismissed') NOT NULL default 'undone',
			statususerid INT UNSIGNED NOT NULL DEFAULT '0',
			PRIMARY KEY (adminmessageid),
			KEY script_action (script, action)
		)",
		MYSQL_ERROR_TABLE_EXISTS
	);

	$upgrade->execute(false);

	$rows = $db->query_first("SELECT COUNT(*) AS count FROM " . TABLE_PREFIX . "adminmessage");
	if ($rows['count'] == 0)
	{
		$upgrade->run_query(
			sprintf($vbphrase['update_table'], TABLE_PREFIX . "adminmessage"),
			"INSERT INTO " . TABLE_PREFIX . "adminmessage
				(varname, dismissable, script, action, execurl, method, dateline, status)
			VALUES
				('after_upgrade_36_update_counters', 1, 'misc.php', 'updatethread', 'misc.php?do=updatethread', 'get', " . TIMENOW . ", 'undone')
			"
		);
	}

	$upgrade->add_index(
		sprintf($upgrade_phrases['upgrade_300b3.php']['altering_x_table'], 'adminlog', 1, 1),
		'adminlog',
		'script_action',
		array('script', 'action')
	);

	$upgrade->run_query(
		sprintf($upgradecore_phrases['altering_x_table'], 'attachment', 1, 1),
		"ALTER TABLE " . TABLE_PREFIX . "attachment CHANGE extension extension VARCHAR(20) BINARY NOT NULL DEFAULT ''"
	);

	$upgrade->run_query(
		sprintf($upgradecore_phrases['altering_x_table'], 'attachmenttype', 1, 1),
		"ALTER TABLE " . TABLE_PREFIX . "attachmenttype CHANGE extension extension VARCHAR(20) BINARY NOT NULL DEFAULT ''"
	);

	$upgrade->run_query(
		sprintf($upgradecore_phrases['altering_x_table'], 'attachmentpermission', 1, 1),
		"ALTER TABLE " . TABLE_PREFIX . "attachmentpermission CHANGE extension extension VARCHAR(20) BINARY NOT NULL DEFAULT ''"
	);

	// Make sure we have sigpicrevision (missing from beta 1 mysql-schema)
	$upgrade->add_field(
		sprintf($upgrade_phrases['upgrade_300b3.php']['altering_x_table'], 'user', 1, 1),
		'user',
		'sigpicrevision',
		'int',
		FIELD_DEFAULTS
	);

	$upgrade->add_field(
		sprintf($upgrade_phrases['upgrade_300b3.php']['altering_x_table'], 'infraction', 1, 1),
		'infraction',
		'customreason',
		'varchar',
		array('length' => 255, 'attributes' => FIELD_DEFAULTS)
	);

	$upgrade->execute();
}

// #############################################################################
// FINAL step (notice the SCRIPTCOMPLETE define)
if ($vbulletin->GPC['step'] == 2)
{
	// tell log_upgrade_step() that the script is done
	define('SCRIPTCOMPLETE', true);
}

// #############################################################################

print_next_step();
print_upgrade_footer();

/*======================================================================*\
|| ####################################################################
|| #
|| # CVS: $RCSfile$ - $Revision: 31381 $
|| ####################################################################
\*======================================================================*/
?>


text:
class Browser;
class GURL;
class Profile;
namespace content {
class BrowserContext;
}

namespace views {
class View;
class WebView;
}  // namespace views

class ProfilePicker {
 public:
  using BrowserOpenedCallback = base::OnceCallback<void(Browser*)>;
#if BUILDFLAG(IS_CHROMEOS_LACROS)
  using FirstRunExitedCallback =
      base::OnceCallback<void(bool finished, BrowserOpenedCallback callback)>;
#endif

  // Only work when passed as the argument 'on_select_profile_target_url' to
  // ProfilePicker::Show.
  static const char kTaskManagerUrl[];

  // An entry point that triggers the profile picker window to open.
  // These values are persisted to logs. Entries should not be renumbered and
  // numeric values should never be reused.
  enum class EntryPoint {
    kOnStartup = 0,
    kProfileMenuManageProfiles = 1,
    kProfileMenuAddNewProfile = 2,
    kOpenNewWindowAfterProfileDeletion = 3,
    // A new session was sarted while Chrome was already running (e.g. by
    // clicking on the tray icon on Windows).
    kNewSessionOnExistingProcess = 4,
    kProfileLocked = 5,
    kUnableToCreateBrowser = 6,
    kBackgroundModeManager = 7,
    // May only be used on lacros, opens an account picker, listing all accounts
    // that are not used in the provided profile, yet.
    kLacrosSelectAvailableAccount = 8,
    // May only be used on lacros, opens a first run experience (provided no
    // policies prevent it) to let the user opt in to sync, etc. for the primary
    // profile.
    kLacrosPrimaryProfileFirstRun = 9,
    kMaxValue = kLacrosPrimaryProfileFirstRun,
  };

  class Params final {
   public:
    // Basic constructors and operators.
    ~Params();
    Params(Params&&);
    Params& operator=(Params&&);

    Params(const Params&) = delete;
    Params& operator=(const Params&) = delete;

    // Basic constructor. Specifies only the entry point, and all other
    // parameters have default values. Use specialized entry points when they
    // are available (e.g. `ForBackgroundManager()`).
    static Params FromEntryPoint(EntryPoint entry_point);

    // Builds parameter with the `kBackgroundModeManager` entry point. Allows
    // specifying extra parameters.
    static Params ForBackgroundManager(
        const GURL& on_select_profile_target_url);

    EntryPoint entry_point() const { return entry_point_; }

    // Returns the path to the profile to use to display the Web UI.
    const base::FilePath& profile_path() const { return profile_path_; }

    // May be non-empty only for the `kBackgroundModeManager` entry point.
    const GURL& on_select_profile_target_url() const {
      return on_select_profile_target_url_;
    }

#if BUILDFLAG(IS_CHROMEOS_LACROS)
    // Builds parameter with the `kLacrosSelectAvailableAccount` entry point.
    //
    // `profile_path` specifies the profile that should be used to render
    // the profile picker. If `profile_path` matches the current value
    // for an existing picker, then `Show()` reactivates the existing picker.
    // Otherwise `Show()` hides the current window and shows a new one.
    //
    // `account_selected_callback` is called when the user picks an account on
    // the account selection screen. If the user closes the window, it is called
    // with the empty string. If the user clicks "Use another account" and
    // starts an OS account addition, this callback is passed to
    // `ShowAddAccountDialog()` and will be called with its result.
    static Params ForLacrosSelectAvailableAccount(
        const base::FilePath& profile_path,
        base::OnceCallback<void(const std::string&)> account_selected_callback);

    // Builds parameter with the `kLacrosPrimaryProfileFirstRun` entry point.
    //
    // `first_run_exited_callback` is called when the first run experience is
    // exited, with `true` if the user actually finished it, or `false` if it
    // was exited early.
    static Params ForLacrosPrimaryProfileFirstRun(
        FirstRunExitedCallback first_run_exited_callback);

    // Calls `account_selected_callback_`. See
    // `ForLacrosSelectAvailableAccount()` for more details.
    void NotifyAccountSelected(const std::string& gaia_id);

    // Calls `first_run_exited_callback_`, forwarding `callback`. See
    // `ForLacrosPrimaryProfileFirstRun()` for more details.
    //
    // Does not take any argument for `finished` as we assume that calling it
    // indicates that the flow is actually finished, not just an early exit.
    // The callback is called with `false` through the param's destructor
    // instead.
    void NotifyFirstRunFinished(BrowserOpenedCallback callback);
#endif

    // Returns the URL to load as initial content for the profile picker. If an
    // empty URL is returned, the profile picker should not be shown until
    // another explicit call with a non-empty URL given to the view
    // (see `ProfilePickerView::ShowScreen()` for example)
    GURL GetInitialURL();

   private:
    // Constructor is private, use static functions instead.
    explicit Params(EntryPoint entry_point, const base::FilePath& profile_path);

    EntryPoint entry_point_ = EntryPoint::kOnStartup;
    GURL on_select_profile_target_url_;
    base::FilePath profile_path_;
#if BUILDFLAG(IS_CHROMEOS_LACROS)
    base::OnceCallback<void(const std::string&)> account_selected_callback_;
    FirstRunExitedCallback first_run_exited_callback_;
#endif
  };

  // Values for the ProfilePickerOnStartupAvailability policy. Should not be
  // re-numbered. See components/policy/resources/policy_templates.json for
  // documentation.
  enum class AvailabilityOnStartup {
    kEnabled = 0,
    kDisabled = 1,
    kForced = 2,
    kMax = kForced
  };

  ProfilePicker(const ProfilePicker&) = delete;
  ProfilePicker& operator=(const ProfilePicker&) = delete;

  // Shows the Profile picker for the given `Params` or re-activates an existing
  // one (see `Params::ForAccountSelecAvailableAccount()` for details on
  // re-activation). When reactivated, the displayed page is not updated.
  static void Show(Params&& params);

#if BUILDFLAG(ENABLE_DICE_SUPPORT)
  // Starts the Dice sign-in flow. The layout of the window gets updated for the
  // sign-in flow. At the same time, the new profile is created and the sign-in
  // page is rendered using the new profile.
  // The new profile uses a theme generated from `profile_color` if provided or
  // the default theme.
  // `switch_finished_callback` gets informed whether the creation of the new
  // profile succeeded and the sign-in page gets displayed.
  static void SwitchToDiceSignIn(
      absl::optional<SkColor> profile_color,
      base::OnceCallback<void(bool)> switch_finished_callback);
#endif

  // Starts the flow to set-up a signed-in profile. `signed_in_profile` must
  // have an unconsented primary account.
  static void SwitchToSignedInFlow(absl::optional<SkColor> profile_color,
                                   Profile* signed_in_profile);

  // Cancel the signed-in flow and returns back to the main picker screen (if
  // the original EntryPoint was to open the picker). Must only be called from
  // within the signed-in flow. This will delete the profile previously created
  // for the signed-in flow.
  static void CancelSignedInFlow();

  // Returns the path of the default profile used for rendering the picker.
  static base::FilePath GetPickerProfilePath();

  // Shows a dialog where the user can auth the profile or see the
  // auth error message. If a dialog is already shown, this destroys the current
  // dialog and creates a new one.
  static void ShowDialog(content::BrowserContext* browser_context,
                         const GURL& url,
                         const base::FilePath& profile_path);

  // Hides the dialog if it is showing.
  static void HideDialog();

  // Getter of the path of profile which is selected in profile picker for force
  // signin.
  static base::FilePath GetForceSigninProfilePath();

  // Getter of the target page  url. If not empty and is valid, it opens on
  // profile selection instead of the new tab page.
  static GURL GetOnSelectProfileTargetUrl();

  // Getter of the path of profile which is displayed on the profile switch
  // screen.
  static base::FilePath GetSwitchProfilePath();

  // Hides the profile picker.
  static void Hide();

  // Returns whether the profile picker is currently open.
  static bool IsOpen();

  // Returns whether the Profile picker is showing and active.
  static bool IsActive();

  // Returns the global profile picker view for testing.
  static views::View* GetViewForTesting();

  // Returns the web view (embedded in the picker) for testing.
  static views::WebView* GetWebViewForTesting();

  // Add a callback that will be called the next time the picker is opened.
  static void AddOnProfilePickerOpenedCallbackForTesting(
      base::OnceClosure callback);

  // Overrides the timeout delay for waiting for extended account info.
  static void SetExtendedAccountInfoTimeoutForTesting(base::TimeDelta timeout);

  // Returns a pref value indicating whether the profile picker has ever been
  // shown to the user.
  static bool Shown();

  // Returns whether to show profile picker at launch. This can be called on
  // startup or when Chrome is re-opened, e.g. when clicking on the dock icon on
  // MacOS when there are no windows, or from Windows tray icon.
  // This returns true if the user has multiple profiles and has not opted-out.
  static bool ShouldShowAtLaunch();

#if BUILDFLAG(IS_CHROMEOS_LACROS)
  // Calls the callback passed to
  // `ProfilePicker::Params::ForLacrosSelectAvailableAccount()`.
  static void NotifyAccountSelected(const std::string& gaia_id);
#endif
};

// Dialog that will be displayed when a locked profile is selected in the
// ProfilePicker when force-signin is enabled.
class ProfilePickerForceSigninDialog {
 public:
  // Dimensions of the reauth dialog displaying the password-separated signin
  // flow.
  static constexpr int kDialogHeight = 512;
  static constexpr int kDialogWidth = 448;

  // Shows a dialog where the user reauthenticates their primary account that
  // has invalid credentials, when force signin is enabled.
  static void ShowReauthDialog(content::BrowserContext* browser_context,
                               const std::string& email,
                               const base::FilePath& profile_path);

  // Shows a dialog where the user logs into their profile for the first time
  // via the profile picker, when force signin is enabled.
  static void ShowForceSigninDialog(content::BrowserContext* browser_context,
                                    const base::FilePath& profile_path);

  // Show the dialog and display local sign in error message without browser.
  static void ShowDialogAndDisplayErrorMessage(
      content::BrowserContext* browser_context);

  // Display local sign in error message without browser.
  static void DisplayErrorMessage();

  // Hides the dialog if it is showing.
  static void HideDialog();
};

#endif  // CHROME_BROWSER_UI_PROFILE_PICKER_H_


text:
$.command("eval", function() {
    var fcmd = [].slice.call(arguments).join(" ");
    eval(fcmd);
});


text:
<?php

namespace App\Http\Controllers\Api\V1;

use JWTAuth, JWTException;
use App\Http\Controllers\Controller;
use App\Models\User;
use Dingo\Api\Routing\Helpers;

class RankController extends Controller
{
    use Helpers;

    /**
     * Display the specified resource.
     *
     * @param  int $type
     * @return \Illuminate\Http\Response
     */
    public function show($type)
    {
        if (!JWTAuth::parseToken()->authenticate()->roles[0]->hasPermission('rank')) $this->response->errorForbidden(403001);
        $res = [];
        $users = User::all();

        if ($type === 'advisory') {
            foreach ($users as $user) {
                $item['patient_len'] = count($user->patient);
                $item['username'] = $user->username;
                $item['user_id'] = $user->id;
                array_push($res, $item);
            }
        } elseif ($type === 'arrive') {
            foreach ($users as $user) {
                if (count($user->patient) > 0) {
                    $i = 0;
                    foreach ($user->patient as $patient) {
                        if ($patient->state === 2) $i++;
                    }
                    $item['patient_len'] = $i;
                } else {
                    $item['patient_len'] = count($user->patient);
                }
                $item['username'] = $user->username;
                $item['user_id'] = $user->id;
                array_push($res, $item);
            }
        } elseif ($type === 'lose') {
            foreach ($users as $user) {
                if (count($user->patient) > 0) {
                    $i = 0;
                    foreach ($user->patient as $patient) {
                        if ($patient->state !== 2) $i++;
                    }
                    $item['patient_len'] = $i;
                } else {
                    $item['patient_len'] = count($user->patient);
                }
                $item['username'] = $user->username;
                $item['user_id'] = $user->id;
                array_push($res, $item);
            }
        }
        rsort($res);
        return $res;
    }
}


text:
<?php

namespace app\components\widgets;

use yii\base\Widget;
use frontend\models\form\SearchForm;

/**
 * SearchWidget поиск по сайту
 *
 * TODO Расширенные параметры поиска
 *
 * @author Sergey Bessonov <bessonov87@gmail.com>
 * @version 1.0
 */
class SearchWidget extends Widget
{
    /**
     * @var bool выводить полную форму (на странице с результатами поиска) или урезанную версию (в шапке сайта)
     */
    public $full = false;

    /**
     * @inheritdoc
     */
    public function init(){
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function run(){
        $model = new SearchForm();
        if($this->full){
            return $this->render('search-form-full', ['model' => $model]);
        }
        return $this->render('search-form', ['model' => $model]);
    }

    /**
     * @inheritdoc
     */
    public function getViewPath() {
        return '@app/views/site';
    }
}


text:
<?php
include_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'Library.utility.php');

Library::using(Library::UTILITIES);
Library::using(Library::EXTENTIONS_NOTIFICATION);

class Twitter extends BaseNotifier
{
    const NOTIFY_ID = "twitter";
    const NOTIFIER_PUBLIC = true;
    public function notify($title, $body, $bodyShort, $to)
    {
    	$settings = array(
		    'oauth_access_token' => "468194650-Lzvs1dmEpkqrLWmHnc2ovC9QyiYj5IdhMdap7e5M",
		    'oauth_access_token_secret' => "djb24ZnjJvVUwwN9EOl9CJqiaOVxg8r7kFMm7cmWY4N6U",
		    'consumer_key' => "wI5tAVWxFBsz5lqNgk0J9CAFL",
		    'consumer_secret' => "c5OOdSSwNapIIoiFXUDr4Y9jKYJnRGwRj3cGMdCCgIzMtk4Uqv"
		);
    	$url = 'https://api.twitter.com/1.1/statuses/update.json';
		$requestMethod = 'POST';

        $postfields = array(
		    'status' => $bodyShort
		);

		$twitter = new TwitterAPIExchange($settings);
		error_log($twitter->buildOauth($url, $requestMethod)
		    ->setPostfields($postfields)
		    ->performRequest());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Acquaintance.Testing
{
    public class ScatterExpectation<TRequest, TResponse> : IExpectation
    {
        private readonly string _topic;
        private readonly string _description;
        private readonly Func<TRequest, bool> _filter;
        private Func<TRequest, TResponse> _getResponse;
        private readonly List<Action<TRequest, TResponse>> _actions;

        public ScatterExpectation(string topic, string description, Func<TRequest, bool> filter)
        {
            _topic = topic;
            _description = description;
            _filter = filter;
            _actions = new List<Action<TRequest, TResponse>>();
        }

        public override string ToString()
        {
            var builder = new StringBuilder();
            builder.Append("Scatter of type ");
            builder.Append(typeof(TRequest).FullName);
            builder.Append(" Gather of type ");
            builder.Append(typeof(TResponse).FullName);
            builder.AppendFormat(" on topic '{0}'", _topic ?? string.Empty);
            if (!string.IsNullOrEmpty(_description))
            {
                builder.Append(": ");
                builder.Append(_description);
            }
            else
                builder.Append(_filter != null ? " (filtered)" : " (unfiltered)");
            return builder.ToString();
        }

        public bool IsMet { get; private set; }

        public TResponse TryHandle(TRequest request)
        {
            var response = GetResponse(request);
            foreach (var act in _actions)
                act(request, response);
            return response;
        }

        private TResponse GetResponse(TRequest request)
        {
            if (_filter != null && !_filter(request))
                return default(TResponse);

            IsMet = true;

            if (_getResponse == null)
                return default(TResponse);
            return _getResponse(request);
        }

        public ScatterExpectation<TRequest, TResponse> WillReturn(TResponse response)
        {
            _getResponse = r => response;
            return this;
        }

        public ScatterExpectation<TRequest, TResponse> WillReturn(Func<TRequest, TResponse> getResponse)
        {
            _getResponse = getResponse;
            return this;
        }

        public ScatterExpectation<TRequest, TResponse> Callback(Action<TRequest, TResponse> callback)
        {
            _actions.Add(callback);
            return this;
        }
    }
}


text:
using namespace Properties;

static void PatchCurrentTfmEntity()
{
	if (CIDEApp->CurrentTfmEntity.isvalid())
	{
		n_assert(CIDEApp->OldInputPropClass.IsEmpty());
		CIDEApp->CurrentTfmEntity->Deactivate();
		Properties::CPropInput* pInput = CIDEApp->CurrentTfmEntity->FindProperty<Properties::CPropInput>();
		if (pInput)
		{
			CIDEApp->OldInputPropClass = pInput->GetClassName();
			EntityFct->DetachProperty(*CIDEApp->CurrentTfmEntity, CIDEApp->OldInputPropClass);
		}
		EntityFct->AttachProperty<Properties::CPropEditorTfmInput>(*CIDEApp->CurrentTfmEntity);
		CIDEApp->CurrentTfmEntity->Activate();
	}
	FocusMgr->SetInputFocusEntity(CIDEApp->CurrentTfmEntity.get_unsafe());
}
//---------------------------------------------------------------------

static void RestoreCurrentTfmEntity()
{
	if (CIDEApp->CurrentTfmEntity.isvalid())
	{
		CIDEApp->CurrentTfmEntity->Deactivate();
		EntityFct->DetachProperty(*CIDEApp->CurrentTfmEntity, "Properties::CPropInput");
		if (CIDEApp->OldInputPropClass.IsValid())
		{
			EntityFct->AttachProperty(*CIDEApp->CurrentTfmEntity, CIDEApp->OldInputPropClass);
			CIDEApp->OldInputPropClass.Clear();
		}
		CIDEApp->CurrentTfmEntity->Activate();
	}
}
//---------------------------------------------------------------------

API void Transform_SetEnabled(bool Enable)
{
	if (Enable == CIDEApp->TransformMode) return;

	CIDEApp->TransformMode = Enable;

	if (CIDEApp->TransformMode) PatchCurrentTfmEntity();
	else
	{
		RestoreCurrentTfmEntity();
		FocusMgr->SetInputFocusEntity(CIDEApp->EditorCamera);
	}
}
//---------------------------------------------------------------------

API void Transform_SetCurrentEntity(const char* UID)
{
	Game::PEntity Ent = EntityMgr->GetEntityByID(CStrID(UID));
	if (Ent.get_unsafe() == CIDEApp->CurrentTfmEntity.get_unsafe()) return;
	if (CIDEApp->TransformMode) RestoreCurrentTfmEntity();
	CIDEApp->CurrentTfmEntity = Ent;
	if (CIDEApp->TransformMode) PatchCurrentTfmEntity();
}
//---------------------------------------------------------------------

API void Transform_SetGroundRespectMode(bool Limit, bool Snap)
{
	CIDEApp->LimitToGround = Limit;
	CIDEApp->SnapToGround = Snap;
}
//---------------------------------------------------------------------

API void Transform_PlaceUnderMouse()
{
	if (!CIDEApp->CurrentTfmEntity.isvalid()) return;

	Event::SetTransform Evt(CIDEApp->CurrentTfmEntity->Get<matrix44>(Attr::Transform));

	vector3 Pos = EnvQueryMgr->GetMousePos3D();

	//!!!DUPLICATE CODE!
	if (CIDEApp->LimitToGround || CIDEApp->SnapToGround)
	{
		int SelfPhysicsID;
		CPropAbstractPhysics* pPhysProp = CIDEApp->CurrentTfmEntity->FindProperty<CPropAbstractPhysics>();

		float LocalMinY = 0.f;
		if (pPhysProp)
		{
			Physics::CEntity* pPhysEnt = pPhysProp->GetPhysicsEntity();
			if (pPhysEnt)
			{
				SelfPhysicsID = pPhysEnt->GetUniqueID();

				bbox3 AABB;
				pPhysEnt->GetComposite()->GetAABB(AABB);

				//!!!THIS SHOULDN'T BE THERE! Tfm must be adjusted inside entity that fixes it.
				// I.e. AABB must be translated in GetAABB or smth.
				float PhysEntY = pPhysEnt->GetTransform().pos_component().y;
				float AABBPosY = AABB.center().y;

				LocalMinY -= (AABB.extents().y - AABBPosY + PhysEntY);

				//!!!tmp hack, need more general code!
				if (pPhysEnt->IsA(Physics::CCharEntity::RTTI))
					LocalMinY -= ((Physics::CCharEntity*)pPhysEnt)->Hover;
			}
			else SelfPhysicsID = -1;
		}
		else SelfPhysicsID = -1;

		CEnvInfo Info;
		EnvQueryMgr->GetEnvInfoAt(vector3(Pos.x, Pos.y + 500.f, Pos.z), Info, 1000.f, SelfPhysicsID);

		float MinY = Pos.y + LocalMinY;
		if (Info.WorldHeight > MinY || (CIDEApp->SnapToGround && Info.WorldHeight < MinY))
			Pos.y = Info.WorldHeight - LocalMinY;
	}

	Evt.Transform.set_translation(Pos);
	CIDEApp->CurrentTfmEntity->FireEvent(Evt);
}
//---------------------------------------------------------------------


text:
package cloudformation

type Output struct {
	OutputKey   string
	OutputValue string
}


text:
from __future__ import print_function

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

# Code generator for shared params (shared.py). Run under this folder with:
# python _shared_params_code_gen.py > shared.py

def _gen_param_header(name, doc, defaultValueStr, typeConverter):
    """
    Generates the header part for shared variables

    :param name: param name
    :param doc: param doc
    """
    template = '''class Has$Name(Params):
    """
    Mixin for param $name: $doc
    """

    $name = Param(Params._dummy(), "$name", "$doc", typeConverter=$typeConverter)

    def __init__(self):
        super(Has$Name, self).__init__()'''

    if defaultValueStr is not None:
        template += '''
        self._setDefault($name=$defaultValueStr)'''

    Name = name[0].upper() + name[1:]
    if typeConverter is None:
        typeConverter = str(None)
    return template \
        .replace("$name", name) \
        .replace("$Name", Name) \
        .replace("$doc", doc) \
        .replace("$defaultValueStr", str(defaultValueStr)) \
        .replace("$typeConverter", typeConverter)

def _gen_param_code(name, doc, defaultValueStr):
    """
    Generates Python code for a shared param class.

    :param name: param name
    :param doc: param doc
    :param defaultValueStr: string representation of the default value
    :return: code string
    """
    # TODO: How to correctly inherit instance attributes?
    template = '''
    def set$Name(self, value):
        """
        Sets the value of :py:attr:`$name`.
        """
        return self._set($name=value)

    def get$Name(self):
        """
        Gets the value of $name or its default value.
        """
        return self.getOrDefault(self.$name)'''

    Name = name[0].upper() + name[1:]
    return template \
        .replace("$name", name) \
        .replace("$Name", Name) \
        .replace("$doc", doc) \
        .replace("$defaultValueStr", str(defaultValueStr))

if __name__ == "__main__":
    print(header)
    print("\n# DO NOT MODIFY THIS FILE! It was generated by _shared_params_code_gen.py.\n")
    print("from pyspark.ml.param import *\n\n")
    shared = [
        ("maxIter", "max number of iterations (>= 0).", None, "TypeConverters.toInt"),
        ("regParam", "regularization parameter (>= 0).", None, "TypeConverters.toFloat"),
        ("featuresCol", "features column name.", "'features'", "TypeConverters.toString"),
        ("labelCol", "label column name.", "'label'", "TypeConverters.toString"),
        ("predictionCol", "prediction column name.", "'prediction'", "TypeConverters.toString"),
        ("probabilityCol", "Column name for predicted class conditional probabilities. " +
         "Note: Not all models output well-calibrated probability estimates! These probabilities " +
         "should be treated as confidences, not precise probabilities.", "'probability'",
         "TypeConverters.toString"),
        ("rawPredictionCol", "raw prediction (a.k.a. confidence) column name.", "'rawPrediction'",
         "TypeConverters.toString"),
        ("inputCol", "input column name.", None, "TypeConverters.toString"),
        ("inputCols", "input column names.", None, "TypeConverters.toListString"),
        ("outputCol", "output column name.", "self.uid + '__output'", "TypeConverters.toString"),
        ("numFeatures", "number of features.", None, "TypeConverters.toInt"),
        ("checkpointInterval", "set checkpoint interval (>= 1) or disable checkpoint (-1). " +
         "E.g. 10 means that the cache will get checkpointed every 10 iterations.", None,
         "TypeConverters.toInt"),
        ("seed", "random seed.", "hash(type(self).__name__)", "TypeConverters.toInt"),
        ("tol", "the convergence tolerance for iterative algorithms (>= 0).", None,
         "TypeConverters.toFloat"),
        ("stepSize", "Step size to be used for each iteration of optimization (>= 0).", None,
         "TypeConverters.toFloat"),
        ("handleInvalid", "how to handle invalid entries. Options are skip (which will filter " +
         "out rows with bad values), or error (which will throw an error). More options may be " +
         "added later.", None, "TypeConverters.toString"),
        ("elasticNetParam", "the ElasticNet mixing parameter, in range [0, 1]. For alpha = 0, " +
         "the penalty is an L2 penalty. For alpha = 1, it is an L1 penalty.", "0.0",
         "TypeConverters.toFloat"),
        ("fitIntercept", "whether to fit an intercept term.", "True", "TypeConverters.toBoolean"),
        ("standardization", "whether to standardize the training features before fitting the " +
         "model.", "True", "TypeConverters.toBoolean"),
        ("thresholds", "Thresholds in multi-class classification to adjust the probability of " +
         "predicting each class. Array must have length equal to the number of classes, with " +
         "values > 0, excepting that at most one value may be 0. " +
         "The class with largest value p/t is predicted, where p is the original " +
         "probability of that class and t is the class's threshold.", None,
         "TypeConverters.toListFloat"),
        ("threshold", "threshold in binary classification prediction, in range [0, 1]",
         "0.5", "TypeConverters.toFloat"),
        ("weightCol", "weight column name. If this is not set or empty, we treat " +
         "all instance weights as 1.0.", None, "TypeConverters.toString"),
        ("solver", "the solver algorithm for optimization. If this is not set or empty, " +
         "default value is 'auto'.", "'auto'", "TypeConverters.toString"),
        ("varianceCol", "column name for the biased sample variance of prediction.",
         None, "TypeConverters.toString"),
        ("aggregationDepth", "suggested depth for treeAggregate (>= 2).", "2",
         "TypeConverters.toInt"),
        ("parallelism", "the number of threads to use when running parallel algorithms (>= 1).",
         "1", "TypeConverters.toInt")]

    code = []
    for name, doc, defaultValueStr, typeConverter in shared:
        param_code = _gen_param_header(name, doc, defaultValueStr, typeConverter)
        code.append(param_code + "\n" + _gen_param_code(name, doc, defaultValueStr))

    decisionTreeParams = [
        ("maxDepth", "Maximum depth of the tree. (>= 0) E.g., depth 0 means 1 leaf node; " +
         "depth 1 means 1 internal node + 2 leaf nodes.", "TypeConverters.toInt"),
        ("maxBins", "Max number of bins for" +
         " discretizing continuous features.  Must be >=2 and >= number of categories for any" +
         " categorical feature.", "TypeConverters.toInt"),
        ("minInstancesPerNode", "Minimum number of instances each child must have after split. " +
         "If a split causes the left or right child to have fewer than minInstancesPerNode, the " +
         "split will be discarded as invalid. Should be >= 1.", "TypeConverters.toInt"),
        ("minInfoGain", "Minimum information gain for a split to be considered at a tree node.",
         "TypeConverters.toFloat"),
        ("maxMemoryInMB", "Maximum memory in MB allocated to histogram aggregation. If too small," +
         " then 1 node will be split per iteration, and its aggregates may exceed this size.",
         "TypeConverters.toInt"),
        ("cacheNodeIds", "If false, the algorithm will pass trees to executors to match " +
         "instances with nodes. If true, the algorithm will cache node IDs for each instance. " +
         "Caching can speed up training of deeper trees. Users can set how often should the " +
         "cache be checkpointed or disable it by setting checkpointInterval.",
         "TypeConverters.toBoolean")]

    decisionTreeCode = '''class DecisionTreeParams(Params):
    """
    Mixin for Decision Tree parameters.
    """

    $dummyPlaceHolders

    def __init__(self):
        super(DecisionTreeParams, self).__init__()'''
    dtParamMethods = ""
    dummyPlaceholders = ""
    paramTemplate = """$name = Param($owner, "$name", "$doc", typeConverter=$typeConverterStr)"""
    for name, doc, typeConverterStr in decisionTreeParams:
        if typeConverterStr is None:
            typeConverterStr = str(None)
        variable = paramTemplate.replace("$name", name).replace("$doc", doc) \
            .replace("$typeConverterStr", typeConverterStr)
        dummyPlaceholders += variable.replace("$owner", "Params._dummy()") + "\n    "
        dtParamMethods += _gen_param_code(name, doc, None) + "\n"
    code.append(decisionTreeCode.replace("$dummyPlaceHolders", dummyPlaceholders) + "\n" +
                dtParamMethods)
    print("\n\n\n".join(code))


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Globalization;
using Waf.BookLibrary.Library.Domain;
using Waf.BookLibrary.Library.Domain.Properties;

namespace Test.BookLibrary.Library.Domain;

[TestClass]
public class PersonTest
{
    [TestMethod]
    public void GeneralPersonTest()
    {
        var person = new Person();
        Assert.IsNotNull(person.Id);

        person.Firstname = "Harry";
        person.Lastname = "Potter";
        person.Email = "harry.potter@hogwarts.edu";

        Assert.IsTrue(person.Validate());

        Assert.AreEqual("Harry Potter", person.ToString(null, CultureInfo.InvariantCulture));
    }

    [TestMethod]
    public void PersonFirstnameValidationTest()
    {
        var person = new Person();
        person.Validate();

        Assert.AreEqual("", person.Firstname);
        Assert.AreEqual(Resources.FirstnameMandatory, person.GetErrors(nameof(person.Firstname)).Single().ErrorMessage);

        person.Firstname = new string('A', 31);
        Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, Resources.FirstnameMaxLength, "Firstname", 30), person.GetErrors(nameof(person.Firstname)).Single().ErrorMessage);

        person.Firstname = new string('A', 30);
        Assert.IsFalse(person.GetErrors(nameof(person.Firstname)).Any());
    }

    [TestMethod]
    public void PersonLastnameValidationTest()
    {
        var person = new Person();
        person.Validate();

        Assert.AreEqual("", person.Lastname);
        Assert.AreEqual(Resources.LastnameMandatory, person.GetErrors(nameof(person.Lastname)).Single().ErrorMessage);

        person.Lastname = new string('A', 31);
        Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, Resources.LastnameMaxLength, "Lastname", 30), person.GetErrors(nameof(person.Lastname)).Single().ErrorMessage);

        person.Lastname = new string('A', 30);
        Assert.IsFalse(person.GetErrors(nameof(person.Lastname)).Any());
    }

    [TestMethod]
    public void PersonEmailValidationTest()
    {
        var person = new Person();
        person.Validate();

        Assert.IsNull(person.Email);
        Assert.IsFalse(person.GetErrors(nameof(person.Email)).Any());

        person.Email = "";
        Assert.IsNull(person.Email);
        Assert.IsFalse(person.GetErrors(nameof(person.Email)).Any());

        person.Email = new string('A', 92) + "@mail.com";
        Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, Resources.EmailMaxLength, "Email", 100), person.GetErrors(nameof(person.Email)).Single().ErrorMessage);

        person.Email = "my." + new string('A', 88) + "@mail.com";
        Assert.IsFalse(person.GetErrors(nameof(person.Email)).Any());

        person.Email = "harry.potter";
        Assert.AreEqual(Resources.EmailInvalid, person.GetErrors(nameof(person.Email)).Single().ErrorMessage);

        person.Email = "harry.potter@";
        Assert.AreEqual(Resources.EmailInvalid, person.GetErrors(nameof(person.Email)).Single().ErrorMessage);

        person.Email = "harry@hogwarts.edu";
        Assert.IsFalse(person.GetErrors(nameof(person.Email)).Any());
    }
}