text:
package hudson.console;

import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.model.Run;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import org.jvnet.tiger_types.Types;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebMethod;

/**
 * Entry point to the {@link ConsoleAnnotator} extension point. This class creates a new instance
 * of {@link ConsoleAnnotator} that starts a new console annotation session.
 *
 *

 * {@link ConsoleAnnotatorFactory}s are used whenever a browser requests console output (as opposed to when
 * the console output is being produced — for that see {@link ConsoleNote}.)
 *
 *

 * {@link ConsoleAnnotator}s returned by {@link ConsoleAnnotatorFactory} are asked to start from
 * an arbitrary line of the output, because typically browsers do not request the entire console output.
 * Because of this, {@link ConsoleAnnotatorFactory} is generally suitable for peep-hole local annotation
 * that only requires a small contextual information, such as keyword coloring, URL hyperlinking, and so on.
 *
 *

 * To register, put @{@link Extension} on your {@link ConsoleAnnotatorFactory} subtype.
 *
 *
Behaviour, JavaScript, and CSS

 *

 * {@link ConsoleNote} can have associated {@code script.js} and {@code style.css} (put them
 * in the same resource directory that you normally put Jelly scripts), which will be loaded into
 * the HTML page whenever the console notes are used. This allows you to use minimal markup in
 * code generation, and do the styling in CSS and perform the rest of the interesting work as a CSS behaviour/JavaScript.
 *
 * @author Kohsuke Kawaguchi
 * @since 1.349
 */
public abstract class ConsoleAnnotatorFactory<T> implements ExtensionPoint {
    /**
     * Called when a console output page is requested to create a stateful {@link ConsoleAnnotator}.
     *
     *

     * This method can be invoked concurrently by multiple threads.
     *
     * @param context
     *      The model object that owns the console output, such as {@link Run}.
     *      This method is only called when the context object if assignable to
     *      {@linkplain #type() the advertised type}.
     * @return
     *      null if this factory is not going to participate in the annotation of this console.
     */
    public abstract ConsoleAnnotator<T> newInstance(T context);

    /**
     * For which context type does this annotator work?
     */
    public Class<?> type() {
        Type type = Types.getBaseClass(getClass(), ConsoleAnnotatorFactory.class);
        if (type instanceof ParameterizedType)
            return Types.erasure(Types.getTypeArgument(type, 0));
        else
            return Object.class;
    }

    /**
     * Returns true if this descriptor has a JavaScript to be inserted on applicable console page.
     */
    public boolean hasScript() {
        return getResource("/script.js") != null;
    }

    public boolean hasStylesheet() {
        return getResource("/style.css") != null;
    }

    private URL getResource(String fileName) {
        Class<?> c = getClass();
        return c.getClassLoader().getResource(c.getName().replace('.', '/').replace('$', '/') + fileName);
    }

    /**
     * Serves the JavaScript file associated with this console annotator factory.
     */
    @WebMethod(name = "script.js")
    public void doScriptJs(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        rsp.serveFile(req, getResource("/script.js"), TimeUnit.DAYS.toMillis(1));
    }

    @WebMethod(name = "style.css")
    public void doStyleCss(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        rsp.serveFile(req, getResource("/style.css"), TimeUnit.DAYS.toMillis(1));
    }

    /**
     * All the registered instances.
     */
    @SuppressWarnings("rawtypes")
    public static ExtensionList<ConsoleAnnotatorFactory> all() {
        return ExtensionList.lookup(ConsoleAnnotatorFactory.class);
    }
}


text:
Contributor License
-------------------

If this is your first time contributing to an Eclipse Foundation project, you'll need to sign the [Eclipse Foundation Contributor License Agreement][CLA].

- [Create an account](https://dev.eclipse.org/site_login/createaccount.php) on dev.eclipse.org
- Open your [Account Settings tab](https://dev.eclipse.org/site_login/myaccount.php#open_tab_accountsettings), enter your GitHub ID and click Update Account
- Read and [sign the CLA](https://projects.eclipse.org/user/sign/cla)
- Your git commits must be [signed off](https://wiki.eclipse.org/Development_Resources/Contributing_via_Git#Signing_off_on_a_commit)
- Use the exact same email address for your Eclipse account, your commit author, and your commit sign-off.

Issues
------

Search the [issue tracker](https://github.com/eclipse/eclipse-collections/issues) for a relevant issue or create a new one.

Making changes
--------------

Fork the repository in GitHub and make changes in your fork.

Please add a description of your changes to the [draft release notes](RELEASE_NOTE_DRAFT.md).

Finally, submit a pull request.

Contact us
----------

[Join the mailing list][mailing-list] and email the community at collections-dev@eclipse.org to discuss your ideas and get help.

Build
-----
The Eclipse Collections build requires below as dependencies.

- Java 1.8
- Maven 3.1.0+

The Eclipse Collections build performs code generation to create primitive collections. Run the full build once before opening your IDE.

```bash
$ mvn install -DskipTests=true
```

Now you can open the project in your IDE and it won't complain about missing files. You'll be able to use the IDE to perform incremental builds and run tests. You should rarely need to run the maven build, except when:

- you want to force a clean build
- you work on [JMH][jmh] tests
- your changes affect code generation
- you want to see if your changes will pass [the same builds that Travis CI runs][travis]

Semantic Versioning
-------------------

Eclipse Collections version numbers follow [Semantic Versioning][semver]. This means we increment the major version when we make incompatible API changes. This includes any changes which

- break binary compatibility
- break source compatibility
- break serialization compatibility

Normally, collections will have the same serialized form across major releases, indefinitely. But if we have to break serialization for some reason, it will be in a major release. Eclipse Collections includes a suite of serialization tests to prevent accidental changes.

While preparing a minor release, the master branch won't contain any compatibility breaking changes. Feel free to work on major, compatibility-breaking changes whenever you'd like. However, if you submit a pull request to master while we're preparing a minor release, you'll have to be patient and you'll need to rebase your changes once the release is complete.

Coding Style
------------

Eclipse Collections follows a coding style that is similar to [Google's Style Guide for Java][style-guide], but with curly braces on their own lines. Many aspects of the style guide are enforced by CheckStyle, but not all, so please take care.

```bash
$ mvn clean install checkstyle:check findbugs:check --projects '!scala-unit-tests,!jmh-scala-tests,!jmh-tests' -DskipTests=true
```

Avoid changing whitespace on lines that are unrelated to your pull request. This helps preserve the accuracy of the git blame view, and makes code reviews easier.

Commit messages
---------------

- [Use the imperative mood][imperative-mood] as in "Fix bug" or "Add feature" rather than "Fixed bug" or "Added feature"
- [Mention the GitHub issue][github-issue] when relevant
- It's a good idea to follow the [advice in Pro Git](https://git-scm.com/book/ch5-2.html)
- Sign-off your commits using `git commit --signoff` or `git commit -s` for short

Pull requests
-------------

Excessive branching and merging can make git history confusing. With that in mind

- Squash your commits down to a few commits, or one commit, before submitting a pull request
- [Rebase your pull request changes on top of the current master][rebase]. Pull requests shouldn't include merge commits.

Submit your pull request when ready. Three checks will be kicked off automatically.

- IP Validation: Checks that all committers signed the Eclipse CLA and signed their commits.
- Continuous integration: [Travis builds][travis] that run JUnit tests, CheckStyle, and FindBugs.
- The standard GitHub check that the pull request has no conflicts with the base branch.

Make sure all the checks pass. One of the committers will take a look and provide feedback or merge your contribution.

That's it! Thanks for contributing to Eclipse Collections!

[CLA]:             https://www.eclipse.org/legal/CLA.php
[jmh]:             http://openjdk.java.net/projects/code-tools/jmh/
[semver]:          http://semver.org/
[style-guide]:     https://google.github.io/styleguide/javaguide.html
[rebase]:          https://github.com/edx/edx-platform/wiki/How-to-Rebase-a-Pull-Request
[travis]:          https://travis-ci.org/eclipse/eclipse-collections
[imperative-mood]: https://github.com/git/git/blob/master/Documentation/SubmittingPatches
[github-issue]:    https://help.github.com/articles/closing-issues-via-commit-messages/
[mailing-list]:    https://dev.eclipse.org/mailman/listinfo/collections-dev

redpajama_set_name: RedPajamaGithub


text:
package net.uncontended.precipice.metrics.counts;

import net.uncontended.precipice.metrics.tools.Allocator;

public final class Counters {

    private Counters() {
    }

    public static <T extends Enum<T>> Allocator<PartitionedCount<T>> longAdder(Class<T> clazz) {
        return new LongAdderAllocator<>(clazz);
    }

    public static <T extends Enum<T>> Allocator<PartitionedCount<T>> atomicLong(Class<T> clazz) {
        return new AtomicLongAllocator<>(clazz);
    }

    public static <T extends Enum<T>> Allocator<PartitionedCount<T>> longCounter(Class<T> clazz) {
        return new LongAllocator<>(clazz);
    }

    private static class LongAdderAllocator<T extends Enum<T>> implements Allocator<PartitionedCount<T>> {

        private final Class<T> clazz;

        private LongAdderAllocator(Class<T> clazz) {
            this.clazz = clazz;
        }

        @Override
        public PartitionedCount<T> allocateNew() {
            return new LongAdderCounter<>(clazz);
        }
    }

    private static class AtomicLongAllocator<T extends Enum<T>> implements Allocator<PartitionedCount<T>> {

        private final Class<T> clazz;

        private AtomicLongAllocator(Class<T> clazz) {
            this.clazz = clazz;
        }

        @Override
        public PartitionedCount<T> allocateNew() {
            return new AtomicLongCounter<>(clazz);
        }
    }

    private static class LongAllocator<T extends Enum<T>> implements Allocator<PartitionedCount<T>> {

        private final Class<T> clazz;

        private LongAllocator(Class<T> clazz) {
            this.clazz = clazz;
        }

        @Override
        public PartitionedCount<T> allocateNew() {
            return new LongCounter<>(clazz);
        }
    }
}


text:
class AddIndexToLocations < ActiveRecord::Migration
  def change
    add_index :locations, :name
  end
end


text:
/*flexberryautogenerated="true"*/
namespace IIS.indiv_Firm
{
    using System;
    using ICSSoft.STORMNET.Web.Controls;

    using Resources;

    public partial class EmployeeL : BaseListForm<Employee>
    {
        /// <summary>
        /// Конструктор без параметров,
        /// инициализирует свойства, соответствующие конкретной форме.
        /// </summary>
        public EmployeeL() : base(Employee.Views.EmployeeL)
        {
            EditPage = EmployeeE.FormPath;
        }

        /// <summary>
        /// Путь до формы.
        /// </summary>
        public static string FormPath
        {
            get { return "~/forms/Employee/EmployeeL.aspx"; }
        }

        /// <summary>
        /// Вызывается самым первым в Page_Load.
        /// </summary>
        protected override void Preload()
        {
        }

        /// <summary>
        /// Вызывается самым последним в Page_Load.
        /// </summary>
        protected override void Postload()
        {
        }
    }
}


text:
"use strict";

const utils = require("../../../utils/ast-utils");

/**
 *
 * Transform for recordsInputPath. Finds the recordsInputPath property from yeoman and creates a
 * property based on what the user has given us.
 *
 * @param j — jscodeshift API
 * @param ast - jscodeshift API
 * @param {any} webpackProperties - transformation object to scaffold
 * @param {String} action - action that indicates what to be done to the AST
 * @returns ast - jscodeshift API
 */

module.exports = function recordsInputPathTransform(
	j,
	ast,
	webpackProperties,
	action
) {
	function createRecordsInputPathProperty(p) {
		utils.pushCreateProperty(j, p, "recordsInputPath", j.objectExpression([]));
		return utils.pushObjectKeys(j, p, webpackProperties, "recordsInputPath");
	}
	if (webpackProperties) {
		if (action === "init" && typeof webpackProperties === "object") {
			return ast
				.find(j.ObjectExpression)
				.filter(p =>
					utils.isAssignment(null, p, createRecordsInputPathProperty)
				);
		} else if (action === "init" && webpackProperties.length) {
			return ast
				.find(j.ObjectExpression)
				.filter(p =>
					utils.isAssignment(
						j,
						p,
						utils.pushCreateProperty,
						"recordsInputPath",
						webpackProperties
					)
				);
		} else if (action === "add") {
			const recordsInputPathNode = utils.findRootNodesByName(
				j,
				ast,
				"recordsInputPath"
			);
			if (
				recordsInputPathNode.size() !== 0 &&
				typeof webpackProperties === "object"
			) {
				return ast
					.find(j.ObjectExpression)
					.filter(
						p =>
							utils.safeTraverse(p, ["parentPath", "value", "key", "name"]) ===
							"recordsInputPath"
					)
					.filter(p => {
						Object.keys(webpackProperties).forEach(prop => {
							utils.checkIfExistsAndAddValue(
								j,
								p,
								prop,
								utils.createIdentifierOrLiteral(j, webpackProperties[prop])
							);
						});
						return ast;
					});
			} else if (
				recordsInputPathNode.size() !== 0 &&
				webpackProperties.length > 0
			) {
				return utils
					.findRootNodesByName(j, ast, "recordsInputPath")
					.forEach(p => {
						j(p).replaceWith(
							j.property(
								"init",
								utils.createIdentifierOrLiteral(j, "recordsInputPath"),
								utils.createIdentifierOrLiteral(j, webpackProperties)
							)
						);
					});
			} else {
				return recordsInputPathTransform(j, ast, webpackProperties, "init");
			}
		} else if (action === "remove") {
			// TODO
		} else if (action === "update") {
			// TODO
		}
	} else {
		return ast;
	}
};


text:
package org.jbpm.console.ng.dm.client.document.CMISconfig;

import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.inject.Inject;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.Composite;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.Label;
import org.gwtbootstrap3.client.ui.TextBox;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.EventHandler;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import org.jbpm.console.ng.dm.client.i18n.Constants;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.workbench.events.NotificationEvent;
import org.uberfire.workbench.events.NotificationEvent.NotificationType;

@Dependent
@Templated(value = "CMISConfigurationViewImpl.html")
public class CMISConfigurationViewImpl extends Composite implements
		CMISConfigurationPresenter.CMISConfigurationView {

	@Inject
	private PlaceManager placeManager;

	private CMISConfigurationPresenter presenter;

	private Constants constants = GWT.create(Constants.class);

	@Inject
	private Event<NotificationEvent> notification;

	@Inject
    @DataField
    public Label accordionLabel;

    @Inject
    @DataField
    public Label webServicesACLLabel;

    @Inject
    @DataField
    public TextBox webServicesACLBox;

    @Inject
    @DataField
    public Label webServicesDiscoveryLabel;

    @Inject
    @DataField
    public TextBox webServicesDiscoveryBox;

    @Inject
    @DataField
    public Label webServicesMultifilingLabel;

    @Inject
    @DataField
    public TextBox webServicesMultifilingBox;

    @Inject
    @DataField
    public Label webServicesNavigationLabel;

    @Inject
    @DataField
    public TextBox webServicesNavigationBox;

    @Inject
    @DataField
    public Label webServicesObjectLabel;

    @Inject
    @DataField
    public TextBox webServicesObjectBox;

    @Inject
    @DataField
    public Label webServicesPolicyLabel;

    @Inject
    @DataField
    public TextBox webServicesPolicyBox;

    @Inject
    @DataField
    public Label webServicesRelationshipLabel;

    @Inject
    @DataField
    public TextBox webServicesRelationshipBox;

    @Inject
    @DataField
    public Label webServicesRepositoryLabel;

    @Inject
    @DataField
    public TextBox webServicesRepositoryBox;

    @Inject
    @DataField
    public Label webServicesVersioningLabel;

    @Inject
    @DataField
    public TextBox webServicesVersioningBox;

    @Inject
    @DataField
    public Label repositoryIDLabel;

    @Inject
    @DataField
    public TextBox repositoryIDBox;

    @Inject
    @DataField
    public Label userLabel;

    @Inject
    @DataField
    public TextBox userBox;

    @Inject
    @DataField
    public Label passwordLabel;

    @Inject
    @DataField
    public TextBox passwordBox;

    @Inject
    @DataField
    public Button configureButton;

    @Inject
    @DataField
    public Button testButton;

	@Override
	public void init(final CMISConfigurationPresenter presenter) {
		this.presenter = presenter;
        accordionLabel.setText("CMIS Configuration");

        webServicesACLLabel.setText("Webservices ACL");
        webServicesDiscoveryLabel.setText("Webservices Discovery");
        webServicesMultifilingLabel.setText("Webservices Multifiling");
        webServicesNavigationLabel.setText("Webservices Navigation");
        webServicesObjectLabel.setText("Webservices Object");
        webServicesPolicyLabel.setText("Webservices Policy");
        webServicesRelationshipLabel.setText("Webservices Relationship");
        webServicesRepositoryLabel.setText("Webservices Repository");
        webServicesVersioningLabel.setText("Webservices Versioning");
        repositoryIDLabel.setText("Repository ID");
        userLabel.setText("User");
        passwordLabel.setText("Password");

        configureButton.setText("Save");
        testButton.setText("Test Connection");
	}

	@Override
	public void displayNotification(String text) {
		displayNotification(text, NotificationType.INFO);
	}

	@Override
	public void displayNotification(String text, NotificationType type) {
		notification.fire(new NotificationEvent(text,type));
	}

	@EventHandler("configureButton")
    public void configureButton( ClickEvent e ) {
        presenter.configureParameters();
    }

	@EventHandler("testButton")
    public void testButton( ClickEvent e ) {
        presenter.testConnection();
    }

	@Override
	public TextBox getWSACLTextBox() {
		return webServicesACLBox;
	}

	@Override
	public TextBox getWSDiscoveryTextBox() {
		return webServicesDiscoveryBox;
	}

	@Override
	public TextBox getWSMultifilingTextBox() {
		return webServicesMultifilingBox;
	}

	@Override
	public TextBox getWSNavigationTextBox() {
		return webServicesNavigationBox;
	}

	@Override
	public TextBox getWSObjectTextBox() {
		return webServicesObjectBox;
	}

	@Override
	public TextBox getWSPolicyTextBox() {
		return webServicesPolicyBox;
	}

	@Override
	public TextBox getWSRelationshipTextBox() {
		return webServicesRelationshipBox;
	}

	@Override
	public TextBox getWSRepositoryTextBox() {
		return webServicesRepositoryBox;
	}

	@Override
	public TextBox getWSVersioningTextBox() {
		return webServicesVersioningBox;
	}

	@Override
	public TextBox getUserTextBox() {
		return userBox;
	}

	@Override
	public TextBox getPasswordTextBox() {
		return passwordBox;
	}

	@Override
	public TextBox getRepositoryIDTextBox() {
		return repositoryIDBox;
	}

	@Override
	public Button getConfigureButton() {
		return configureButton;
	}

	@Override
	public Button getTestButton() {
		return testButton;
	}

}


text:
An AsciiDoc canvas that facilitates writing AsciiDoc to a stream. The main methods are #surround:with: and #precede:by: that allow you to write something like this:

canvas surround:  [ "some code that generates the string inside the bold" ] with: '*'

canvas precede: [ "some code that generates the string which will be change by the label" ]  by: '[label]'


text:
package com.microsoft.azure.management.compute;

import java.util.List;

/**
 * Api error.
 */
public class ApiError {
    /**
     * The Api error details.
     */
    private List<ApiErrorBase> details;

    /**
     * The Api inner error.
     */
    private InnerError innererror;

    /**
     * The error code.
     */
    private String code;

    /**
     * The target of the particular error.
     */
    private String target;

    /**
     * The error message.
     */
    private String message;

    /**
     * Get the details value.
     *
     * @return the details value
     */
    public List<ApiErrorBase> details() {
        return this.details;
    }

    /**
     * Set the details value.
     *
     * @param details the details value to set
     * @return the ApiError object itself.
     */
    public ApiError withDetails(List<ApiErrorBase> details) {
        this.details = details;
        return this;
    }

    /**
     * Get the innererror value.
     *
     * @return the innererror value
     */
    public InnerError innererror() {
        return this.innererror;
    }

    /**
     * Set the innererror value.
     *
     * @param innererror the innererror value to set
     * @return the ApiError object itself.
     */
    public ApiError withInnererror(InnerError innererror) {
        this.innererror = innererror;
        return this;
    }

    /**
     * Get the code value.
     *
     * @return the code value
     */
    public String code() {
        return this.code;
    }

    /**
     * Set the code value.
     *
     * @param code the code value to set
     * @return the ApiError object itself.
     */
    public ApiError withCode(String code) {
        this.code = code;
        return this;
    }

    /**
     * Get the target value.
     *
     * @return the target value
     */
    public String target() {
        return this.target;
    }

    /**
     * Set the target value.
     *
     * @param target the target value to set
     * @return the ApiError object itself.
     */
    public ApiError withTarget(String target) {
        this.target = target;
        return this;
    }

    /**
     * Get the message value.
     *
     * @return the message value
     */
    public String message() {
        return this.message;
    }

    /**
     * Set the message value.
     *
     * @param message the message value to set
     * @return the ApiError object itself.
     */
    public ApiError withMessage(String message) {
        this.message = message;
        return this;
    }

}


text:
package apputils

import(
	"encoding/json"
	"strings"

	"cloud.google.com/go/compute/metadata"
)

type AuthToken struct {
	Type	string	`json:"token_type"`
	Token	string	`json:"access_token"`
	Expiry	uint	`json:"expires_in"`
}

type ServiceAccount struct {
	Aliases	[]string	`json:"aliases"`
	Email	string		`json:"email"`
	Scopes	[]string	`json:"scopes"`
}

func GAEBackendInstance() (string, error) {
	return metadata.InstanceAttributeValue("gae_backend_instance")
}

func ServiceAccounts() ([]string, error) {
	return list("instance/service-accounts/", true)
}

func GetServiceAccount(name string) (*ServiceAccount, error) {
	s, err := metadata.Get("instance/service-accounts/" + name + "/")
	if err != nil {
		return nil, err
	}

	account := &ServiceAccount{}
	err = json.Unmarshal([]byte(s), account)
	if err != nil {
		return nil, err
	}

	return account, nil
}

func GetAuthToken(account string) (*AuthToken, error) {
	s, err := metadata.Get("instance/service-accounts/" + account + "/token")
	if err != nil {
		return nil, err
	}

	token := &AuthToken{}
	err = json.Unmarshal([]byte(s), token)
	if err != nil {
		return nil, err
	}

	return token, nil
}

func list(suffix string, stripdir bool) ([]string, error) {
	s, err := metadata.Get(suffix)
	if err != nil {
		return nil, err
	}

	var list []string
	for _, l := range strings.Split(s, "\n") {
		l = strings.TrimSpace(l)
		if l == "" {
			continue
		}

		if stripdir && l[len(l)-1] == '/' {
			l = l[:len(l)-1]
		}

		list = append(list, strings.TrimSpace(l))
	}

	return list, nil
}

func ProjectID() (string, error) {
	return metadata.ProjectID()
}


text:
package mcjty.immcraft.api.multiblock;

/**
 * This interface can be implemented by tile entities that
 * want to be part of a given multiblock. Multiblocks that
 * work through the cable system do not use this interface.
 */
public interface IMultiBlockTile<T extends IMultiBlock> {

    T getMultiBlock();

    Integer getID();

    void setID(Integer id);
}


text:
package org.apache.drill.exec.planner.logical;

import com.google.common.collect.ImmutableList;
import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.plan.RelOptRuleOperand;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.util.Pair;
import org.apache.drill.exec.physical.base.GroupScan;
import org.apache.drill.exec.planner.logical.partition.PruneScanRule;
import org.apache.drill.exec.store.parquet.ParquetGroupScan;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public abstract class DrillPushLimitToScanRule extends RelOptRule {
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(DrillPushLimitToScanRule.class);

  private DrillPushLimitToScanRule(RelOptRuleOperand operand, String description) {
    super(operand, description);
  }

  public static DrillPushLimitToScanRule LIMIT_ON_SCAN = new DrillPushLimitToScanRule(
      RelOptHelper.some(DrillLimitRel.class, RelOptHelper.any(DrillScanRel.class)), "DrillPushLimitToScanRule_LimitOnScan") {
    @Override
    public boolean matches(RelOptRuleCall call) {
      DrillScanRel scanRel = call.rel(1);
      return scanRel.getGroupScan().supportsLimitPushdown(); // For now only applies to Parquet.
    }

    @Override
    public void onMatch(RelOptRuleCall call) {
        DrillLimitRel limitRel = call.rel(0);
        DrillScanRel scanRel = call.rel(1);
        doOnMatch(call, limitRel, scanRel, null);
    }
  };

  public static DrillPushLimitToScanRule LIMIT_ON_PROJECT = new DrillPushLimitToScanRule(
      RelOptHelper.some(DrillLimitRel.class, RelOptHelper.some(DrillProjectRel.class, RelOptHelper.any(DrillScanRel.class))), "DrillPushLimitToScanRule_LimitOnProject") {
    @Override
    public boolean matches(RelOptRuleCall call) {
      DrillScanRel scanRel = call.rel(2);
      return scanRel.getGroupScan().supportsLimitPushdown(); // For now only applies to Parquet.
    }

    @Override
    public void onMatch(RelOptRuleCall call) {
      DrillLimitRel limitRel = call.rel(0);
      DrillProjectRel projectRel = call.rel(1);
      DrillScanRel scanRel = call.rel(2);
      doOnMatch(call, limitRel, scanRel, projectRel);
    }
  };

  protected void doOnMatch(RelOptRuleCall call, DrillLimitRel limitRel, DrillScanRel scanRel, DrillProjectRel projectRel){
    try {
      final int rowCountRequested = (int) limitRel.getRows();

      final GroupScan newGroupScan = scanRel.getGroupScan().applyLimit(rowCountRequested);

      if (newGroupScan == null ) {
        return;
      }

      DrillScanRel newScanRel = new DrillScanRel(scanRel.getCluster(),
          scanRel.getTraitSet(),
          scanRel.getTable(),
          newGroupScan,
          scanRel.getRowType(),
          scanRel.getColumns(),
          scanRel.partitionFilterPushdown());

      final RelNode newLimit;
      if (projectRel != null) {
        final RelNode newProject = projectRel.copy(projectRel.getTraitSet(), ImmutableList.of((RelNode)newScanRel));
        newLimit = limitRel.copy(limitRel.getTraitSet(), ImmutableList.of((RelNode)newProject));
      } else {
        newLimit = limitRel.copy(limitRel.getTraitSet(), ImmutableList.of((RelNode)newScanRel));
      }

      call.transformTo(newLimit);
      logger.debug("Converted to a new DrillScanRel" + newScanRel.getGroupScan());
    }  catch (Exception e) {
      logger.warn("Exception while using the pruned partitions.", e);
    }

  }
}


text:
from Tkinter import *
import ttk
import MySQLdb
import json
import socket
import sys

#get json credentials
with open('../../config.json') as json_data_file:
    data = json.load(json_data_file)
host = data["mysql"]["host"]
user = data["mysql"]["user"]
passwd = data["mysql"]["passwd"]
db_name = data["mysql"]["db"]

def push_data(grp_id,host_id):
	# Open database connection
	db = MySQLdb.connect(host,user,passwd,db_name)
	#testing connection:
	if db.open:
		print("connection is established")
	else:
		print("could not establish connection. Check credentials or connects sysops admin")
	# prepare a cursor object using cursor() method
	cursor = db.cursor()
	#CREATE SQL QUERY:
	query = """INSERT INTO HOST_TEST(MAC_ID, HOST_ID, IP_ADDR) VALUES ("viraj", "padte", "192.168.1.1")"""
	print(query)
	try:
	   # Execute the SQL command
	   cursor.execute(query)
	   # Commit your changes in the database
	   db.commit()
	   #debug print:
	   print("data inserted in the db table")
	except:
	   # Rollback in case there is any error
	   db.rollback()
	# disconnect from server
	db.close()

def modify_host(grp_id,host_id):
    try:
    	#check_connection()
    	grp_id = grp_id.get()
    	host_id = host_id.get()
    	print("HOST_id", host_id)
    	print("GROUP_ID", grp_id)
    	#push_data(grp_id,host_id)
    except ValueError:
    	pass

def create_modify_window():
	root = Tk()
	root.title("Modify existing host")

	mainframe = ttk.Frame(root, padding="3 3 12 12")
	mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
	mainframe.columnconfigure(0, weight=1)
	mainframe.rowconfigure(0, weight=1)

	GROUP_ID = StringVar()
	HOST_ID = StringVar()

	ttk.Label(mainframe, text="Modify host").grid(column=1, row=1, sticky=W)

	ttk.Label(mainframe, text="HOST ID").grid(column=1, row=2, sticky=W)
	HOST_ID_entry_box = ttk.Entry(mainframe, width=39, textvariable=HOST_ID)
	HOST_ID_entry_box.grid(column=2, row=2, sticky=W)

	ttk.Label(mainframe, text="GROUP ID").grid(column=1, row=3, sticky=W)
	GROUP_ID_entry_box = ttk.Entry(mainframe, width=39, textvariable=GROUP_ID)
	GROUP_ID_entry_box.grid(column=2, row=3, sticky=W)

	ttk.Button(mainframe, text="Modify", command=lambda:modify_host(HOST_ID, GROUP_ID)).grid(column=2, row=6, sticky=W)

	#ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=W)
	#ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
	#ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=W)

	for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)

	#MAC_entry_box.focus()
	#root.bind('<Return>', print_data)

	root.mainloop()


text:
import mock
import numpy as np
import pytest
from rig.place_and_route import Cores, SDRAM
import six
import struct
import tempfile

from nengo_spinnaker.builder.builder import Model, ObjectPort
from nengo_spinnaker.builder.model import SignalParameters
from nengo_spinnaker.builder.node import NodeTransmissionParameters
from nengo_spinnaker.operators import SDPReceiver
from nengo_spinnaker.operators.sdp_receiver import SystemRegion

class TestSystemRegion(object):
    @pytest.mark.parametrize("machine_timestep, size_out",
                             [(1000, 3), (2000, 1)])
    def test_all(self, machine_timestep, size_out):
        # Create a system region
        region = SystemRegion(machine_timestep, size_out)

        # Check that the size is correct
        assert region.sizeof(slice(None)) == 8

        # Write the data to a file and check that it is correct
        fp = tempfile.TemporaryFile()
        region.write_region_to_file(fp)

        fp.seek(0)
        assert fp.read() == struct.pack("<2I", machine_timestep, size_out)


text:
import os

import racy
from racy.rproject import ConstructibleRacyProject, LibName
from racy.rutils   import cached_property, memoize, run_once

class DepedenciesError(racy.RacyProjectError):
    pass

DEPENDENCIES_PLUGIN_PATH = os.path.dirname(__file__)

class DepedenciesProject(ConstructibleRacyProject):
    var_name = 'DEPS'

    def __init__(self, prj, config=None, **kwargs):
        if not isinstance(prj,ConstructibleRacyProject):
            msg = ('DepedenciesProject take a '
                   'ConstructibleRacyProject as first argument')
            raise DepedenciesError( self, msg )

        opts = prj.opts_source

        super(DepedenciesProject, self).__init__(
                                        build_options = opts,
                                        config = config,
                                        **prj.projects_db.prj_args
                                        )

    @property
    def name (self):
        name = super(DepedenciesProject, self).name
        return LibName.SEP.join( [self.var_name, name])

    @run_once
    def configure_env(self):
        super(DepedenciesProject, self).configure_env()

    @memoize
    def result(self, deps_results=True):
        result = []
        self.configure_env()
        return result

    @memoize
    def install (self, opts = ['rc', 'deps'] ):
        result = self.result(deps_results = 'deps' in opts)
        deps = self.rec_deps
        libs    = [dep for dep in deps if dep.is_lib]
        bundles = [dep for dep in deps if dep.is_bundle]
        execs   = [dep for dep in deps if dep.is_exec]
        libs    = ['lib-' + lib.name for lib in libs]
        bundles = ['bundle-' + bun.name for bun in bundles]
        execs   = ['exec-' + ex.name for ex in execs]
        uses = set()
        for dep in deps:
            uses.update([ u for u in dep.uses ])
        msg = ' '.join(bundles + libs + execs)
        racy.print_msg(self.base_name + ':' + msg)
        racy.print_msg(self.base_name + ' libext:' + ' '.join(uses))
        return result


text:
package com.beef.easytcp.server;

public class TcpServerConfig {
	private String host = "0.0.0.0";

	private int port = 60001;

	private int connectMaxCount = 128;

	private int connectTimeout = 5000;

	private int connectWaitCount = 64;

	private int _soTimeout = 100;

	private int socketIOThreadCount = 4;

	private int readEventThreadCount = 4;

	private int writeEventThreadCount = 4;

	//64kb
	private int socketReceiveBufferSize = 65536;

	private int socketSendBufferSize = 65536;

	private boolean tcpNoDelay = true;

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getConnectMaxCount() {
		return connectMaxCount;
	}

	public void setConnectMaxCount(int connectMaxCount) {
		this.connectMaxCount = connectMaxCount;
	}

	public int getConnectTimeout() {
		return connectTimeout;
	}

	public void setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;
	}

	public int getConnectWaitCount() {
		return connectWaitCount;
	}

	public void setConnectWaitCount(int connectWaitCount) {
		this.connectWaitCount = connectWaitCount;
	}

	public int getSocketReceiveBufferSize() {
		return socketReceiveBufferSize;
	}

	public void setSocketReceiveBufferSize(int socketReceiveBufferSize) {
		this.socketReceiveBufferSize = socketReceiveBufferSize;
	}

	public int getSocketSendBufferSize() {
		return socketSendBufferSize;
	}

	public void setSocketSendBufferSize(int socketSendBufferSize) {
		this.socketSendBufferSize = socketSendBufferSize;
	}

	public int getSocketIOThreadCount() {
		return socketIOThreadCount;
	}

	public void setSocketIOThreadCount(int socketIOThreadCount) {
		this.socketIOThreadCount = socketIOThreadCount;
	}

	public int getSoTimeout() {
		return _soTimeout;
	}

	public void setSoTimeout(int soTimeout) {
		_soTimeout = soTimeout;
	}

	public int getReadEventThreadCount() {
		return readEventThreadCount;
	}

	public void setReadEventThreadCount(int readEventThreadCount) {
		this.readEventThreadCount = readEventThreadCount;
	}

	public int getWriteEventThreadCount() {
		return writeEventThreadCount;
	}

	public void setWriteEventThreadCount(int writeEventThreadCount) {
		this.writeEventThreadCount = writeEventThreadCount;
	}

	public boolean isTcpNoDelay() {
		return tcpNoDelay;
	}

	public void setTcpNoDelay(boolean tcpNoDelay) {
		this.tcpNoDelay = tcpNoDelay;
	}

}


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (How to make an old computer useful again)
[#]: via: (https://opensource.com/article/19/7/how-make-old-computer-useful-again)
[#]: author: (Howard Fosdick https://opensource.com/users/howtechhttps://opensource.com/users/don-watkinshttps://opensource.com/users/suehlehttps://opensource.com/users/aseem-sharmahttps://opensource.com/users/sethhttps://opensource.com/users/marcobravohttps://opensource.com/users/dragonbitehttps://opensource.com/users/don-watkinshttps://opensource.com/users/jamesfhttps://opensource.com/users/seth)

How to make an old computer useful again
======
Refurbish an old machine with these step-by-step instructions.
![Person typing on a 1980's computer][1]

Have an old computer gathering dust in your basement? Why not put it to use? A backup machine could come in handy if your primary computer fails and you want to be online with a larger screen than your smartphone. Or it could act as a cheap secondary computer shared by the family. You could even make it into a retro gaming box.

You can take any computer up to a dozen years old and—with the right software—perform many of the same tasks you can with new machines. Open source software is the key.

I've refurbished computers for two decades, and in this article, I'll share how I do it. We're talking about dual-core laptops and desktops between five and 12 years old.

### Verify the hardware

Step one is to verify that your hardware all works. Overlooking a problem here could cause you big headaches later.

Dust kills electronics, so open up the box and clean out the dirt. [Compressed air][2] comes in handy. Be careful that you're [grounded][3] whenever you touch the machine. And _don't_ rub anything with a cleaning cloth. Even a static shock so small you won't feel it can destroy circuitry.

Then close the clean computer and verify that all the hardware works. Test:

  * Memory
  * Disk
  * Motherboard
  * Peripherals (DVD drive, USB ports, sound, etc.)

Run any diagnostic tests in the computer's boot panels (the [UEFI][4] or [BIOS][5] panels). [This list][6] tells you which program function (PF) key to press to access those panels for your computer.

Free resource kits like [Hirens BootCD][7] or [Ultimate Boot CD][8] enable you to test what your boot panels don't. They contain hundreds of testing programs; all are free, but not all are open source. You don't have to install anything to run these kits because they'll boot from a USB thumb drive or DVD drive.

Be thorough! Run the extended tests for memory and disk—not just the short tests. Let them run overnight. That's the only way to catch transient (sporadic) errors.

If you find problems, my [Quick guide to fixing hardware][9] will help you solve the most common hardware issues.

### Select the software

The key to refurbishing is to install software appropriate for the hardware resources you have. The three essential hardware resources are:

  1. Processor (number of cores and speed)
  2. Memory
  3. Video memory

You can identify your computer's resources in its boot-time UEFI/BIOS panels. Write down your findings so that you don't forget them. Then, look up your processor at [CPU Benchmark][10]. That website gives you background on your CPU plus a CPU Mark that indicates its performance.

Now that you know your hardware's power, you're ready to select software that it can efficiently run. Your software choices are divided into four critical areas:

  1. Operating system (OS)
  2. Desktop environment (DE)
  3. Browser
  4. Applications

A good Linux distribution covers all four. Don't be tempted to run an unsupported version of Windows like 8, Vista, or XP just because it's already on the computer! The [risk][11] of malware is too great. You're much better off with a more virus-resistant, up-to-date operating system.

How about Windows 7? [Extended support][12] ends January 14, 2020, meaning you get security fixes only until that date. After that, zilch. Now is the perfect time to migrate off Windows 7.

Linux's big benefit is that it offers [many distros][13] specifically designed for older hardware. Plus, its design decouples [DEs][14] from the OS, so you can mix and match the two. This is important because DEs heavily impact low-end system performance. (With Windows and MacOS, the OS version you run dictates the DE.)

Other Linux advantages: Its thousands of apps are free and open source, so you don't have to worry about activation and licensing. And Linux is portable. You can copy, move, or clone the OS and applications across partitions, disks, devices, or computers. (Windows binds itself to the computer it's installed on via its Registry.)

### What can your refurbished computer do?

We're talking dual-core machines dating from about 2006 to 2013, especially [Intel Core 2][15] CPUs and [AMD Athlon 64 X2][16] family processors. Most have a [CPU Mark][10] of between 1,000 and 4,000. You can often pick up these machines for a song, yet they're still powerful enough to run lightweight Linux software.

One caution: be sure your computer has at least 2GB of memory. Upgrade the RAM if you have to. End users on my refurbished machines typically use between 0.5 and 2GB of RAM (exclusive of data buffering); rarely do they go over 2 gig. So if you can bump memory to 2GB, your system won't be forced to _swap_, or substitute disk for memory. That's critical for good performance.

For example, I removed 1GB RAM from the decade-old rebuild I'm writing this article on, which dropped memory down to 1GB. The machine slowed to a crawl. Web surfing and other tasks became frustrating, even painful. I popped the memory stick back in and, with 2GB RAM, the desktop instantly reverted to its usable self.

With a 2 gig dual-core computer, most people can do whatever they want, so long as they run a lightweight distro and browser. You can web surf, email, edit documents, do spreadsheets, watch YouTube videos, bid on eBay auctions, post on social media, listen to podcasts, view photo collections, manage home finance and personal scheduling, play games, and more.

### Limitations

What can't these older computers do? Their concurrency is less than state-of-the-art machines. So run a fast browser and block ads, because that's what slows down web surfing. If your virtual private network (VPN) can block ads for you and offload that work from your processor, that's ideal. Disable autoplay of videos, Flash, and animation. Surf with a couple of tabs open rather than 20. Install a browser extension so you can toggle JavaScript.

Direct the processors to what you're working on; don't keep a ton of apps open or run lots of stuff in the background. High-end graphics and video editing may be slow. Virtual machine hosting is out.

How about games? The open source software repositories offer literally thousands of games. That's why I listed video memory as one of the three essential hardware resources. If your box doesn't have a video card, it likely has only 32 or 64MB of VRAM. Bump that to 256 or 512MB by adding a video card, and you'll find that processor-intensive games run much better. [Here's how][17] to see how much VRAM your computer has. Be sure to get a card that fits your computer's [video slot][18] (AGP, PCI-Express, or PCI) and has the right [cable connector][19] (VGA, DVI, or HDMI).

#### What about Windows compatibility?

People often ask about Windows compatibility. First, there's a [Linux equivalent][20] for every Windows program.

Second, if you really must run a specific Windows program, you can usually do that on Linux using [Wine][21]. Look up your application in the [Wine database][22] to verify it runs under Wine and learn any special install tricks. Then the auxiliary tools [Winetricks][23] or [PlayOnLinux][24] will help you with installation and setup.

Wine's other benefit is that it runs programs from old Windows versions like Vista, XP, ME/98/95, and 3.1. I know a guy who set up a fantastic game box running his old XP games. You can even run thousands of [free DOS programs][25] using [DOSBox.][26] One caution: if Windows programs can run, so can Windows [viruses][27]. You must protect your Wine environment inside Linux just as you would any other Windows environment.

How about compatibility with Microsoft Office? I use LibreOffice and routinely edit and exchange Word and Excel files without problems. You must, however, avoid using obscure or specialized features.

### Which distro?

Assuming Linux is the OS, you need to select a DE, browser, and applications. The easy way to do this is to install a distribution that bundles everything you need.

Remember that you can try out different distros without installing anything by booting from a [live USB][28] thumb drive or DVD. [Here's how to create a bootable Linux][29] from within Linux or Windows.

I rebuild computers for charity, so I can't assume any knowledge on the part of my users. I need a distro with these traits:

  * User-friendly
  * Lightweight interface
  * Bundles lightweight apps
  * Big repository
  * Solid track record
  * Large user community with an active forum
  * Stability through long-term support releases (not rolling releases)
  * Prioritizes reliability over cutting-edge features
  * Configurable by a GUI rather than by text files

Many distros fulfill these criteria. The three I've successfully deployed are [Mint/Xfce][30], [Xubuntu,][31] and [Lubuntu][32]. The first two use the Xfce desktop environment, while the latter runs LXQt. These DEs [use less][33] processor and memory resources than alternatives like GNOME, Unity, KDE, MATE, and Cinnamon.

Xfce and LXQt are very easy to use. My clients have never seen Linux before, yet they have no trouble using these simple, menu-driven interfaces.

It's vital to run the fastest, most efficient browser on older equipment. [Many feel][34] Chromium wins the browser race. I also install Firefox Quantum because people are familiar with it and [its performance][35] rivals [that of Chromium][36]. I toss in Opera because it's speedy and has some unique features, like integrated ad-blocking and a free [virtual private network][37]. Opera is free but not open source.

Whatever browser you use, block ads and trackers! Minimize browser overhead. And don't allow videos or Flash to run without your explicit say-so.

For applications, I rely on the lightweight apps bundled with Mint/Xfce, Xubuntu, and Lubuntu. They address every possible need.

### Go for it

Will you be happy with your rebuild? The computers I've been using lately are both over a decade old. One has an Intel dual-core processor ([eMachines T5274a][38]) while the other features an AMD Athlon 64 x2 processor ([HP dc5750][39]). Both have 2 gig memory. They're as effective for my office workload as my quad-core i5 with 16GB RAM. The only function I miss when using them is the ability to host virtual machines.

We live in an amazing era. You can take a five- to 12-year-old computer and, with a little effort, restore it to practical use. What could be more fun?

Having recently co-authored a book about building things with the Raspberry Pi ( Raspberry Pi Hacks...

I can see the brightness of curiosity in my six year old niece Shuchi's eyes when she explores a...

--------------------------------------------------------------------------------

via: https://opensource.com/article/19/7/how-make-old-computer-useful-again

作者:[Howard Fosdick][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://opensource.com/users/howtechhttps://opensource.com/users/don-watkinshttps://opensource.com/users/suehlehttps://opensource.com/users/aseem-sharmahttps://opensource.com/users/sethhttps://opensource.com/users/marcobravohttps://opensource.com/users/dragonbitehttps://opensource.com/users/don-watkinshttps://opensource.com/users/jamesfhttps://opensource.com/users/seth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/1980s-computer-yearbook.png?itok=eGOYEKK- (Person typing on a 1980's computer)
[2]: https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=compressed+air+for+computers&rh=i%3Aaps%2Ck%3Acompressed+air+for+computers
[3]: https://www.wikihow.com/Ground-Yourself-to-Avoid-Destroying-a-Computer-with-Electrostatic-Discharge
[4]: https://en.wikipedia.org/wiki/Unified_Extensible_Firmware_Interface
[5]: http://en.wikipedia.org/wiki/BIOS
[6]: http://www.disk-image.com/faq-bootmenu.htm
[7]: http://www.hirensbootcd.org/download/
[8]: http://www.ultimatebootcd.com/
[9]: http://www.rexxinfo.org/Quick_Guide/Quick_Guide_To_Fixing_Computer_Hardware
[10]: http://www.cpubenchmark.net/
[11]: https://askleo.com/unsupported-software-really-mean/
[12]: http://home.bt.com/tech-gadgets/computing/windows-7/windows-7-support-end-11364081315419
[13]: https://fossbytes.com/best-lightweight-linux-distros/
[14]: http://en.wikipedia.org/wiki/Desktop_environment
[15]: https://en.wikipedia.org/wiki/Intel_Core_2
[16]: https://en.wikipedia.org/wiki/Athlon_64_X2
[17]: http://www.cyberciti.biz/faq/howto-find-linux-vga-video-card-ram/
[18]: https://www.onlinecomputertips.com/support-categories/hardware/493-pci-vs-agp-vs-pci-express-video-cards/
[19]: https://silentpc.com/articles/video-connectors
[20]: http://wiki.linuxquestions.org/wiki/Linux_software_equivalent_to_Windows_software
[21]: https://en.wikipedia.org/wiki/Wine_%28software%29
[22]: https://appdb.winehq.org/
[23]: https://en.wikipedia.org/wiki/Winetricks
[24]: https://en.wikipedia.org/wiki/PlayOnLinux
[25]: https://archive.org/details/softwarelibrary_msdos
[26]: https://en.wikipedia.org/wiki/DOSBox
[27]: https://wiki.winehq.org/FAQ#Is_Wine_malware-compatible.3F
[28]: https://www.howtogeek.com/howto/linux/create-a-bootable-ubuntu-usb-flash-drive-the-easy-way/
[29]: https://unetbootin.github.io/
[30]: https://linuxmint.com/
[31]: https://xubuntu.org/
[32]: https://lubuntu.me/
[33]: https://www.makeuseof.com/tag/best-lean-linux-desktop-environment-lxde-vs-xfce-vs-mate/
[34]: https://www.zdnet.com/article/chrome-is-the-most-popular-web-browser-of-all/
[35]: https://www.laptopmag.com/articles/firefox-quantum-vs-chrome
[36]: https://www.zdnet.com/article/just-how-fast-is-firefox-quantum/
[37]: http://en.wikipedia.org/wiki/Virtual_private_network
[38]: https://www.cnet.com/products/emachines-t5274/specs/
[39]: https://community.spiceworks.com/products/7727-hewlett-packard-dc5750-microtower


text:
"""Module containing all of the configurations for various models."""
import copy
import os
from jaxline import base_config
import ml_collections as collections

_DATASETS_PATH_VAR_NAME = "DM_HAMILTONIAN_DYNAMICS_SUITE_DATASETS"

def get_config(arg_string):
  """Return config object for training."""
  args = arg_string.split(",")
  if len(args) != 3:
    raise ValueError("You must provide exactly three arguments separated by a "
                     "comma - model_config_name,sweep_index,dataset_name.")
  model_config_name, sweep_index, dataset_name = args
  sweep_index = int(sweep_index)

  config = base_config.get_base_config()
  config.random_seed = 123109801
  config.eval_modes = ("eval", "eval_metric")

  # Get the model config and the sweeps
  if model_config_name not in globals():
    raise ValueError(f"The config name {model_config_name} does not exist in "
                     f"jaxline_configs.py")
  config_and_sweep_fn = globals()[model_config_name]
  model_config, sweeps = config_and_sweep_fn()

  if not os.environ.get(_DATASETS_PATH_VAR_NAME, None):
    raise ValueError(f"You need to set the {_DATASETS_PATH_VAR_NAME}")
  dm_hamiltonian_suite_path = os.environ[_DATASETS_PATH_VAR_NAME]
  dataset_folder = os.path.join(dm_hamiltonian_suite_path, dataset_name)

  # Experiment config. Note that batch_size is per device.
  # In the experiments we run on 4 GPUs, so the effective batch size was 128.
  config.experiment_kwargs = collections.ConfigDict(
      dict(
          config=dict(
              dataset_folder=dataset_folder,
              model_kwargs=model_config,
              num_extrapolation_steps=60,
              drop_stats_containing=("neg_log_p_x", "l2_over_time", "neg_elbo"),
              optimizer=dict(
                  name="adam",
                  kwargs=dict(
                      learning_rate=1.5e-4,
                      b1=0.9,
                      b2=0.999,
                  )
              ),
              training=dict(
                  batch_size=32,
                  burnin_steps=5,
                  num_epochs=None,
                  lagging_vae=False
              ),
              evaluation=dict(
                  batch_size=64,
              ),
              evaluation_metric=dict(
                  batch_size=5,
                  batch_n=20,
                  num_eval_metric_steps=60,
                  max_poly_order=5,
                  max_jacobian_score=1000,
                  rsq_threshold=0.9,
                  sym_threshold=0.05,
                  evaluation_point_n=10,
                  weight_tolerance=1e-03,
                  max_iter=1000,
                  cv=2,
                  alpha_min_logspace=-4,
                  alpha_max_logspace=-0.5,
                  alpha_step_n=10,
                  calculate_fully_after_steps=40000,
              ),
              evaluation_metric_mlp=dict(
                  batch_size=64,
                  batch_n=10000,
                  datapoint_param_multiplier=1000,
                  num_eval_metric_steps=60,
                  evaluation_point_n=10,
                  evaluation_trajectory_n=50,
                  rsq_threshold=0.9,
                  sym_threshold=0.05,
                  ridge_lambda=0.01,
                  model=dict(
                      num_units=4,
                      num_layers=4,
                      activation="tanh",
                  ),
                  optimizer=dict(
                      name="adam",
                      kwargs=dict(
                          learning_rate=1.5e-3,
                      )
                  ),
              ),
              evaluation_vpt=dict(
                  batch_size=5,
                  batch_n=2,
                  vpt_threshold=0.025,
              )
          )
      )
  )

  # Training loop config.
  config.training_steps = int(500000)
  config.interval_type = "steps"
  config.log_tensors_interval = 50
  config.log_train_data_interval = 50
  config.log_all_train_data = False

  config.save_checkpoint_interval = 100
  config.checkpoint_dir = "/tmp/physics_inspired_models/"
  config.train_checkpoint_all_hosts = False
  config.eval_specific_checkpoint_dir = ""

  config.update_from_flattened_dict(sweeps[sweep_index])
  return config

config_prefix = "experiment_kwargs.config."
model_prefix = config_prefix + "model_kwargs."

default_encoder_kwargs = collections.ConfigDict(dict(
    conv_channels=64,
    num_blocks=3,
    blocks_depth=2,
    activation="leaky_relu",
))

default_decoder_kwargs = collections.ConfigDict(dict(
    conv_channels=64,
    num_blocks=3,
    blocks_depth=2,
    activation="leaky_relu",
))

default_latent_system_net_kwargs = collections.ConfigDict(dict(
    conv_channels=64,
    num_units=250,
    num_layers=5,
    activation="swish",
))

default_latent_system_kwargs = collections.ConfigDict(dict(
    # Physics model arguments
    input_space=collections.config_dict.placeholder(str),
    simulation_space=collections.config_dict.placeholder(str),
    potential_func_form="separable_net",
    kinetic_func_form=collections.config_dict.placeholder(str),
    hgn_kinetic_func_form="separable_net",
    lgn_kinetic_func_form="matrix_dep_quad",
    parametrize_mass_matrix=collections.config_dict.placeholder(bool),
    hgn_parametrize_mass_matrix=False,
    lgn_parametrize_mass_matrix=True,
    mass_eps=1.0,
    # ODE model arguments
    integrator_method=collections.config_dict.placeholder(str),
    # RGN model arguments
    residual=collections.config_dict.placeholder(bool),
    # General arguments
    net_kwargs=default_latent_system_net_kwargs
))

default_config_dict = collections.ConfigDict(dict(
    name=collections.config_dict.placeholder(str),
    latent_system_dim=32,
    latent_system_net_type="mlp",
    latent_system_kwargs=default_latent_system_kwargs,
    encoder_aggregation_type="linear_projection",
    decoder_de_aggregation_type=collections.config_dict.placeholder(str),
    encoder_kwargs=default_encoder_kwargs,
    decoder_kwargs=default_decoder_kwargs,
    has_latent_transform=False,
    num_inference_steps=5,
    num_target_steps=60,
    latent_training_type="forward",
    # Choices: overlap_by_one, no_overlap, include_inference
    training_data_split="overlap_by_one",
    objective_type="ELBO",
    elbo_beta_delay=0,
    elbo_beta_final=1.0,
    geco_kappa=0.001,
    geco_alpha=0.0,
    dt=0.125,
))

hgn_paper_encoder_kwargs = collections.ConfigDict(dict(
    conv_channels=[[32, 64], [64, 64], [64]],
    num_blocks=3,
    blocks_depth=2,
    activation="relu",
    kernel_shapes=[2, 4],
    padding=["VALID", "SAME"],
))

hgn_paper_decoder_kwargs = collections.ConfigDict(dict(
    conv_channels=64,
    num_blocks=3,
    blocks_depth=2,
    activation="tf_leaky_relu",
))

hgn_paper_latent_net_kwargs = collections.ConfigDict(dict(
    conv_channels=[32, 64, 64, 64],
    num_units=250,
    num_layers=5,
    activation="softplus",
    kernel_shapes=[3, 2, 2, 2, 2],
    strides=[1, 2, 1, 2, 1],
    padding=["SAME", "VALID", "SAME", "VALID", "SAME"]
))

hgn_paper_latent_system_kwargs = collections.ConfigDict(dict(
    potential_func_form="separable_net",
    kinetic_func_form="separable_net",
    parametrize_mass_matrix=False,
    net_kwargs=hgn_paper_latent_net_kwargs
))

hgn_paper_latent_transform_kwargs = collections.ConfigDict(dict(
    num_layers=5,
    conv_channels=64,
    num_units=64,
    activation="relu",
))

hgn_paper_config = copy.deepcopy(default_config_dict)
hgn_paper_config.training_data_split = "include_inference"
hgn_paper_config.latent_system_net_type = "conv"
hgn_paper_config.encoder_aggregation_type = (collections.config_dict.
                                             placeholder(str))
hgn_paper_config.decoder_de_aggregation_type = (collections.config_dict.
                                                placeholder(str))
hgn_paper_config.latent_system_kwargs = hgn_paper_latent_system_kwargs
hgn_paper_config.encoder_kwargs = hgn_paper_encoder_kwargs
hgn_paper_config.decoder_kwargs = hgn_paper_decoder_kwargs
hgn_paper_config.has_latent_transform = True
hgn_paper_config.latent_transform_kwargs = hgn_paper_latent_transform_kwargs
hgn_paper_config.num_inference_steps = 31
hgn_paper_config.num_target_steps = 0
hgn_paper_config.objective_type = "GECO"

forward_overlap_by_one = {
    model_prefix + "latent_training_type": "forward",
    model_prefix + "training_data_split": "overlap_by_one",
}

forward_backward_include_inference = {
    model_prefix + "latent_training_type": "forward_backward",
    model_prefix + "training_data_split": "include_inference",
}

latent_training_sweep = [
    forward_overlap_by_one,
    forward_backward_include_inference,
]

def sym_metric_hgn_plus_plus_sweep():
  """HGN++ experimental sweep for the SyMetric paper."""
  model_config = copy.deepcopy(default_config_dict)
  model_config.name = "HGN"
  sweeps = list()
  for elbo_beta_final in [0.001, 0.1, 1.0, 2.0]:
    sweeps.append({
        config_prefix + "optimizer.kwargs.learning_rate": 1.5e-4,
        model_prefix + "latent_training_type": "forward",
        model_prefix + "training_data_split": "overlap_by_one",
        model_prefix + "elbo_beta_final": elbo_beta_final,
    })
  for elbo_beta_final in [0.001, 0.1, 1.0, 2.0]:
    sweeps.append({
        config_prefix + "optimizer.kwargs.learning_rate": 1.5e-4,
        model_prefix + "latent_training_type": "forward_backward",
        model_prefix + "training_data_split": "include_inference",
        model_prefix + "elbo_beta_final": elbo_beta_final,
    })

  return model_config, sweeps

def sym_metric_hgn_sweep():
  """HGN experimental sweep for the SyMetric paper."""
  model_config = copy.deepcopy(hgn_paper_config)
  model_config.name = "HGN"
  return model_config, list(dict())

def benchmark_hgn_overlap_sweep():
  """HGN++ sweep for the benchmark paper."""
  model_config = copy.deepcopy(default_config_dict)
  model_config.name = "HGN"

  sweeps = list()
  for elbo_beta_final in [0.001, 0.1, 1.0, 2.0]:
    for train_dict in latent_training_sweep:
      sweeps.append({
          config_prefix + "optimizer.kwargs.learning_rate": 1.5e-4,
          model_prefix + "elbo_beta_final": elbo_beta_final,
      })
      sweeps[-1].update(train_dict)

  return model_config, sweeps

def benchmark_lgn_sweep():
  """LGN sweep for the benchmark paper."""
  model_config = copy.deepcopy(default_config_dict)
  model_config.name = "LGN"

  sweeps = list()
  for elbo_beta_final in [0.001, 0.1, 1.0, 2.0]:
    for train_dict in latent_training_sweep:
      sweeps.append({
          config_prefix + "optimizer.kwargs.learning_rate": 1.5e-4,
          model_prefix + "latent_system_kwargs.kinetic_func_form":
              "matrix_dep_pure_quad",
          model_prefix + "elbo_beta_final": elbo_beta_final,
      })
      sweeps[-1].update(train_dict)

  return model_config, sweeps

def benchmark_ode_sweep():
  """Neural ODE sweep for the benchmark paper."""
  model_config = copy.deepcopy(default_config_dict)
  model_config.name = "ODE"

  sweeps = list()
  for elbo_beta_final in [0.001, 0.1, 1.0, 2.0]:
    for integrator in ("adaptive", "rk2"):
      for train_dict in latent_training_sweep:
        sweeps.append({
            config_prefix + "optimizer.kwargs.learning_rate": 1.5e-4,
            model_prefix + "integrator_method": integrator,
            model_prefix + "elbo_beta_final": elbo_beta_final,
        })
        sweeps[-1].update(train_dict)

  return model_config, sweeps

def benchmark_rgn_sweep():
  """RGN sweep for the benchmark paper."""
  model_config = copy.deepcopy(default_config_dict)
  model_config.name = "RGN"

  sweeps = list()
  for elbo_beta_final in [0.001, 0.1, 1.0, 2.0]:
    for residual in (True, False):
      sweeps.append({
          config_prefix + "optimizer.kwargs.learning_rate": 1.5e-4,
          model_prefix + "latent_system_kwargs.residual": residual,
          model_prefix + "elbo_beta_final": elbo_beta_final,
      })

  return model_config, sweeps

def benchmark_ar_sweep():
  """AR sweep for the benchmark paper."""
  model_config = copy.deepcopy(default_config_dict)
  model_config.name = "AR"
  model_config.latent_dynamics_type = "vanilla"

  sweeps = list()
  for elbo_beta_final in [0.001, 0.1, 1.0, 2.0]:
    for ar_type in ("vanilla", "lstm", "gru"):
      sweeps.append({
          config_prefix + "optimizer.kwargs.learning_rate": 1.5e-4,
          model_prefix + "latent_dynamics_type": ar_type,
          model_prefix + "elbo_beta_final": elbo_beta_final,
      })

  return model_config, sweeps


text:
import pytest
from context import <%= packageName %>

class TestCLI(object):
    """
    Class for testing the command interface.
    """

    def test_onecmd_with_wrapper_script(self):
        # Fixture setup
        import sys
        app_dir = '../..'
        if app_dir not in sys.path:
            sys.path.insert(0, app_dir)
        import app
        sys.argv = ['test.py', app.__file__, 'q']

        # Exercise system
        result = app.main()

        # Verify outcome
        assert result

        # Fixture teardown

    def test_onecmd_with_hyphen_c_script(self):
        # Fixture setup
        import sys
        app_dir = '../..'
        if app_dir not in sys.path:
            sys.path.insert(0, app_dir)
        import app
        sys.argv = ['-c', 'q']

        # Exercise system
        result = app.main()

        # Verify outcome
        assert result

        # Fixture teardown

    def test_onecmd_with_empty_script(self):
        # Fixture setup
        import sys
        app_dir = '../..'
        if app_dir not in sys.path:
            sys.path.insert(0, app_dir)
        import app
        sys.argv = ['', 'q']

        # Exercise system
        result = app.main()

        # Verify outcome
        assert result

        # Fixture teardown

    def test_quit(self):
        cli = <%= packageName %>.cli.CLI()
        assert cli.onecmd('q') == 1

class TestMetadata(object):
    """
    Class for testing the app's metadata.
    """

    def test_version_number(self):
        assert <%= packageName %>.__version__ == '0.0.1'

if __name__ == '__main__':
    pytest.main([__file__])


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  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.
  -->
<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">
  <parent>
    <groupId>org.apache</groupId>
    <artifactId>apache</artifactId>
    <version>9</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <name>Apache Log4j BOM</name>
  <description>Apache Log4j Bill of Materials</description>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-bom</artifactId>
  <version>2.4-SNAPSHOT</version>
  <packaging>pom</packaging>
  <dependencyManagement>
    <dependencies>
      <!-- Log4j API -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>${project.version}</version>
      </dependency>
      <!-- Core Log4j -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>${project.version}</version>
      </dependency>
      <!-- Legacy Log4j 1.2 API -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-1.2-api</artifactId>
        <version>${project.version}</version>
      </dependency>
      <!-- Commons Logging Compatibility API -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-jcl</artifactId>
        <version>${project.version}</version>
      </dependency>
      <!-- Apache Flume Bridge -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-flume-ng</artifactId>
        <version>${project.version}</version>
      </dependency>
      <!-- JSP Tag Library -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-taglib</artifactId>
        <version>${project.version}</version>
      </dependency>
      <!-- JMX GUI -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-jmx-gui</artifactId>
        <version>${project.version}</version>
      </dependency>
      <!-- SLF4J Compatibility API -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
        <version>${project.version}</version>
      </dependency>
      <!-- Web Application Support -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-web</artifactId>
        <version>${project.version}</version>
      </dependency>
      <!-- NoSQL Appender Plugins -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-nosql</artifactId>
        <version>${project.version}</version>
      </dependency>
      <!-- Streaming API -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-iostreams</artifactId>
        <version>${project.version}</version>
      </dependency>
      <!-- java.util.logging adapter -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-jul</artifactId>
        <version>${project.version}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.0</version>
        <configuration>
          <skip>true</skip>
          <skipDeploy>true</skipDeploy>
        </configuration>
      </plugin>
      <!-- RAT report -->
      <plugin>
        <groupId>org.apache.rat</groupId>
        <artifactId>apache-rat-plugin</artifactId>
        <version>0.11</version>
      </plugin>
    </plugins>
  </build>

  <scm>
    <tag>log4j-2.3</tag>
  </scm>
</project>


text:
/* ========================================================================== */
/* === umfpack_tictoc ======================================================= */
/* ========================================================================== */

/* -------------------------------------------------------------------------- */
/* Copyright (c) 2005-2012 by Timothy A. Davis, http://www.suitesparse.com.   */
/* All Rights Reserved.  See ../Doc/License.txt for License.                  */
/* -------------------------------------------------------------------------- */

void umfpack_tic (double stats [2]) ;

void umfpack_toc (double stats [2]) ;

/*
Syntax (for all versions: di, dl, zi, and zl):

    #include "umfpack.h"
    double stats [2] ;
    umfpack_tic (stats) ;
    ...
    umfpack_toc (stats) ;

Purpose:

    umfpack_tic returns the wall clock time.
    umfpack_toc returns the wall clock time since the
    last call to umfpack_tic with the same stats array.

    Typical usage:

	umfpack_tic (stats) ;
	... do some work ...
	umfpack_toc (stats) ;

    then stats [0] contains the elapsed wall clock time in seconds between
    umfpack_tic and umfpack_toc.

Arguments:

    double stats [2]:

	stats [0]:  wall clock time, in seconds
	stats [1]:  (same; was CPU time in prior versions)
*/


text:
#pragma once

#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/client/AWSErrorMarshaller.h>

namespace Aws
{
namespace Client
{

class AWS_EC2_API EC2ErrorMarshaller : public Client::XmlErrorMarshaller
{
public:
  Client::AWSError<Client::CoreErrors> FindErrorByName(const char* exceptionName) const override;
};

} // namespace EC2
} // namespace Aws


text:
class Container::Markdown < ::Container
  store_accessor :content, :markdown

  def custom_container_permitted_attributes
    %i(markdown)
  end

  def renderer(options={})
    Redcarpet::Markdown.new(
      Redcarpet::Render::HTML,
      autolink: true, tables: true
    )
  end
end


text:
<?php

namespace Zend\Code\Scanner;

use Zend\Code\Annotation\AnnotationManager;
use Zend\Code\Exception;
use Zend\Code\NameInformation;

class CachingFileScanner extends FileScanner
{
    /**
     * @var array
     */
    protected static $cache = [];

    /**
     * @var null|FileScanner
     */
    protected $fileScanner = null;

    /**
     * @param  string $file
     * @param  AnnotationManager $annotationManager
     * @throws Exception\InvalidArgumentException
     */
    public function __construct($file, AnnotationManager $annotationManager = null)
    {
        if (!file_exists($file)) {
            throw new Exception\InvalidArgumentException(sprintf(
                'File "%s" not found',
                $file
            ));
        }

        $file = realpath($file);

        $cacheId = md5($file) . '/' . ((isset($annotationManager) ? spl_object_hash($annotationManager) : 'no-annotation'));

        if (isset(static::$cache[$cacheId])) {
            $this->fileScanner = static::$cache[$cacheId];
        } else {
            $this->fileScanner       = new FileScanner($file, $annotationManager);
            static::$cache[$cacheId] = $this->fileScanner;
        }
    }

    /**
     * @return void
     */
    public static function clearCache()
    {
        static::$cache = [];
    }

    /**
     * @return AnnotationManager
     */
    public function getAnnotationManager()
    {
        return $this->fileScanner->getAnnotationManager();
    }

    /**
     * @return array|null|string
     */
    public function getFile()
    {
        return $this->fileScanner->getFile();
    }

    /**
     * @return null|string
     */
    public function getDocComment()
    {
        return $this->fileScanner->getDocComment();
    }

    /**
     * @return array
     */
    public function getNamespaces()
    {
        return $this->fileScanner->getNamespaces();
    }

    /**
     * @param  null|string $namespace
     * @return array|null
     */
    public function getUses($namespace = null)
    {
        return $this->fileScanner->getUses($namespace);
    }

    /**
     * @return array
     */
    public function getIncludes()
    {
        return $this->fileScanner->getIncludes();
    }

    /**
     * @return array
     */
    public function getClassNames()
    {
        return $this->fileScanner->getClassNames();
    }

    /**
     * @return array
     */
    public function getClasses()
    {
        return $this->fileScanner->getClasses();
    }

    /**
     * @param  int|string $className
     * @return ClassScanner
     */
    public function getClass($className)
    {
        return $this->fileScanner->getClass($className);
    }

    /**
     * @param  string $className
     * @return bool|null|NameInformation
     */
    public function getClassNameInformation($className)
    {
        return $this->fileScanner->getClassNameInformation($className);
    }

    /**
     * @return array
     */
    public function getFunctionNames()
    {
        return $this->fileScanner->getFunctionNames();
    }

    /**
     * @return array
     */
    public function getFunctions()
    {
        return $this->fileScanner->getFunctions();
    }
}


text:
from __future__ import annotations # isort:skip

import pytest ; pytest

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

# Standard library imports
import gc
import logging
from typing import Any
from unittest.mock import MagicMock, patch

# Bokeh imports
from bokeh.core.enums import HoldPolicy, HoldPolicyType
from bokeh.core.types import ID
from bokeh.document import Document
from bokeh.document.events import DocumentChangedEvent, SessionCallbackAdded, SessionCallbackRemoved
from bokeh.document.locking import UnlockedDocumentProxy
from bokeh.events import ButtonClick, DocumentReady
from bokeh.io import curdoc
from bokeh.models.widgets import Button, Div
from bokeh.server.callbacks import SessionCallback
from bokeh.util.logconfig import basicConfig

# Module under test
import bokeh.document.callbacks as bdc # isort:skip

#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------

class TestDocumentCallbackManager:

    def test_basic(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)

        # module manager should only hold a weak ref
        assert len(gc.get_referrers(d)) == 0

        assert len(cm._message_callbacks) == 1
        assert cm._message_callbacks == {"bokeh_event": [cm.trigger_event]}

    def test_session_callbacks(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        assert set(cm.session_callbacks) == set()
        s1 = SessionCallback(lambda: None, callback_id=ID("1"))
        cm._session_callbacks.add(s1)
        assert set(cm.session_callbacks) == {s1}
        s2 = SessionCallback(lambda: None, callback_id=ID("2"))
        cm._session_callbacks.add(s2)
        assert set(cm.session_callbacks) == {s1, s2}

    def test_session_destroyed_callbacks(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        assert cm.session_destroyed_callbacks == set()
        s1 = lambda x: None
        cm._session_destroyed_callbacks.add(s1)
        assert cm.session_destroyed_callbacks == {s1}
        s2 = lambda x: None
        cm._session_destroyed_callbacks.add(s2)
        assert cm.session_destroyed_callbacks == {s1, s2}

        cm.session_destroyed_callbacks = {s2}
        assert cm.session_destroyed_callbacks == {s2}

    def test_add_session_callback(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)

        events = []
        def listener(event: DocumentChangedEvent) -> None:
            events.append(event)
        cm.on_change(listener)

        assert len(cm.session_callbacks) == 0
        assert not events

        def cb() -> None: pass
        obj = SessionCallback(cb, callback_id=ID("1"))

        callback_obj = cm.add_session_callback(obj, cb, one_shot=False)
        assert len(cm.session_callbacks) == len(events) == 1
        assert isinstance(events[0], SessionCallbackAdded)
        assert callback_obj == cm.session_callbacks[0] == events[0].callback

    def test_destroy(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)

        cm._change_callbacks["foo"] = lambda x: None
        cm._event_callbacks["bar"] = []
        cm._message_callbacks["baz"] = []

        assert cm.destroy() is None  # type: ignore [func-returns-value]

        assert not hasattr(cm, "_change_callbacks")
        assert not hasattr(cm, "_event_callbacks")
        assert not hasattr(cm, "_messagecallbacks")

    @pytest.mark.parametrize('policy', HoldPolicy)
    def test_hold(self, policy: HoldPolicyType) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        assert cm.hold_value is None
        assert cm._held_events == []

        cm.hold(policy)
        assert cm.hold_value == policy

    def test_hold_bad_policy(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        with pytest.raises(ValueError):
            cm.hold("junk")  # type: ignore [arg-type]

    @pytest.mark.parametrize('first,second', [('combine', 'collect'), ('collect', 'combine')])
    def test_hold_rehold(self, first: HoldPolicyType, second: HoldPolicyType, caplog: pytest.LogCaptureFixture) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        with caplog.at_level(logging.WARN):
            cm.hold(first)
            assert caplog.text == ""
            assert len(caplog.records) == 0

            cm.hold(first)
            assert caplog.text == ""
            assert len(caplog.records) == 0

            cm.hold(second)
            assert caplog.text.strip().endswith(f"hold already active with {first!r}, ignoring {second!r}")
            assert len(caplog.records) == 1

            cm.unhold()

            cm.hold(second)
            assert len(caplog.records) == 1

    def test_notify_event(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        reported_curdoc = None
        reported_foo = None
        def invoker() -> None:
            nonlocal reported_curdoc
            nonlocal reported_foo
            reported_curdoc = curdoc()
            reported_foo = 10
        m = Button()
        cm.notify_event(m, ButtonClick(m), invoker)
        assert reported_curdoc is d
        assert reported_foo == 10

    def test_on_change(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        def cb(x: Any) -> None:
            pass
        cm.on_change(cb)
        assert cm._change_callbacks == {cb: cb}  # XXX !!!?

    def test_on_change_dispatch_to(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        called = None
        class recv:
            def _document_changed(x: Any) -> None:
                nonlocal called
                called = x
        cm.on_change_dispatch_to(recv)
        assert recv in cm._change_callbacks
        evt = DocumentChangedEvent(d)
        cm._change_callbacks[recv](evt)
        assert called == evt

    def test_on_event_good_string(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        def good(event: Any) -> None:
            pass
        cm.on_event("document_ready", good)
        assert cm._event_callbacks == {"document_ready": [good]}

    @pytest.mark.parametrize("evt", ("button_click", "junk"))
    def test_on_event_bad_string(self, evt: str) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        def good(event: Any) -> None:
            pass
        with pytest.raises(ValueError):
            cm.on_event(evt, good)
        assert cm._event_callbacks == {}

    def test_on_event_good_event(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        def good(event: Any) -> None:
            pass
        cm.on_event(DocumentReady, good)
        assert cm._event_callbacks == {"document_ready": [good]}

    def test_on_event_bad_event(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        def good(event: Any) -> None:
            pass
        with pytest.raises(ValueError):
            cm.on_event(ButtonClick, good)
        assert cm._event_callbacks == {}

    def test_on_message(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        def cb(x: Any) -> None:
            pass
        cm.on_message("foo", cb)
        assert cm._message_callbacks == {"foo": [cb], "bokeh_event": [cm.trigger_event]}

    def test_on_session_destroyed(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)

        def good(session_context: Any) -> None:
            pass
        cm.on_session_destroyed(good)
        assert cm.session_destroyed_callbacks == {good}

        def bad() -> None:  # wrong signature
            pass

        with pytest.raises(ValueError):
            cm.on_session_destroyed(bad) # type: ignore  [arg-type]  # want to test bad param

    def test_remove_on_change(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        def cb(x: Any) -> None:
            pass
        cm.on_change(cb)
        cm.remove_on_change(cb)
        assert cm._change_callbacks == {}

    def test_remove_on_message(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        def cb(x: Any) -> None:
            pass
        cm.on_message("foo", cb)
        cm.remove_on_message("foo", cb)
        assert cm._message_callbacks == {"foo": [], "bokeh_event": [cm.trigger_event]}

    def test_remove_session_callback(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)

        events = []
        def listener(event: DocumentChangedEvent) -> None:
            events.append(event)
        cm.on_change(listener)

        assert len(cm.session_callbacks) == 0
        assert not events

        def cb() -> None: pass
        obj = SessionCallback(cb, callback_id=ID("1"))

        cm.add_session_callback(obj, cb, one_shot=False)

        cm.remove_session_callback(obj)
        assert len(cm.session_callbacks) == 0
        assert len(events) == 2
        assert isinstance(events[0], SessionCallbackAdded)
        assert isinstance(events[1], SessionCallbackRemoved)

    def test_subscribe(self) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        m = Div()
        assert cm._subscribed_models == {}
        cm.subscribe("foo", m)
        assert "foo" in cm._subscribed_models
        assert len(cm._subscribed_models["foo"]) == 1
        mref = cm._subscribed_models["foo"].pop()
        assert mref() is m

    # TODO (bev) def test_trigger_event
    # TODO (bev) def test_trigger_on_change

    @pytest.mark.parametrize('policy', HoldPolicy)
    def test_unhold(self, policy: HoldPolicyType) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        assert cm.hold_value is None
        assert cm._held_events == []

        cm.hold(policy)
        assert cm.hold_value == policy
        cm.unhold()
        assert cm.hold_value is None

    @patch("bokeh.document.callbacks.DocumentCallbackManager.trigger_on_change")
    def test_unhold_triggers_events(self, mock_trigger: MagicMock) -> None:
        d = Document()
        cm = bdc.DocumentCallbackManager(d)
        cm.hold('collect')
        last = DocumentChangedEvent(d, None)
        cm._held_events = [DocumentChangedEvent(d, None), DocumentChangedEvent(d, None), last]
        cm.unhold()
        assert mock_trigger.call_count == 3
        assert mock_trigger.call_args[0] == (last,)
        assert mock_trigger.call_args[1] == {}

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

def test_invoke_with_curdoc() -> None:
    reported_curdoc = None
    d = Document()
    def f() -> None:
        nonlocal reported_curdoc
        reported_curdoc = curdoc()
    bdc.invoke_with_curdoc(d, f)
    assert reported_curdoc == d

def test_invoke_with_curdoc_nolock() -> None:
    reported_curdoc: Document | UnlockedDocumentProxy | None = None
    d = Document()
    def f() -> None:
        nonlocal reported_curdoc
        reported_curdoc = curdoc()
    f.nolock = True  # type: ignore [attr-defined]
    bdc.invoke_with_curdoc(d, f)
    assert isinstance(reported_curdoc, UnlockedDocumentProxy)
    assert reported_curdoc._doc == d

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------

# needed for caplog tests to function
basicConfig()


text:
package com.flipkart.statse;

import java.util.Properties;

public class Config {
    private final Properties properties;

    public Config(Properties properties) {
        this.properties = properties;
    }

    public int getInt(String key, int defaultValue) {
        String property = properties.getProperty(key);
        if (property == null) {
            return defaultValue;
        }
        return Integer.parseInt(property);
    }

    public String getString(String key, String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }
}


text:
#ifndef WebFontDecoder_h
#define WebFontDecoder_h

#include "third_party/skia/include/core/SkTypeface.h"
#include "wtf/Allocator.h"
#include "wtf/RefPtr.h"
#include "wtf/text/WTFString.h"

namespace blink {

class SharedBuffer;

class WebFontDecoder final {
    STACK_ALLOCATED();
public:
    WebFontDecoder()
    {
    }

    PassRefPtr<SkTypeface> decode(SharedBuffer*);

    static bool supportsFormat(const String&);
    String getErrorString() const { return m_otsErrorString; }

private:
    void setErrorString(const String& errorString) { m_otsErrorString = errorString; }

    String m_otsErrorString;
};

} // namespace blink

#endif // WebFontDecoder_h


text:
cask 'navicat-premium-essentials' do
  version '12.1.10'
  sha256 'b031feff9b8c1a45606d989345f4f92df48273d90a9182300fdb9d59a7ec7376'

  url "http://download.navicat.com/download/navicatess#{version.major_minor.no_dots}_premium_en.dmg"
  name 'Navicat Premium Essentials'
  homepage 'https://navicat.com/products/navicat-essentials'

  app 'Navicat Premium Essentials.app'
end


text: $( dirname "${BASH_SOURCE[0]}" )/exec-class.sh ch.tkuhn.memetools.LayoutWosGraph "$@"