text:
package com.glaf.oa.purchase.web.springmvc;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.glaf.oa.purchase.model.Purchase;
import com.glaf.oa.purchase.query.PurchaseQuery;
import com.glaf.oa.purchase.service.PurchaseService;
import com.glaf.base.modules.BaseDataManager;
import com.glaf.base.modules.sys.model.SysDepartment;
import com.glaf.base.modules.sys.service.SysDepartmentService;

import com.glaf.core.identity.User;
import com.glaf.core.security.LoginContext;
import com.glaf.core.util.JsonUtils;
import com.glaf.core.util.PageResult;
import com.glaf.core.util.ParamUtils;
import com.glaf.core.util.RequestUtils;
import com.glaf.core.util.Tools;

@Controller("/oa/purchaseSearch")
@RequestMapping("/oa/purchaseSearch")
public class PurchaseSearchController {
	protected static final Log logger = LogFactory
			.getLog(PurchaseSearchController.class);

	protected PurchaseService purchaseService;

	protected SysDepartmentService sysDepartmentService;

	public PurchaseSearchController() {

	}

	@RequestMapping("/init")
	public ModelAndView edit(HttpServletRequest request, ModelMap modelMap) {
		User user = RequestUtils.getUser(request);
		RequestUtils.setRequestParameterToAttribute(request);

		Purchase purchase = new Purchase();
		int areaRole = Integer.parseInt(request.getParameter("areaRole"));
		if (areaRole == 0) {
			// 根据用户部门id 获取整个部门的对象(GZ01)
			SysDepartment curdept = sysDepartmentService.findById(user
					.getDeptId());
			// 根据部门CODE(例如GZ01)截取前2位 作为地区
			String curAreadeptCode = curdept.getCode().substring(0, 2);
			purchase.setArea(curAreadeptCode);
		}

		request.setAttribute("purchase", purchase);
		JSONObject rowJSON = purchase.toJsonObject();
		request.setAttribute("x_json", rowJSON.toJSONString());

		return new ModelAndView("/oa/purchase/search_list", modelMap);
	}

	@RequestMapping("/json")
	@ResponseBody
	public byte[] json(HttpServletRequest request, ModelMap modelMap)
			throws IOException {
		LoginContext loginContext = RequestUtils.getLoginContext(request);
		Map<String, Object> params = RequestUtils.getParameterMap(request);
		PurchaseQuery query = new PurchaseQuery();
		Tools.populate(query, params);
		query.setActorId(loginContext.getActorId());// 只能查找自己
		query.setLoginContext(loginContext);

		User user = RequestUtils.getUser(request);
		/**
		 * 查询条件
		 */
		int areaRole = Integer.parseInt(request.getParameter("areaRole"));
		if (areaRole == 0) {
			// 根据用户部门id 获取整个部门的对象(GZ01)
			SysDepartment curdept = sysDepartmentService.findById(user
					.getDeptId());
			// 根据部门CODE(例如GZ01)截取前2位 作为地区
			String curAreadeptCode = curdept.getCode().substring(0, 2);
			query.setArea(curAreadeptCode);
		} else {
			query.setArea(ParamUtils.getString(params, "area"));
		}
		query.setPurchasenoLike(ParamUtils.getString(params, "purchaseNoLike"));
		query.setAppdateGreaterThanOrEqual(ParamUtils.getDate(params,
				"appdateGreaterThanOrEqual"));
		query.setAppdateLessThanOrEqual(ParamUtils.getDate(params,
				"appdateLessThanOrEqual"));
		query.setCompany(ParamUtils.getString(params, "company"));
		query.setDept(ParamUtils.getString(params, "dept"));
		query.setStatusGreaterThanOrEqual(1);

		String gridType = ParamUtils.getString(params, "gridType");
		if (gridType == null) {
			gridType = "easyui";
		}
		int start = 0;
		int limit = 10;
		String orderName = null;
		String order = null;

		int pageNo = ParamUtils.getInt(params, "page");
		limit = ParamUtils.getInt(params, "rows");
		start = (pageNo - 1) * limit;
		orderName = ParamUtils.getString(params, "sortName");
		order = ParamUtils.getString(params, "sortOrder");

		if (start < 0) {
			start = 0;
		}

		if (limit <= 0) {
			limit = PageResult.DEFAULT_PAGE_SIZE;
		}

		JSONObject result = new JSONObject();
		int total = purchaseService.getPurchaseCountByQueryCriteria(query);
		if (total > 0) {
			result.put("total", total);
			result.put("totalCount", total);
			result.put("totalRecords", total);
			result.put("start", start);
			result.put("startIndex", start);
			result.put("limit", limit);
			result.put("pageSize", limit);

			if (StringUtils.isNotEmpty(orderName)) {
				query.setSortOrder(orderName);
				if (StringUtils.equals(order, "desc")) {
					query.setSortOrder(" desc ");
				}
			}

			List<Purchase> list = purchaseService.getPurchasesByQueryCriteria(
					start, limit, query);

			if (list != null && !list.isEmpty()) {
				JSONArray rowsJSON = new JSONArray();

				result.put("rows", rowsJSON);

				for (Purchase purchase : list) {
					JSONObject rowJSON = purchase.toJsonObject();
					rowJSON.put("id", purchase.getPurchaseid());
					rowJSON.put("purchaseId", purchase.getPurchaseid());
					rowJSON.put("startIndex", ++start);
					String areaname = BaseDataManager.getInstance()
							.getStringValue(purchase.getArea(), "area");
					rowJSON.put("areaname", areaname);
					String companyname = BaseDataManager.getInstance()
							.getStringValue(purchase.getCompany(),
									purchase.getArea());
					rowJSON.put("companyname", companyname);
					String appusername = BaseDataManager.getInstance()
							.getStringValue(purchase.getAppuser(), "SYS_USERS");
					rowJSON.put("appusername", appusername);
					String deptname = BaseDataManager.getInstance()
							.getStringValue(purchase.getDept(), "SYS_DEPTS");
					rowJSON.put("deptname", deptname);
					rowsJSON.add(rowJSON);
				}

			}
		} else {
			JSONArray rowsJSON = new JSONArray();
			result.put("rows", rowsJSON);
			result.put("total", total);
		}
		return result.toJSONString().getBytes("UTF-8");
	}

	@RequestMapping
	public ModelAndView list(HttpServletRequest request, ModelMap modelMap) {
		RequestUtils.setRequestParameterToAttribute(request);
		String x_query = request.getParameter("x_query");
		if (StringUtils.equals(x_query, "true")) {
			Map<String, Object> paramMap = RequestUtils
					.getParameterMap(request);
			String x_complex_query = JsonUtils.encode(paramMap);
			x_complex_query = RequestUtils.encodeString(x_complex_query);
			request.setAttribute("x_complex_query", x_complex_query);
		} else {
			request.setAttribute("x_complex_query", "");
		}
		String view = request.getParameter("view");
		if (StringUtils.isNotEmpty(view)) {
			return new ModelAndView(view, modelMap);
		}

		return new ModelAndView("/oa/purchase/search_list", modelMap);
	}

	@javax.annotation.Resource
	public void setPurchaseService(PurchaseService purchaseService) {
		this.purchaseService = purchaseService;
	}

	@javax.annotation.Resource
	public void setSysDepartmentService(
			SysDepartmentService sysDepartmentService) {
		this.sysDepartmentService = sysDepartmentService;
	}

}


text:
<?php
/*
 BASED ON IJ POST ATTACHMENTS BY GUSTAVO HENKE - http://www.injoin.com.br
*/

//<editor-fold desc="Constants">
define('IJ_POST_ATTACHMENTS_DIR', dirname(__FILE__));
define('IJ_POST_ATTACHMENTS_URL', plugin_dir_url(__FILE__));
define('IJ_POST_ATTACHMENTS_VER', '0.1.0');
//</editor-fold>

class IJ_Post_Attachments
{

	//<editor-fold desc="Properties">
	/**
	 * List of methods that are WP actions.
	 *
	 * @since   0.0.1a
	 * @var     array
	 */
	private $actions = array(
		'add_meta_boxes', 'admin_print_styles', 'admin_enqueue_scripts',
		'wp_ajax_ij_realign', 'wp_ajax_ij_attachment_edit'
	);

	/**
	 * The singleton instance of this class
	 *
	 * @since   0.0.1a
	 * @var     IJ_Post_Attachments
	 */
	private static $instance;
	//</editor-fold>

	//<editor-fold desc="Basic methods">
	/**
	 * Constructor
	 *
	 * @since   0.0.1a
	 * @return  IJ_Post_Attachments
	 */
	private function __construct()
	{
		foreach ($this->actions as $action)
			add_action($action, array($this, $action));
	}

	/**
	 * Singleton access for the class
	 *
	 * @static
	 * @since   0.0.1a
	 * @return  IJ_Post_Attachments
	 */
	static public function getInstance()
	{
		if (!isset(self::$instance))
			self::$instance = new IJ_Post_Attachments();

		return self::$instance;
	}

	/**
	 * Disallows cloning this class
	 *
	 * @since   0.0.1a
	 * @throws  Exception
	 * @return  void
	 */
	public function __clone()
	{
		throw new Exception("Clone is disallowed.");
	}
	//</editor-fold>

	//<editor-fold desc="Metabox">
	/**
	 * Add the plugin meta box
	 *
	 * @since   0.0.1a
	 * @return  void
	 */
	public function add_meta_boxes()
	{
		$pid = isset($_GET['post']) ? $_GET['post'] : 0;
		global $pagenow;
		if (!(in_array( $pagenow, array( 'post-new.php' ) )) && ($pid == '0' || $pid == NULL)) {
			return; //Additional check to avoid showing the metabox in not-intended pages (ex. Members Plugin)
		}

		add_meta_box(
			// 'ij-post-attachments', __('Media'),
			'ij-post-attachments', 'Anexos',
			array($this, 'printMetaBox'), null, 'normal', 'high'
		);
	}

	/**
	 * Enqueue the JS files needed by the plugin
	 *
	 * @since	0.0.1a
	 * @return	void
	 */
	public function admin_enqueue_scripts()
	{
		global $hook_suffix;
		if ($hook_suffix != 'post.php')
			return;

		wp_enqueue_script('syoHint', IJ_POST_ATTACHMENTS_URL . 'js/jquery.syoHint.js', array('jquery'), '1.0.10');
		wp_enqueue_script(
			'ij-post-attachments', IJ_POST_ATTACHMENTS_URL . 'js/ij-post-attachments.js',
			array('syoHint', 'jquery-ui-sortable'), IJ_POST_ATTACHMENTS_VER
		);

		wp_localize_script('ij-post-attachments', 'IJ_Post_Attachments_Vars', array(
			'editMedia' => __('Edit Media'),
			'postID'    => isset($_GET['post']) ? $_GET['post'] : 0
		));
	}

	/**
	 * Enqueue the plugin CSS
	 *
	 * @since	0.0.1a
	 * @return	void
	 */
	public function admin_print_styles()
	{
		global $hook_suffix;
		if ($hook_suffix == 'post.php' || $hook_suffix == 'post-new.php' )
			wp_enqueue_style('ij-post-attachments', IJ_POST_ATTACHMENTS_URL . 'css/ij-post-attachments.css', array(), IJ_POST_ATTACHMENTS_VER);
	}

	/**
	 * Create the meta box below the post editor and list the files
	 *
	 * @since   0.0.1a
	 * @param   object $post
	 * @return  void
	 */
	public function printMetaBox($post)
	{

		$attachments = new WP_Query(array(
			'post_parent'   => $post->ID,
			'post_type'     => 'attachment',
			'post_status'   => 'any',
			'orderby'       => 'menu_order',
			'order'         => 'ASC',
			'posts_per_page' => 1000
		));

		include IJ_POST_ATTACHMENTS_DIR . '/templates/metabox.php';
	}
	//</editor-fold>

	//<editor-fold desc="Attachment Edition Screen">
	/**
	 * Output the script/link tags needed by the edit iframe
	 *
	 * @since   0.0.1a
	 * @return  void
	 */
	public function attachmentEditHeadIframe()
	{
		global $wp_scripts;
		wp_default_scripts($wp_scripts);

		// I don't know if all these scripts are really needed by the media edit screen.
		// They're just there, so they'll be here too :P
		include IJ_POST_ATTACHMENTS_DIR . '/templates/attachmentEditHead.php';

		// Add the needed vars to set the thumbnail :)
		$wp_scripts->localize('set-post-thumbnail', 'post_id', $_GET['post_id']);
		$wp_scripts->print_extra_script('set-post-thumbnail');
	}

	/**
	 * Echoes the content of the edit iframe
	 *
	 * @since   0.0.1a
	 * @return  void
	 */
	public function attachmentEditIframe()
	{
		$url    = admin_url('media.php');
		$id     = $_REQUEST['attachment_id'];
		include IJ_POST_ATTACHMENTS_DIR . '/templates/attachmentEditIframe.php';
	}

	/**
	 * Initialize the attachment edit pop-up.
	 *
	 * @since   0.0.1a
	 * @return  void
	 */
	public function wp_ajax_ij_attachment_edit()
	{
		add_action('admin_head-media-upload-popup', array($this, 'attachmentEditHeadIframe'));
		wp_iframe(array($this, 'attachmentEditIframe'));

		// Without the line below, the WP AJAX caller (admin-ajax.php) would print an '0'
		// at the end of the request.
		die;
	}
	//</editor-fold>

	//<editor-fold desc="Attachment sorting">
	/**
	 * Re-align attachments.
	 *
	 * @since   0.0.1a
	 * @return  void
	 */
	public function wp_ajax_ij_realign()
	{
		header('Content-Type: text/plain');

		$alignment = $_REQUEST['alignment'];
		if (!is_array($alignment))
			$alignment = array_map('trim', explode(',', $alignment));

		$alignment = array_values($alignment);
		$count = count($alignment);

		for ($i = 0; $i < $count; $i++) {
			if (!is_numeric($alignment[$i]))
				continue;

			$attachment = get_post($alignment[$i]);
			$attachment->menu_order = $i;
			wp_update_post($attachment);
		}
	}
	//</editor-fold>

}

$IJ_Post_Attachments = IJ_Post_Attachments::getInstance();

redpajama_set_name: RedPajamaGithub


text:
package org.keycloak.testsuite.util;

import org.jboss.arquillian.graphene.context.GrapheneContext;
import org.jboss.arquillian.graphene.page.Page;
import org.keycloak.testsuite.page.AbstractPage;
import org.openqa.selenium.WebDriver;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author Vaclav Muzikar <vmuzikar@redhat.com>
 */
public final class DroneUtils {
    private static Queue<WebDriver> driverQueue = new LinkedList<>();

    public static WebDriver getCurrentDriver() {
        if (driverQueue.isEmpty()) {
            return GrapheneContext.lastContext().getWebDriver();
        }

        return driverQueue.peek();
    }

    public static void addWebDriver(WebDriver driver) {
        driverQueue.add(driver);
    }

    public static void removeWebDriver() {
        driverQueue.poll();
    }

    public static void resetQueue() {
        driverQueue = new LinkedList<>();
    }

    /**
     * This static method can be used to change default {@ode WebDriver} to different one if the test is able to run
     * with only one {@code WebDriver}.
     *
     * {@code target} parameter is supposed be of type {@code AbstractKeycloakTest} or {@link AbstractPage}.
     *
     * @param target target class on which one needs to change {@code WebDriver}
     * @param driver the new {@code WebDriver}
     */
    public static void replaceDefaultWebDriver(Object target, WebDriver driver) {
        DroneUtils.addWebDriver(driver);
        List<Field> allFields = new ArrayList<>();
        // Add all fields of this class and superclasses
        Class<?> targetClass = target.getClass();
        while (targetClass != null) {
            allFields.addAll(Arrays.asList(targetClass.getDeclaredFields()));
            allFields.addAll(Arrays.asList(targetClass.getFields()));
            targetClass = targetClass.getSuperclass();
        }

        for (Field f : allFields) {
            if (f.getAnnotation(Page.class) != null
                    && AbstractPage.class.isAssignableFrom(f.getType())) {
                try {
                    if (!f.isAccessible())
                        f.setAccessible(true);
                    Object o = f.get(target);
                    AbstractPage page = (AbstractPage) o;
                    page.setDriver(driver);
                    replaceDefaultWebDriver(page, driver);
                } catch (IllegalAccessException e) {
                    throw new IllegalStateException("Could not replace the driver in " + f, e);
                }
            } else if (f.getName().equals("driver") && WebDriver.class.isAssignableFrom(f.getType())) {
                try {
                    if (!f.isAccessible())
                        f.setAccessible(true);
                    f.set(target, driver);

                } catch (IllegalAccessException e) {
                    throw new IllegalStateException("Could not replace the " + f.getName() + " in class "
                            + target.getClass().getName(), e);
                }
            } else if (f.getName().equals("oauth") && OAuthClient.class.isAssignableFrom(f.getType())) {
                try {
                    if (!f.isAccessible())
                        f.setAccessible(true);
                    Object o = f.get(target);
                    ((OAuthClient) o).setDriver(driver);
                } catch (IllegalAccessException e) {
                    throw new IllegalStateException("Could not replace the " + f.getName() + " in class "
                            + target.getClass().getName(), e);
                }
            }
        }
        DroneUtils.removeWebDriver();
    }

}


text:
package com.spotify.helios.system;

import com.spotify.docker.client.DockerClient;
import com.spotify.helios.Polling;
import com.spotify.helios.client.HeliosClient;
import com.spotify.helios.common.descriptors.DockerVersion;
import com.spotify.helios.common.descriptors.HostStatus;

import org.junit.Test;

import java.util.concurrent.Callable;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class AgentReportingTest extends SystemTestBase {

  @Test
  public void verifyAgentReportsDockerVersion() throws Exception {
    startDefaultMaster();
    startDefaultAgent(testHost());

    final HeliosClient client = defaultClient();
    final DockerVersion dockerVersion = Polling.await(
        LONG_WAIT_SECONDS, SECONDS, new Callable<DockerVersion>() {
          @Override
          public DockerVersion call() throws Exception {
            final HostStatus status = client.hostStatus(testHost()).get();
            return status == null
                   ? null
                   : status.getHostInfo() == null
                     ? null
                     : status.getHostInfo().getDockerVersion();
          }
        });

    try (final DockerClient dockerClient = getNewDockerClient()) {
      final String expectedDockerVersion = dockerClient.version().version();
      assertThat(dockerVersion.getVersion(), is(expectedDockerVersion));
    }
  }
}


text:
/*
 * A body switching control
 *
 * TODO Touch UI controls
 */
L.KSP.Control.CelestialBody = L.Control.extend({
	options: {
		position: "topright",
		collapsed: true
	},

	initialize: function (bodies, options) {
		L.Util.setOptions(this, options);
		this._bodies = bodies;
		this._timeInMillis = new Date().valueOf();
		this._weekInMillis = 604800000;
	},

	onAdd: function () {
		this._initLayout();
		this._update();
		this._map.on("bodychangeend", this._update, this);
		return this._container;
	},

	_initLayout: function () {
		var className = "leaflet-control-celestialbodies",
			container = this._container = L.DomUtil.create("div", className),
			bodies = this._bodies;
		if (this.options.collapsed) {
			L.DomEvent
				.on(container, "mouseover", this._expand, this)
				.on(container, "mouseout", this._collapse, this);
			var link = this._bodiesLink = L.DomUtil.create("a", className + "-toggle", container);
			link.href = "#";
			link.title = "Celestial Bodies";
			L.DomEvent.on(link, "focus", this._expand, this);
			this._map.on("movestart", this._collapse, this);
		}
		var list = this._list = L.DomUtil.create("ul", className + "-list", container);
		// TODO cleanup
		for (var body in bodies) {
			if (bodies.hasOwnProperty(body)) {
				var planetItem = this._addBody(bodies[body], list);
				if (bodies[body].children) {
					var satelliteList = document.createElement("ul");
					for (var satellite in bodies[body].children) {
						if (bodies[body].children.hasOwnProperty(satellite)) {
							this._addBody(bodies[body].children[satellite], satelliteList);
						}
					}
					planetItem.appendChild(satelliteList);
				}
			}
		}
	},

	_update: function () {
		if (this._map._body) {
			this._bodiesLink.style.backgroundImage = "url(\"" + this._map._body.thumbnail + "\")";
		}
	},

	_addBody: function (body, list) {
		var bodyItem = document.createElement("li"),
			thumbnail = document.createElement("img"),
			flag;
		thumbnail.src = body.thumbnail;
		thumbnail.alt = bodyItem.title = body.name;
		if (body.addedOn) {
			if (this._timeInMillis - body.addedOn < this._weekInMillis) {
				flag = L.DomUtil.create("h2", "leaflet-control-celestialbodies-flag leaflet-control-celestialbodies-flag-orange", bodyItem);
				flag.innerHTML = "new";
			} else if (this._timeInMillis - body.lastUpdated < this._weekInMillis) {
				flag = L.DomUtil.create("h2", "leaflet-control-celestialbodies-flag", bodyItem);
				flag.innerHTML = "update";
			}

			var link = document.createElement("a");
			link.href = "#";

			var stop = L.DomEvent.stopPropagation;

			L.DomEvent
				.on(link, "click", stop)
				.on(link, "mousedown", stop)
				.on(link, "dblclick", stop)
				.on(link, "click", L.DomEvent.preventDefault)
				.on(link, "click", function () {body.addTo(this._map); return false; }, this);

			link.appendChild(thumbnail);
			bodyItem.appendChild(link);

		} else {
			L.DomUtil.addClass(thumbnail, "disabled");
			bodyItem.appendChild(thumbnail);
		}

		list.appendChild(bodyItem);
		return bodyItem;
	},

	_expand: function () {
		L.DomUtil.addClass(this._container, "leaflet-control-celestialbodies-expanded");
	},

	_collapse: function () {
		this._container.className = this._container.className.replace(" leaflet-control-celestialbodies-expanded", "");
	}
});

L.KSP.Map.mergeOptions({
	bodyControl: true
});

L.KSP.Map.addInitHook(function () {
	if (this.options.bodyControl) {
		this.bodyControl = new L.KSP.Control.CelestialBody(L.KSP.CelestialBody.ALL_PLANETARY);
		this.addControl(this.bodyControl);
	}
});

L.KSP.control.celestialBody = function (bodies, options) {
	return new L.KSP.Control.CelestialBody(bodies, options);
};


text:
namespace Burrows.Tests.Saga
{
    using System;
    using System.Threading;
    using Magnum.Extensions;
    using Messages;

    public class RegisterUserController :
		Consumes<UserRegistrationPending>.For<Guid>,
		Consumes<UserRegistrationComplete>.For<Guid>
	{
		readonly IServiceBus _bus;
		readonly ManualResetEvent _registrationComplete = new ManualResetEvent(false);
		readonly Guid _correlationId;
		readonly ManualResetEvent _registrationPending = new ManualResetEvent(false);

		public RegisterUserController(IServiceBus bus)
		{
			_bus = bus;
			_correlationId = Guid.NewGuid();
		}

		public void Consume(UserRegistrationComplete message)
		{
			_registrationComplete.Set();
		}

		public Guid CorrelationId
		{
			get { return _correlationId; }
		}

		public void Consume(UserRegistrationPending message)
		{
			_registrationPending.Set();
		}

		public bool RegisterUser(string username, string password, string displayName, string email)
		{
			var message = new RegisterUser(_correlationId, username, password, displayName, email);

		    _bus.Publish(message);

		    return _registrationPending.WaitOne(8.Seconds());
		}

		public bool ValidateUser()
		{
		    _bus.Publish(new UserValidated(CorrelationId));

		    return WaitOn(_registrationComplete, 8.Seconds(), "Timeout waiting for registration to complete");
		}

        bool WaitOn(WaitHandle handle, TimeSpan timeout, string message)
        {
            int result = WaitHandle.WaitAny(new[] { handle }, timeout, true);
            if (result == 0)
                return true;

            if (result == 1)
                return false;

            throw new ApplicationException(message);
        }
	}
}


text:
package org.openjdk.tests.java.util.stream;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.function.Supplier;
import java.util.stream.LambdaTestHelpers;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.*;
import java.util.stream.Stream;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

/**
 * Tests laziness of stream operations -- mutations to the source after the stream() but prior to terminal operations
 * are reflected in the stream contents.
 */
@Test
public class CollectionAndMapModifyStreamTest {

    @DataProvider(name = "collections")
    public Object[][] createCollections() {
        List<Integer> content = LambdaTestHelpers.countTo(10);

        List<Collection<Integer>> collections = new ArrayList<>();
        collections.add(new ArrayList<>(content));
        collections.add(new LinkedList<>(content));
        collections.add(new Vector<>(content));

        collections.add(new HashSet<>(content));
        collections.add(new LinkedHashSet<>(content));
        collections.add(new TreeSet<>(content));

        Stack<Integer> stack = new Stack<>();
        stack.addAll(content);
        collections.add(stack);
        collections.add(new PriorityQueue<>(content));
        collections.add(new ArrayDeque<>(content));

        // Concurrent collections

        collections.add(new ConcurrentSkipListSet<>(content));

        ArrayBlockingQueue<Integer> arrayBlockingQueue = new ArrayBlockingQueue<>(content.size());
        for (Integer i : content)
            arrayBlockingQueue.add(i);
        collections.add(arrayBlockingQueue);
        collections.add(new PriorityBlockingQueue<>(content));
        collections.add(new LinkedBlockingQueue<>(content));
        collections.add(new LinkedTransferQueue<>(content));
        collections.add(new ConcurrentLinkedQueue<>(content));
        collections.add(new LinkedBlockingDeque<>(content));
        collections.add(new ConcurrentLinkedDeque<>(content));

        Object[][] params = new Object[collections.size()][];
        for (int i = 0; i < collections.size(); i++) {
            params[i] = new Object[]{collections.get(i).getClass().getName(), collections.get(i)};
        }

        return params;
    }

    @Test(dataProvider = "collections")
    public void testCollectionSizeRemove(String name, Collection<Integer> c) {
        assertTrue(c.remove(1));
        Stream<Integer> s = c.stream();
        assertTrue(c.remove(2));
        Object[] result = s.toArray();
        assertEquals(result.length, c.size());
    }

    @DataProvider(name = "maps")
    public Object[][] createMaps() {
        Map<Integer, Integer> content = new HashMap<>();
        for (int i = 0; i < 10; i++) {
            content.put(i, i);
        }

        Map<String, Supplier<Map<Integer, Integer>>> maps = new HashMap<>();

        maps.put(HashMap.class.getName(), () -> new HashMap<>(content));
        maps.put(HashMap.class.getName(), () -> new LinkedHashMap<>(content));
        maps.put(IdentityHashMap.class.getName(), () -> new IdentityHashMap<>(content));
        maps.put(WeakHashMap.class.getName(), () -> new WeakHashMap<>(content));

        maps.put(TreeMap.class.getName(), () -> new TreeMap<>(content));
        maps.put(TreeMap.class.getName() + ".descendingMap()", () -> new TreeMap<>(content).descendingMap());

        // The following are not lazy
//        maps.put(TreeMap.class.getName() + ".descendingMap().descendingMap()", () -> new TreeMap<>(content).descendingMap().descendingMap());
//        maps.put(TreeMap.class.getName() + ".headMap()", () -> new TreeMap<>(content).headMap(content.size() - 1));
//        maps.put(TreeMap.class.getName() + ".descendingMap().headMap()", () -> new TreeMap<>(content).descendingMap().tailMap(content.size() - 1, false));

        // Concurrent collections

        maps.put(ConcurrentHashMap.class.getName(), () -> new ConcurrentHashMap<>(content));
        maps.put(ConcurrentSkipListMap.class.getName(), () -> new ConcurrentSkipListMap<>(content));

        Object[][] params = new Object[maps.size()][];
        int i = 0;
        for (Map.Entry<String, Supplier<Map<Integer, Integer>>> e : maps.entrySet()) {
            params[i++] = new Object[]{e.getKey(), e.getValue()};

        }

        return params;
    }

    @Test(dataProvider = "maps", groups = { "serialization-hostile" })
    public void testMapKeysSizeRemove(String name, Supplier<Map<Integer, Integer>> c) {
        testCollectionSizeRemove(name + " key set", c.get().keySet());
    }

    @Test(dataProvider = "maps", groups = { "serialization-hostile" })
    public void testMapValuesSizeRemove(String name, Supplier<Map<Integer, Integer>> c) {
        testCollectionSizeRemove(name + " value set", c.get().values());
    }

    @Test(dataProvider = "maps")
    public void testMapEntriesSizeRemove(String name, Supplier<Map<Integer, Integer>> c) {
        testEntrySetSizeRemove(name + " entry set", c.get().entrySet());
    }

    private void testEntrySetSizeRemove(String name, Set<Map.Entry<Integer, Integer>> c) {
        Map.Entry<Integer, Integer> first = c.iterator().next();
        assertTrue(c.remove(first));
        Stream<Map.Entry<Integer, Integer>> s = c.stream();
        Map.Entry<Integer, Integer> second = c.iterator().next();
        assertTrue(c.remove(second));
        Object[] result = s.toArray();
        assertEquals(result.length, c.size());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        style="@style/LinearLayout.Base"
        android:background="@color/black">

        <include layout="@layout/toolbar" />

        <ImageView
            android:id="@+id/iv_customer_picture"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/mifos_logo_new"
            android:layout_marginTop="@dimen/layout_padding_64dp"
            android:layout_marginBottom="@dimen/layout_padding_64dp"
            android:adjustViewBounds="true"
            android:scaleType="centerInside"
            android:contentDescription="@string/customer_image"/>

    </LinearLayout>

</RelativeLayout>


text:
using Content.Shared.Damage;
using Content.Shared.Damage.Prototypes;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.Prototypes;

namespace Content.Shared.Blocking;

public sealed class BlockingUserSystem : EntitySystem
{
    [Dependency] private readonly IPrototypeManager _proto = default!;
    [Dependency] private readonly BlockingSystem _blockingSystem = default!;
    [Dependency] private readonly DamageableSystem _damageable = default!;
    [Dependency] private readonly SharedAudioSystem _audio = default!;

    public override void Initialize()
    {
        base.Initialize();

        SubscribeLocalEvent<BlockingUserComponent, DamageChangedEvent>(OnDamageChanged);
        SubscribeLocalEvent<BlockingUserComponent, DamageModifyEvent>(OnUserDamageModified);

        SubscribeLocalEvent<BlockingUserComponent, EntParentChangedMessage>(OnParentChanged);
        SubscribeLocalEvent<BlockingUserComponent, ContainerGettingInsertedAttemptEvent>(OnInsertAttempt);
        SubscribeLocalEvent<BlockingUserComponent, AnchorStateChangedEvent>(OnAnchorChanged);
    }

    private void OnParentChanged(EntityUid uid, BlockingUserComponent component, ref EntParentChangedMessage args)
    {
        if (TryComp<BlockingComponent>(component.BlockingItem, out var blockComp) && blockComp.IsBlocking)
            _blockingSystem.StopBlocking(component.BlockingItem.Value, blockComp, uid);
    }

    private void OnInsertAttempt(EntityUid uid, BlockingUserComponent component, ContainerGettingInsertedAttemptEvent args)
    {
        if (TryComp<BlockingComponent>(component.BlockingItem, out var blockComp) && blockComp.IsBlocking)
            _blockingSystem.StopBlocking(component.BlockingItem.Value, blockComp, uid);
    }

    private void OnAnchorChanged(EntityUid uid, BlockingUserComponent component, ref AnchorStateChangedEvent args)
    {
        if (args.Anchored)
            return;

        if (TryComp<BlockingComponent>(component.BlockingItem, out var blockComp) && blockComp.IsBlocking)
            _blockingSystem.StopBlocking(component.BlockingItem.Value, blockComp, uid);
    }

    private void OnDamageChanged(EntityUid uid, BlockingUserComponent component, DamageChangedEvent args)
    {
        if (args.DamageDelta != null && args.DamageIncreased)
            _damageable.TryChangeDamage(component.BlockingItem, args.DamageDelta, origin: args.Origin);
    }

    private void OnUserDamageModified(EntityUid uid, BlockingUserComponent component, DamageModifyEvent args)
    {
        if (TryComp<BlockingComponent>(component.BlockingItem, out var blockingComponent))
        {
            if (_proto.TryIndex(blockingComponent.PassiveBlockDamageModifer, out DamageModifierSetPrototype? passiveblockModifier) && !blockingComponent.IsBlocking)
                args.Damage = DamageSpecifier.ApplyModifierSet(args.Damage, passiveblockModifier);

            if (_proto.TryIndex(blockingComponent.ActiveBlockDamageModifier, out DamageModifierSetPrototype? activeBlockModifier) && blockingComponent.IsBlocking)
            {
                args.Damage = DamageSpecifier.ApplyModifierSet(args.Damage, activeBlockModifier);
                _audio.PlayPvs(blockingComponent.BlockSound, component.Owner, AudioParams.Default.WithVariation(0.2f));
            }
        }
    }
}


text:
package org.apache.flink.runtime.source.coordinator;

import org.apache.flink.api.connector.source.Source;
import org.apache.flink.api.connector.source.mocks.MockSourceSplit;
import org.apache.flink.api.connector.source.mocks.MockSourceSplitSerializer;
import org.apache.flink.api.connector.source.mocks.MockSplitEnumeratorCheckpointSerializer;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.operators.coordination.EventReceivingTasks;
import org.apache.flink.runtime.operators.coordination.MockOperatorCoordinatorContext;
import org.apache.flink.runtime.source.event.ReaderRegistrationEvent;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.concurrent.ExecutorThreadFactory;

import org.junit.After;
import org.junit.Before;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static org.junit.Assert.assertNotNull;

/** The test base for SourceCoordinator related tests. */
public abstract class SourceCoordinatorTestBase {

    protected static final String OPERATOR_NAME = "TestOperator";
    protected static final OperatorID TEST_OPERATOR_ID = new OperatorID(1234L, 5678L);
    protected static final int NUM_SUBTASKS = 3;

    // ---- Mocks for the underlying Operator Coordinator Context ---
    protected EventReceivingTasks receivingTasks;
    protected MockOperatorCoordinatorContext operatorCoordinatorContext;

    // ---- Mocks for the Source Coordinator Context ----
    protected SourceCoordinatorProvider.CoordinatorExecutorThreadFactory coordinatorThreadFactory;
    protected ExecutorService coordinatorExecutor;
    protected SplitAssignmentTracker<MockSourceSplit> splitSplitAssignmentTracker;
    protected SourceCoordinatorContext<MockSourceSplit> context;

    // ---- Mocks for the Source Coordinator ----
    protected SourceCoordinator<MockSourceSplit, Set<MockSourceSplit>> sourceCoordinator;
    private TestingSplitEnumerator<MockSourceSplit> enumerator;

    // ------------------------------------------------------------------------

    @Before
    public void setup() throws Exception {
        receivingTasks = EventReceivingTasks.createForRunningTasks();
        operatorCoordinatorContext =
                new MockOperatorCoordinatorContext(TEST_OPERATOR_ID, NUM_SUBTASKS);
        splitSplitAssignmentTracker = new SplitAssignmentTracker<>();
        String coordinatorThreadName = TEST_OPERATOR_ID.toHexString();
        coordinatorThreadFactory =
                new SourceCoordinatorProvider.CoordinatorExecutorThreadFactory(
                        coordinatorThreadName, getClass().getClassLoader());

        coordinatorExecutor = Executors.newSingleThreadExecutor(coordinatorThreadFactory);
        sourceCoordinator = getNewSourceCoordinator();
        context = sourceCoordinator.getContext();
    }

    @After
    public void cleanUp() throws InterruptedException, TimeoutException {
        coordinatorExecutor.shutdown();
        if (!coordinatorExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
            throw new TimeoutException("Failed to close the CoordinatorExecutor before timeout.");
        }
    }

    // ------------------------------------------------------------------------

    protected TestingSplitEnumerator<MockSourceSplit> getEnumerator() {
        if (enumerator == null) {
            enumerator =
                    (TestingSplitEnumerator<MockSourceSplit>) sourceCoordinator.getEnumerator();
            assertNotNull("source was not started", enumerator);
        }
        return enumerator;
    }

    protected void sourceReady() throws Exception {
        sourceCoordinator.start();
        setAllReaderTasksReady(sourceCoordinator);
    }

    protected void setAllReaderTasksReady() {
        setAllReaderTasksReady(sourceCoordinator);
    }

    protected void setAllReaderTasksReady(SourceCoordinator<?, ?> sourceCoordinator) {
        for (int i = 0; i < NUM_SUBTASKS; i++) {
            sourceCoordinator.subtaskReady(i, receivingTasks.createGatewayForSubtask(i));
        }
    }

    protected void addTestingSplitSet(int num) {
        final List<MockSourceSplit> splits = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            splits.add(new MockSourceSplit(i));
        }

        getEnumerator().addNewSplits(splits);
    }

    protected void registerReader(int subtask) {
        sourceCoordinator.handleEventFromOperator(
                subtask, new ReaderRegistrationEvent(subtask, "location_" + subtask));
    }

    protected void waitForCoordinatorToProcessActions() {
        final CompletableFuture<Void> future = new CompletableFuture<>();
        context.runInCoordinatorThread(() -> future.complete(null));

        try {
            future.get();
        } catch (InterruptedException e) {
            throw new AssertionError("test interrupted");
        } catch (ExecutionException e) {
            ExceptionUtils.rethrow(ExceptionUtils.stripExecutionException(e));
        }
    }

    // ------------------------------------------------------------------------

    protected SourceCoordinator<MockSourceSplit, Set<MockSourceSplit>> getNewSourceCoordinator() {
        final Source<Integer, MockSourceSplit, Set<MockSourceSplit>> mockSource =
                TestingSplitEnumerator.factorySource(
                        new MockSourceSplitSerializer(),
                        new MockSplitEnumeratorCheckpointSerializer());

        return new SourceCoordinator<>(
                OPERATOR_NAME, coordinatorExecutor, mockSource, getNewSourceCoordinatorContext());
    }

    protected SourceCoordinatorContext<MockSourceSplit> getNewSourceCoordinatorContext() {
        return new SourceCoordinatorContext<>(
                coordinatorExecutor,
                Executors.newScheduledThreadPool(
                        1,
                        new ExecutorThreadFactory(
                                coordinatorThreadFactory.getCoordinatorThreadName() + "-worker")),
                coordinatorThreadFactory,
                operatorCoordinatorContext,
                new MockSourceSplitSerializer(),
                splitSplitAssignmentTracker);
    }
}


text:
/**
 * A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6
 * LEDs on the bottom represent the minutes (0-59).
 *
 * Each LED represents a zero or one, with the least significant bit on the right.
 *
 * For example, the above binary watch reads "3:25".
 *
 * Given a non-negative integer n which represents the number of LEDs that are
 * currently on, return all possible times the watch could represent.
 *
 * Example:
 *  Input: n = 1
 *  Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
 *
 * Note:
 *  1. The order of output does not matter.
 *  2. The hour must not contain a leading zero, for example "01:00" is not valid, it
 *     should be "1:00".
 *  3. The minute must be consist of two digits and may contain a leading zero, for
 *     example "10:2" is not valid, it should be "10:02".
 *
 * @param {number} num
 * @return {string[]}
 */
var readBinaryWatch = function(num) {
    const output = [];

    // find the number of ones in bit expression of time and match with num
    for (let h = 0; h < 12; h++) {
        for (let m = 0; m < 60; m++) {
            const ones = Number(h * 64 + m).toString(2).split('').filter(d => d === '1').length;
            if (ones === num) output.push(m < 10 ? `${h}:0${m}` : `${h}:${m}`);
        }
    }

    return output;
};


text:
namespace gfx {
struct PresentationFeedback;
}

namespace gpu {
struct GpuPreferences;
struct SwapBuffersCompleteParams;

namespace gles2 {
class FeatureInfo;
}

class GPU_IPC_SERVICE_EXPORT ImageTransportSurfaceDelegate {
 public:
#if defined(OS_WIN)
  // Tells the delegate that a child window was created with the provided
  // SurfaceHandle.
  virtual void DidCreateAcceleratedSurfaceChildWindow(
      SurfaceHandle parent_window,
      SurfaceHandle child_window) = 0;
#endif

  // Tells the delegate that SwapBuffers returned.
  virtual void DidSwapBuffersComplete(SwapBuffersCompleteParams params) = 0;

  // Returns the features available for the ContextGroup.
  virtual const gles2::FeatureInfo* GetFeatureInfo() const = 0;

  virtual const GpuPreferences& GetGpuPreferences() const = 0;

  // Tells the delegate a buffer has been presented.
  virtual void BufferPresented(const gfx::PresentationFeedback& feedback) = 0;

  // Callback for GPU vsync signal.  May be called on a different thread.
  virtual viz::GpuVSyncCallback GetGpuVSyncCallback() = 0;

  // Returns how long GpuThread was blocked since last swap. Used for metrics.
  virtual base::TimeDelta GetGpuBlockedTimeSinceLastSwap() = 0;

 protected:
  virtual ~ImageTransportSurfaceDelegate() = default;
};

}  // namespace gpu

#endif  // GPU_IPC_SERVICE_IMAGE_TRANSPORT_SURFACE_DELEGATE_H_


text:
// Copyright 2022 DeepMind Technologies Limited..
//
// 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.

#include "envlogger/converters/xtensor_codec.h"

#include <cstdint>
#include <optional>
#include <variant>

#include "glog/logging.h"
#include "google/protobuf/repeated_field.h"
#include "absl/strings/string_view.h"
#include <gmpxx.h>
#include "riegeli/bytes/string_writer.h"
#include "riegeli/endian/endian_reading.h"
#include "riegeli/endian/endian_writing.h"
#include "xtensor/xview.hpp"

namespace envlogger {
namespace {

// Dimension size reserved for scalars. Please see proto definition.
constexpr int SCALAR_DIM_SIZE = -438;

std::vector<int> ShapeVector(const envlogger::Datum::Shape& shape) {
  std::vector<int> v;
  for (const auto& d : shape.dim()) {
    v.push_back(d.size());
  }
  return v;
}

bool IsScalar(const std::vector<int>& shape) {
  return shape.size() == 1 && shape[0] == SCALAR_DIM_SIZE;
}

// Converts `value` arbitrary precision integer to a binary string.
std::string FromMpzClass(mpz_class value) {
  auto z = value.get_mpz_t();
  const int num_bits = mpz_sizeinbase(z, 2);
  const int num_bytes = num_bits / 8 + 1;
  const bool is_negative = mpz_sgn(z) == -1;
  if (is_negative) {
    // NOTE: We cannot reinterpret cast z from a signed to an unsigned value so
    // we convert it by hand using the formula:
    // z_unsigned = 2^num_bytes(z) + z
    mpz_t max_int;
    mpz_init(max_int);
    mpz_pow_ui(max_int, /*base=*/mpz_class(2).get_mpz_t(), num_bytes * 8);
    mpz_add(z, max_int, z);
    mpz_clear(max_int);
  }
  std::string output(num_bytes, '\0');
  const int should_pad_first_byte = num_bits % 8 ? 0 : 1;
  mpz_export(/*rop=*/output.data() + should_pad_first_byte,
             /*countp=*/nullptr, /*order=*/1,
             /*size=*/1, /*endian=*/1, /*nails=*/0, z);
  return output;
}

// Converts the binary representation `bytes` to an arbitrary precision integer.
mpz_class ToMpzClass(const absl::string_view bytes) {
  const bool is_padded = bytes[0] == '\0';
  mpz_t z;
  mpz_init(z);
  mpz_import(/*rop=*/z, /*count=*/bytes.size() + (is_padded ? -1 : 0),
             /*order=*/1,
             /*size=*/1, /*endian=*/1, /*nails=*/0,
             bytes.data() + (is_padded ? 1 : 0));
  const bool is_negative = static_cast<uint8_t>(bytes[0]) > 127;
  if (is_negative) {
    // NOTE: We cannot reinterpret cast from an unsigned to a signed integer so
    // we convert it by hand using the formula:
    // z_signed = z - 2^num_bytes(z)
    mpz_t max_int;
    mpz_init(max_int);
    mpz_pow_ui(max_int, /*base=*/mpz_class(2).get_mpz_t(), bytes.size() * 8);
    mpz_sub(z, z, max_int);
    mpz_clear(max_int);
  }
  mpz_class output(z);
  mpz_clear(z);  // Free up memory taken by `z`.
  return output;
}

template <typename T>
xt::xarray<T> FillXarrayValues(const google::protobuf::RepeatedField<T>& values,
                               const std::vector<int>& shape) {
  xt::xarray<T> output;
  output.resize({static_cast<uint64_t>(values.size())});
  for (int i = 0; i < values.size(); ++i) {
    output(i) = values[i];
  }
  output.reshape(shape);
  return output;
}

template <typename T>
xt::xarray<T> FillXarrayValues(const google::protobuf::RepeatedPtrField<T>& values,
                               const std::vector<int>& shape) {
  xt::xarray<T> output;
  output.resize({static_cast<uint64_t>(values.size())});
  for (int i = 0; i < values.size(); ++i) {
    output(i) = values[i];
  }
  output.reshape(shape);
  return output;
}

template <typename T>
inline T LoadScalar(const char* p) {
  constexpr int kSize = sizeof(T);
  static_assert(std::is_integral<T>::value &&
                    (kSize == 1 || kSize == 2 || kSize == 4 || kSize == 8),
                "T needs to be an integral type with byte size 1, 2, 4, or 8.");
  return riegeli::ReadBigEndian<T>(p);
}

// Specialization of the above for floats.
template <>
inline float LoadScalar(const char* p) {
  return riegeli::ReadBigEndianFloat(p);
}

template <typename T>
inline void StoreInteger(T value, char* p) {
  constexpr int kSize = sizeof(T);
  static_assert(std::is_integral<T>::value &&
                    (kSize == 1 || kSize == 2 || kSize == 4 || kSize == 8),
                "T needs to be an integral type with byte size 1, 2, 4, or 8.");
  riegeli::WriteBigEndian<T>(value, p);
}

template <typename T>
xt::xarray<T> FillXarrayValuesBigEndian(const absl::string_view values,
                                        const std::vector<int>& shape) {
  const uint64_t num_elements = values.size() / sizeof(T);
  xt::xarray<T> output;
  output.resize({num_elements});
  for (uint64_t i = 0; i < num_elements * sizeof(T); i += sizeof(T)) {
    output(i / sizeof(T)) = LoadScalar<T>(values.substr(i, sizeof(T)).data());
  }
  output.reshape(shape);
  return output;
}

xt::xarray<absl::Cord> FillXarrayValuesCord(
    const google::protobuf::RepeatedPtrField<std::string>& values,
    const std::vector<int>& shape) {
  xt::xarray<absl::Cord> output;
  for (int i = 0; i < values.size(); ++i) {
    output(i) = absl::Cord(values[i]);
  }
  output.reshape(shape);
  return output;
}

xt::xarray<mpz_class> FillXarrayValuesMpzClass(
    const google::protobuf::RepeatedPtrField<std::string>& values,
    const std::vector<int>& shape) {
  xt::xarray<mpz_class> output;
  for (int i = 0; i < values.size(); ++i) {
    output(i) = ToMpzClass(values[i]);
  }
  output.reshape(shape);
  return output;
}

template <typename T>
std::optional<BasicType> DecodeValues(const google::protobuf::RepeatedField<T>& values,
                                      const std::vector<int>& shape,
                                      bool is_scalar) {
  if (values.empty()) return std::nullopt;

  if (is_scalar) {
    return values[0];
  } else {
    return FillXarrayValues(values, shape);
  }
}

template <typename T>
std::optional<BasicType> DecodeValues(const google::protobuf::RepeatedPtrField<T>& values,
                                      const std::vector<int>& shape,
                                      bool is_scalar) {
  if (values.empty()) return std::nullopt;

  if (is_scalar) {
    return values[0];
  } else {
    return FillXarrayValues(values, shape);
  }
}

template <typename T>
std::optional<BasicType> DecodeValuesBigEndian(const std::string& values,
                                               const std::vector<int>& shape,
                                               bool is_scalar) {
  if (values.empty()) return std::nullopt;

  if (is_scalar) {
    return LoadScalar<T>(values.data());
  } else {
    return FillXarrayValuesBigEndian<T>(values, shape);
  }
}

template <typename T>
std::optional<BasicType> DecodeValues(const std::string& values,
                                      const std::vector<int>& shape,
                                      bool is_scalar) {
  return DecodeValuesBigEndian<T>(values, shape, is_scalar);
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// Encode()
////////////////////////////////////////////////////////////////////////////////

// Scalars

Datum Encode(const float value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  datum.mutable_values()->add_float_values(value);
  return datum;
}

Datum Encode(const double value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  datum.mutable_values()->add_double_values(value);
  return datum;
}

Datum Encode(const int32_t value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  datum.mutable_values()->add_int32_values(value);
  return datum;
}

Datum Encode(const int64_t value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  datum.mutable_values()->add_int64_values(value);
  return datum;
}

Datum Encode(const uint32_t value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  datum.mutable_values()->add_uint32_values(value);
  return datum;
}

Datum Encode(const uint64_t value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  datum.mutable_values()->add_uint64_values(value);
  return datum;
}

Datum Encode(const bool value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  datum.mutable_values()->add_bool_values(value);
  return datum;
}

Datum Encode(const std::string& value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  datum.mutable_values()->add_string_values(value);
  return datum;
}

Datum Encode(const char* value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  datum.mutable_values()->add_string_values(value);
  return datum;
}

Datum Encode(absl::Cord value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  datum.mutable_values()->add_bytes_values(std::string(value));
  return datum;
}

Datum Encode(mpz_class value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  datum.mutable_values()->add_bigint_values(FromMpzClass(value));
  return datum;
}

Datum Encode(const int8_t value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  std::string buffer(sizeof(int8_t), '\0');
  StoreInteger(value, buffer.data());
  datum.mutable_values()->set_int8_values(buffer);
  return datum;
}

Datum Encode(const int16_t value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  std::string buffer(sizeof(int16_t), '\0');
  StoreInteger(value, buffer.data());
  datum.mutable_values()->set_int16_values(buffer);
  return datum;
}

Datum Encode(const uint8_t value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  std::string buffer(sizeof(uint8_t), '\0');
  StoreInteger(value, buffer.data());
  datum.mutable_values()->set_uint8_values(buffer);
  return datum;
}

Datum Encode(const uint16_t value) {
  Datum datum;
  datum.mutable_shape()->add_dim()->set_size(SCALAR_DIM_SIZE);
  std::string buffer(sizeof(uint16_t), '\0');
  StoreInteger(value, buffer.data());
  datum.mutable_values()->set_uint16_values(buffer);
  return datum;
}

// xt::xarrays.

Datum Encode(const xt::xarray<float>& value, bool as_bytes) {
  Datum datum;
  auto* shape = datum.mutable_shape();
  for (const auto& dim : value.shape()) {
    shape->add_dim()->set_size(dim);
  }
  if (as_bytes) {
    riegeli::StringWriter writer(
        datum.mutable_values()->mutable_float_values_buffer());
    writer.SetWriteSizeHint(value.size() * sizeof(float));
    for (const float f : xt::ravel<xt::layout_type::row_major>(value)) {
      riegeli::WriteBigEndianFloat(f, writer);
    }
    writer.Close();
  } else {
    for (const auto x : xt::ravel<xt::layout_type::row_major>(value)) {
      datum.mutable_values()->add_float_values(x);
    }
  }
  return datum;
}

Datum Encode(const xt::xarray<double>& value) {
  Datum datum;
  auto* shape = datum.mutable_shape();
  for (const auto& dim : value.shape()) {
    shape->add_dim()->set_size(dim);
  }
  for (const auto x : xt::ravel<xt::layout_type::row_major>(value)) {
    datum.mutable_values()->add_double_values(x);
  }
  return datum;
}

Datum Encode(const xt::xarray<int32_t>& value) {
  Datum datum;
  auto* shape = datum.mutable_shape();
  for (const auto& dim : value.shape()) {
    shape->add_dim()->set_size(dim);
  }
  for (const auto x : xt::ravel<xt::layout_type::row_major>(value)) {
    datum.mutable_values()->add_int32_values(x);
  }
  return datum;
}

Datum Encode(const xt::xarray<int64_t>& value) {
  Datum datum;
  auto* shape = datum.mutable_shape();
  for (const auto& dim : value.shape()) {
    shape->add_dim()->set_size(dim);
  }
  for (const auto x : xt::ravel<xt::layout_type::row_major>(value)) {
    datum.mutable_values()->add_int64_values(x);
  }
  return datum;
}

Datum Encode(const xt::xarray<uint32_t>& value) {
  Datum datum;
  auto* shape = datum.mutable_shape();
  for (const auto& dim : value.shape()) {
    shape->add_dim()->set_size(dim);
  }
  for (const auto x : xt::ravel<xt::layout_type::row_major>(value)) {
    datum.mutable_values()->add_uint32_values(x);
  }
  return datum;
}

Datum Encode(const xt::xarray<uint64_t>& value) {
  Datum datum;
  auto* shape = datum.mutable_shape();
  for (const auto& dim : value.shape()) {
    shape->add_dim()->set_size(dim);
  }
  for (const auto x : xt::ravel<xt::layout_type::row_major>(value)) {
    datum.mutable_values()->add_uint64_values(x);
  }
  return datum;
}

Datum Encode(const xt::xarray<bool>& value) {
  Datum datum;
  auto* shape = datum.mutable_shape();
  for (const auto& dim : value.shape()) {
    shape->add_dim()->set_size(dim);
  }
  for (const auto x : xt::ravel<xt::layout_type::row_major>(value)) {
    datum.mutable_values()->add_bool_values(x);
  }
  return datum;
}

Datum Encode(const xt::xarray<std::string>& value) {
  Datum datum;
  auto* shape = datum.mutable_shape();
  for (const auto& dim : value.shape()) {
    shape->add_dim()->set_size(dim);
  }
  for (const auto& x : xt::ravel<xt::layout_type::row_major>(value)) {
    datum.mutable_values()->add_string_values(x);
  }
  return datum;
}

Datum Encode(const xt::xarray<absl::Cord>& value) {
  Datum datum;
  auto* shape = datum.mutable_shape();
  for (const auto& dim : value.shape()) {
    shape->add_dim()->set_size(dim);
  }
  for (const auto& x : xt::ravel<xt::layout_type::row_major>(value)) {
    datum.mutable_values()->add_bytes_values(std::string(x));
  }
  return datum;
}

Datum Encode(const xt::xarray<mpz_class>& value) {
  Datum datum;
  auto* shape = datum.mutable_shape();
  for (const auto& dim : value.shape()) {
    shape->add_dim()->set_size(dim);
  }
  for (const auto& x : xt::ravel<xt::layout_type::row_major>(value)) {
    datum.mutable_values()->add_bigint_values(FromMpzClass(x));
  }
  return datum;
}

// Implementation of a generic packer for integer types T.
// Values in `value` are encoded with a big-endian byte order and added one
// after the other in `output`.
template <typename T>
Datum::Shape EncodeBigEndian(const xt::xarray<T>& value, std::string* output) {
  Datum::Shape shape;
  int num_elements = 1;
  for (const auto& dim : value.shape()) {
    shape.add_dim()->set_size(dim);
    num_elements *= dim;
  }

  // Allocate space in the string for all elements.
  *output = std::string(sizeof(T) * num_elements, '\0');
  int i = 0;
  for (const auto x : xt::ravel<xt::layout_type::row_major>(value)) {
    StoreInteger<T>(x, &(*output)[i]);
    i += sizeof(T);
  }
  return shape;
}

Datum Encode(const xt::xarray<int8_t>& value) {
  Datum datum;
  *datum.mutable_shape() =
      EncodeBigEndian(value, datum.mutable_values()->mutable_int8_values());
  return datum;
}

Datum Encode(const xt::xarray<int16_t>& value) {
  Datum datum;
  *datum.mutable_shape() =
      EncodeBigEndian(value, datum.mutable_values()->mutable_int16_values());
  return datum;
}

Datum Encode(const xt::xarray<uint8_t>& value) {
  Datum datum;
  *datum.mutable_shape() =
      EncodeBigEndian(value, datum.mutable_values()->mutable_uint8_values());
  return datum;
}

Datum Encode(const xt::xarray<uint16_t>& value) {
  Datum datum;
  *datum.mutable_shape() =
      EncodeBigEndian(value, datum.mutable_values()->mutable_uint16_values());
  return datum;
}

////////////////////////////////////////////////////////////////////////////////
// Decode()
////////////////////////////////////////////////////////////////////////////////

std::optional<BasicType> Decode(const Datum& datum) {
  const std::vector<int> shape = ShapeVector(datum.shape());
  const bool is_scalar = IsScalar(shape);
  const auto& values = datum.values();

  std::optional<BasicType> float_buffer = DecodeValuesBigEndian<float>(
      values.float_values_buffer(), shape, is_scalar);
  if (float_buffer) return float_buffer;

  std::optional<BasicType> floats =
      DecodeValues(values.float_values(), shape, is_scalar);
  if (floats) return floats;

  std::optional<BasicType> doubles =
      DecodeValues(values.double_values(), shape, is_scalar);
  if (doubles) return doubles;

  std::optional<BasicType> int32s =
      DecodeValues(values.int32_values(), shape, is_scalar);
  if (int32s) return int32s;

  std::optional<BasicType> int64s =
      DecodeValues(values.int64_values(), shape, is_scalar);
  if (int64s) return int64s;

  std::optional<BasicType> uint32s =
      DecodeValues(values.uint32_values(), shape, is_scalar);
  if (uint32s) return uint32s;

  std::optional<BasicType> uint64s =
      DecodeValues(values.uint64_values(), shape, is_scalar);
  if (uint64s) return uint64s;

  std::optional<BasicType> bools =
      DecodeValues(values.bool_values(), shape, is_scalar);
  if (bools) return bools;

  std::optional<BasicType> strings =
      DecodeValues(values.string_values(), shape, is_scalar);
  if (strings) return strings;

  if (!datum.values().bytes_values().empty()) {
    if (is_scalar) {
      return absl::Cord(datum.values().bytes_values(0));
    } else {
      return FillXarrayValuesCord(datum.values().bytes_values(), shape);
    }
  }

  if (!datum.values().bigint_values().empty()) {
    if (is_scalar) {
      return ToMpzClass(datum.values().bigint_values(0));
    } else {
      return FillXarrayValuesMpzClass(datum.values().bigint_values(), shape);
    }
  }

  if (!datum.values().string_values().empty()) {
    if (is_scalar) {
      return datum.values().string_values(0);
    } else {
      // Unimplemented.
    }
  }

  std::optional<BasicType> int8s =
      DecodeValues<int8_t>(values.int8_values(), shape, is_scalar);
  if (int8s) return int8s;

  std::optional<BasicType> int16s =
      DecodeValues<int16_t>(values.int16_values(), shape, is_scalar);
  if (int16s) return int16s;

  std::optional<BasicType> uint8s =
      DecodeValues<uint8_t>(values.uint8_values(), shape, is_scalar);
  if (uint8s) return uint8s;

  std::optional<BasicType> uint16s =
      DecodeValues<uint16_t>(values.uint16_values(), shape, is_scalar);
  if (uint16s) return uint16s;

  return std::nullopt;
}

////////////////////////////////////////////////////////////////////////////////
// DataView
////////////////////////////////////////////////////////////////////////////////

DataView::DataView(const Data* data) : data_(data) {}

Data::ValueCase DataView::Type() const {
  if (data_ == nullptr) return Data::VALUE_NOT_SET;

  return data_->value_case();
}

size_t DataView::size() const {
  if (data_ == nullptr) return 0;

  switch (data_->value_case()) {
    case Data::kArray:
      return data_->array().values().size();
    case Data::kTuple:
      return data_->tuple().values().size();
    case Data::kDict:
      return data_->dict().values().size();
    default:
      return 0;
  }
}

bool DataView::empty() const { return size() == 0; }

const Data* DataView::data() const { return data_; }

const Data* DataView::operator[](int index) const {
  if (data_ == nullptr || index < 0 || index >= static_cast<int>(size()))
    return nullptr;

  const auto type = Type();
  if (type == Data::kArray) return &data_->array().values(index);
  if (type == Data::kTuple) return &data_->tuple().values(index);

  return nullptr;
}

const Data* DataView::operator[](const std::string& key) const {
  if (data_ != nullptr && Type() == Data::kDict) {
    const auto it = data_->dict().values().find(key);
    if (it == data_->dict().values().end()) return nullptr;

    return &it->second;
  }

  return nullptr;
}

const google::protobuf::Map<std::string, Data>& DataView::items() const {
  return data_->dict().values();
}

// Iterator implementation.

DataView::const_iterator DataView::begin() const {
  // Dicts should use .items() and should always return nothing if using
  // .begin() and .end() directly.
  return DataView::const_iterator(this, Type() == Data::kDict ? size() : 0);
}

DataView::const_iterator DataView::end() const {
  return DataView::const_iterator(this, size());
}

bool DataView::const_iterator::operator==(
    const DataView::const_iterator& rhs) const {
  return view_ == rhs.view_ && index_ == rhs.index_;
}

bool DataView::const_iterator::operator!=(
    const DataView::const_iterator& rhs) const {
  return !(*this == rhs);
}

// Pre-inc version.
const DataView::const_iterator& DataView::const_iterator::operator++() {
  ++index_;
  return *this;
}

const Data& DataView::const_iterator::operator*() const {
  return *(*view_)[index_];
}

}  // namespace envlogger


text:
package javax.microedition.khronos.opengles;

public interface GL10Ext
  extends GL
{
  // Methods

  public int glQueryMatrixxOES(int [] arg1, int arg2, int [] arg3, int arg4);
  public int glQueryMatrixxOES(java.nio.IntBuffer arg1, java.nio.IntBuffer arg2);
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="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>

    <!--Editstyle-->
    <style name="edit_style">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">60dp</item>
        <item name="android:layout_marginBottom">10dp</item>
        <item name="android:textColorHint">@color/text_color</item>
        <item name="android:paddingLeft">13dp</item>
        <item name="android:background">@drawable/edittext_bg</item>
        <item name="android:textColor">@color/white</item>
        <item name="android:textCursorDrawable">@null</item>
        <item name="android:textSize">20sp</item>
    </style>

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

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

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

    <!-- 自定义的Toast动画 -->
    <style name="Lite.Animation.Toast" parent="@android:style/Animation.Toast">
        <item name="android:windowEnterAnimation">@anim/lite_toast_enter</item>
        <item name="android:windowExitAnimation">@anim/lite_toast_exit</item>
    </style>
</resources>


text:
package studentRecordsBackup.bst;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by GaneshMac on 11/2/14.
 */
public class Node extends Observable implements Observer{
    private int bNumber;
    private String description;

//    private List<Observer> observers;

    private Node left, right;

    public Node( int inBNumner, String inDescription){
        bNumber = inBNumner;
        description = inDescription;
        left = null;
        right = null;
    }

    public Node getRight() {
        return right;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setbNumber(int bNumber) {
        this.bNumber = bNumber;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    public int getbNumber(){

        return bNumber;
    }

    public Node getLeft() {
        return left;
    }

    @Override
    public String toString() {
        return "Node{" +
                "bNumber=" + bNumber +
                ", description='" + description + '\'' +
                ", left=" + left +
                ", right=" + right +
                '}';
    }

    public String getDescription(){

        return description;
    }

   /**
    * @param inValue
    * */
    public void updateNode( int inValue){
        bNumber += inValue;
        setChanged();
        notifyObservers(inValue);
    }

//    @Override
//    public void addObserver( Observer observer){
//        observers.add(observer);
//    }

//    @Override
//    public void notifyObservers(){
//        for( Observer n: observers){
//            n.update(this, n);
//        }
//    }

    /**@param
     * @see java.util.Observable
     */
    @Override
    public void update(Observable observable, Object o) {
//        System.out.println("Inside update method object class is: "+o.getClass());
        int number = (Integer)o;
        this.bNumber += number;
    }
}


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

namespace System.Text.Lalr
{
    /// <summary>
    /// Reporter
    /// </summary>
    public class Reporter
    {
        private static bool _showPrecedenceConflict = false;

        private static void ConfigPrint(TextWriter w, Config config)
        {
            var rule = config.Rule;
            w.Write("{0} ::=", rule.LHSymbol.Name);
            for (var i = 0; i <= rule.RHSymbols.Length; i++)
            {
                if (i == config.Dot)
                    w.Write(" *");
                if (i == rule.RHSymbols.Length)
                    break;
                var symbol = rule.RHSymbols[i];
                w.Write(" {0}", symbol.Name);
                if (symbol.Type == SymbolType.MultiTerminal)
                    for (var j = 1; j < symbol.Children.Length; j++)
                        w.Write("|{0}", symbol.Children[j].Name);
            }
        }

#if true
        /* Print a set */
        private static void SetPrint(TextWriter w, HashSet<int> set, Context ctx)
        {
            var spacer = string.Empty;
            w.Write("{0,12}[", string.Empty);
            for (var i = 0; i < ctx.Terminals; i++)
                if (set.Contains(i))
                {
                    w.Write("{0}{1}", spacer, ctx.Symbols[i].Name);
                    spacer = " ";
                }
            w.WriteLine("]");
        }

        /* Print a plink chain */
        private static void PlinkPrint(TextWriter w, List<Config> configs, string tag)
        {
            foreach (var config in configs)
            {
                w.Write("{0,12}{1} (state {2,2}) ", string.Empty, tag, config.State.ID);
                ConfigPrint(w, config);
                w.WriteLine();
            }
        }
#endif

        /* Print an action to the given file descriptor.  Return FALSE if nothing was actually printed. */
        private static bool PrintAction(Action action, TextWriter w, int indent)
        {
            var result = true;
            var firstParam = "{0," + indent.ToString() + "}";
            switch (action.Type)
            {
                case ActionType.Shift:
                    w.Write(firstParam + " shift  {1}", action.Symbol.Name, action.State.ID);
                    break;
                case ActionType.Reduce:
                    w.Write(firstParam + " reduce {1}", action.Symbol.Name, action.Rule.ID);
                    break;
                case ActionType.Accept:
                    w.Write(firstParam + " accept", action.Symbol.Name);
                    break;
                case ActionType.Error:
                    w.Write(firstParam + " error", action.Symbol.Name);
                    break;
                case ActionType.SRConflict:
                case ActionType.RRConflict:
                    w.Write(firstParam + " reduce {1,-3} ** Parsing conflict **", action.Symbol.Name, action.Rule.ID);
                    break;
                case ActionType.SSConflict:
                    w.Write(firstParam + " shift  {1,-3} ** Parsing conflict **", action.Symbol.Name, action.State.ID);
                    break;
                case ActionType.SHResolved:
                    if (_showPrecedenceConflict)
                        w.Write(firstParam + " shift  {1,-3} -- dropped by precedence", action.Symbol.Name, action.State.ID);
                    else
                        result = false;
                    break;
                case ActionType.RDResolved:
                    if (_showPrecedenceConflict)
                        w.Write(firstParam + " reduce {1,-3} -- dropped by precedence", action.Symbol.Name, action.Rule.ID);
                    else
                        result = false;
                    break;
                case ActionType.NotUsed:
                    result = false;
                    break;
            }
            return result;
        }

        /// <summary>
        /// Generate the "y.output" log file
        /// </summary>
        /// <param name="ctx">The CTX.</param>
        /// <param name="w">The w.</param>
        /// <param name="wantBasis">if set to <c>true</c> [want basis].</param>
        public static void EmitOutput(Context ctx, StreamWriter w, bool wantBasis)
        {
            for (var i = 0; i < ctx.States; i++)
            {
                var states = ctx.Sorted[i];
                w.WriteLine("State {0}:", states.ID);
                var configs = (wantBasis ? states.Basises : states.Configs);
                foreach (var config in configs)
                {
                    if (config.Dot == config.Rule.RHSymbols.Length)
                        w.Write("    {0,5} ", "(" + config.Rule.ID + ")");
                    else
                        w.Write("          ");
                    ConfigPrint(w, config);
                    w.WriteLine();
#if false
                        SetPrint(w, config.FwSet, ctx);
                        PlinkPrint(w, config.Forwards, "To  ");
                        PlinkPrint(w, config.Basises, "From");
#endif
                }
                w.WriteLine();
                foreach (var action in states.Actions)
                    if (PrintAction(action, w, 30))
                        w.WriteLine();
                w.WriteLine();
            }
            w.WriteLine("----------------------------------------------------");
            w.WriteLine("Symbols:");
            for (var i = 0; i < ctx.Symbols.Length - 1; i++)
            {
                var symbol = ctx.Symbols[i];
                w.Write("  {0,3}: {1}", i, symbol.Name);
                if (symbol.Type == SymbolType.NonTerminal)
                {
                    w.Write(":");
                    if (symbol.Lambda)
                        w.Write(" <lambda>");
                    for (var j = 0; j < ctx.Terminals; j++)
                        if (symbol.FirstSet != null && symbol.FirstSet.Contains(j))
                            w.Write(" {0}", ctx.Symbols[j].Name);
                }
                w.WriteLine();
            }
        }
    }
}


text:
function display(bifd)
%  DISPLAY  Display a functional data object.

%  Last modified 11 May 2004

  if strcmp(class(bifd), 'bifd')
    fprintf('Dimensions of data:\n');
    fdnames = getnames(bifd);
    fprintf(['   ',fdnames{1},'\n']);
    fprintf(['   ',fdnames{2},'\n']);
    fprintf(['   ',fdnames{3},'\n']);
  else
    error('Argument not a functional data object');
  end

  sbasisobj = bifd.sbasisobj;
  fprintf('\nBasis for first argument:\n');
  display(sbasisobj);

  tbasisobj = bifd.tbasisobj;
  fprintf('\nBasis for second argument:\n');
  display(tbasisobj);


text:
<?php

/**
 * Handles the user registration
 * @author Panique
 * @link http://www.php-login.net
 * @link https://github.com/panique/php-login-advanced/
 * @license http://opensource.org/licenses/MIT MIT License
 */
class Registration
{
    /**
     * @var bool success state of registration
     */
    public $registration_successful = false;
    /**
     * @var bool success state of verification
     */
    public $verification_successful = false;
    /**
     * @var array collection of error messages
     */
    public $errors = array();
    /**
     * @var array collection of success / neutral messages
     */
    public $messages = array();
    /**
     * @var object $db_connection The database connection
     */
    private $db_connection = null;

    /**
     * the function "__construct()" automatically starts whenever an object of this class is created,
     * you know, when you do "$login = new Login();"
     */
    public function __construct()
    {
        session_start();

        // if we have such a POST request, call the registerNewUser() method
        if (isset($_POST["register"])) {
            $this->registerNewUser($_POST['user_name'], $_POST['user_email'], $_POST['user_password_new'], $_POST['user_password_repeat'], $_POST["captcha"]);
            // if we have such a GET request, call the verifyNewUser() method
        } else if (isset($_GET["id"]) && isset($_GET["verification_code"])) {
            $this->verifyNewUser($_GET["id"], $_GET["verification_code"]);
        }
    }

    /**
     * handles the entire registration process. checks all error possibilities, and creates a new user in the database if
     * everything is fine
     */
    private function registerNewUser($user_name, $user_email, $user_password, $user_password_repeat, $captcha)
    {
        // we just remove extra space on username and email
        $user_name = trim($user_name);
        $user_email = trim($user_email);

        // check provided data validity
        // TODO: check for "return true" case early, so put this first
        if (strtolower($captcha) != strtolower($_SESSION['captcha'])) {
            $this->errors[] = MESSAGE_CAPTCHA_WRONG;
        } elseif (empty($user_name)) {
            $this->errors[] = MESSAGE_USERNAME_EMPTY;
        } elseif (empty($user_password) || empty($user_password_repeat)) {
            $this->errors[] = MESSAGE_PASSWORD_EMPTY;
        } elseif ($user_password !== $user_password_repeat) {
            $this->errors[] = MESSAGE_PASSWORD_BAD_CONFIRM;
        } elseif (strlen($user_password) < 6) {
            $this->errors[] = MESSAGE_PASSWORD_TOO_SHORT;
        } elseif (strlen($user_name) > 64 || strlen($user_name) < 2) {
            $this->errors[] = MESSAGE_USERNAME_BAD_LENGTH;
        } elseif (!preg_match('/^[a-z\d]{2,64}$/i', $user_name)) {
            $this->errors[] = MESSAGE_USERNAME_INVALID;
        } elseif (empty($user_email)) {
            $this->errors[] = MESSAGE_EMAIL_EMPTY;
        } elseif (strlen($user_email) > 64) {
            $this->errors[] = MESSAGE_EMAIL_TOO_LONG;
        } elseif (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
            $this->errors[] = MESSAGE_EMAIL_INVALID;

            // finally if all the above checks are ok
        } else if ($this->databaseConnection()) {
            // check if username or email already exists
            $query_check_user_name = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email');
            $query_check_user_name->bindValue(':user_name', $user_name, PDO::PARAM_STR);
            $query_check_user_name->bindValue(':user_email', $user_email, PDO::PARAM_STR);
            $query_check_user_name->execute();
            $result = $query_check_user_name->fetchAll();

            // if username or/and email find in the database
            // TODO: this is really awful!
            if (count($result) > 0) {
                for ($i = 0; $i < count($result); $i++) {
                    $this->errors[] = ($result[$i]['user_name'] == $user_name) ? MESSAGE_USERNAME_EXISTS : MESSAGE_EMAIL_ALREADY_EXISTS;
                }
            } else {
                // check if we have a constant HASH_COST_FACTOR defined (in config/hashing.php),
                // if so: put the value into $hash_cost_factor, if not, make $hash_cost_factor = null
                $hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);

                // crypt the user's password with the PHP 5.5's password_hash() function, results in a 60 character hash string
                // the PASSWORD_DEFAULT constant is defined by the PHP 5.5, or if you are using PHP 5.3/5.4, by the password hashing
                // compatibility library. the third parameter looks a little bit shitty, but that's how those PHP 5.5 functions
                // want the parameter: as an array with, currently only used with 'cost' => XX.
                $user_password_hash = password_hash($user_password, PASSWORD_DEFAULT, array('cost' => $hash_cost_factor));
                // generate random hash for email verification (40 char string)
                $user_activation_hash = sha1(uniqid(mt_rand(), true));

                // write new users data into database
                $query_new_user_insert = $this->db_connection->prepare('INSERT INTO users (user_name, user_password_hash, user_email, user_activation_hash, user_registration_ip, user_registration_datetime) VALUES(:user_name, :user_password_hash, :user_email, :user_activation_hash, :user_registration_ip, now())');
                $query_new_user_insert->bindValue(':user_name', $user_name, PDO::PARAM_STR);
                $query_new_user_insert->bindValue(':user_password_hash', $user_password_hash, PDO::PARAM_STR);
                $query_new_user_insert->bindValue(':user_email', $user_email, PDO::PARAM_STR);
                $query_new_user_insert->bindValue(':user_activation_hash', $user_activation_hash, PDO::PARAM_STR);
                $query_new_user_insert->bindValue(':user_registration_ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
                $query_new_user_insert->execute();

                // id of new user
                $user_id = $this->db_connection->lastInsertId();

                if ($query_new_user_insert) {
                    // send a verification email
                    if ($this->sendVerificationEmail($user_id, $user_email, $user_activation_hash)) {
                        // when mail has been send successfully
                        $this->messages[] = MESSAGE_VERIFICATION_MAIL_SENT;
                        $this->registration_successful = true;
                    } else {
                        // delete this users account immediately, as we could not send a verification email
                        $query_delete_user = $this->db_connection->prepare('DELETE FROM users WHERE user_id=:user_id');
                        $query_delete_user->bindValue(':user_id', $user_id, PDO::PARAM_INT);
                        $query_delete_user->execute();

                        $this->errors[] = MESSAGE_VERIFICATION_MAIL_ERROR;
                    }
                } else {
                    $this->errors[] = MESSAGE_REGISTRATION_FAILED;
                }
            }
        }
    }

    /**
     * Checks if database connection is opened and open it if not
     */
    private function databaseConnection()
    {
        // connection already opened
        if ($this->db_connection != null) {
            return true;
        } else {
            // create a database connection, using the constants from config/config.php
            try {
                // Generate a database connection, using the PDO connector
                // @see http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
                // Also important: We include the charset, as leaving it out seems to be a security issue:
                // @see http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Connecting_to_MySQL says:
                // "Adding the charset to the DSN is very important for security reasons,
                // most examples you'll see around leave it out. MAKE SURE TO INCLUDE THE CHARSET!"
                $this->db_connection = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
                return true;
                // If an error is catched, database connection failed
            } catch (PDOException $e) {
                $this->errors[] = MESSAGE_DATABASE_ERROR;
                return false;
            }
        }
    }

    /*
     * sends an email to the provided email address
     * @return boolean gives back true if mail has been sent, gives back false if no mail could been sent
     */

    public function sendVerificationEmail($user_id, $user_email, $user_activation_hash)
    {
        $mail = new PHPMailer;

        // please look into the config/config.php for much more info on how to use this!
        // use SMTP or use mail()
        if (EMAIL_USE_SMTP) {
            // Set mailer to use SMTP
            $mail->IsSMTP();
            //useful for debugging, shows full SMTP errors
            //$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
            // Enable SMTP authentication
            $mail->SMTPAuth = EMAIL_SMTP_AUTH;
            // Enable encryption, usually SSL/TLS
            if (defined(EMAIL_SMTP_ENCRYPTION)) {
                $mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
            }
            // Specify host server
            $mail->Host = EMAIL_SMTP_HOST;
            $mail->Username = EMAIL_SMTP_USERNAME;
            $mail->Password = EMAIL_SMTP_PASSWORD;
            $mail->Port = EMAIL_SMTP_PORT;
        } else {
            $mail->IsMail();
        }

        $mail->From = EMAIL_VERIFICATION_FROM;
        $mail->FromName = EMAIL_VERIFICATION_FROM_NAME;
        $mail->AddAddress($user_email);
        $mail->Subject = EMAIL_VERIFICATION_SUBJECT;

        $link = EMAIL_VERIFICATION_URL . '?id=' . urlencode($user_id) . '&verification_code=' . urlencode($user_activation_hash);

        // the link to your register.php, please set this value in config/email_verification.php
        $mail->Body = EMAIL_VERIFICATION_CONTENT . ' ' . $link;

        // todo : il faut decommenter le bloc si dessous lorsque tous sera fini car tu a force un return true
        /*
            if(!$mail->Send()) {
                $this->errors[] = MESSAGE_VERIFICATION_MAIL_NOT_SENT . $mail->ErrorInfo;
                return false;
            } else {
                return true;
            }
        */
        return true; // todo : enlever ce return de forcement
    }

    /**
     * checks the id/verification code combination and set the user's activation status to true (=1) in the database
     */
    public function verifyNewUser($user_id, $user_activation_hash)
    {
        // if database connection opened
        if ($this->databaseConnection()) {
            // try to update user with specified information
            $query_update_user = $this->db_connection->prepare('UPDATE users SET user_active = 1, user_activation_hash = NULL WHERE user_id = :user_id AND user_activation_hash = :user_activation_hash');
            $query_update_user->bindValue(':user_id', intval(trim($user_id)), PDO::PARAM_INT);
            $query_update_user->bindValue(':user_activation_hash', $user_activation_hash, PDO::PARAM_STR);
            $query_update_user->execute();

            if ($query_update_user->rowCount() > 0) {
                $this->verification_successful = true;
                $this->messages[] = MESSAGE_REGISTRATION_ACTIVATION_SUCCESSFUL;
            } else {
                $this->errors[] = MESSAGE_REGISTRATION_ACTIVATION_NOT_SUCCESSFUL;
            }
        }
    }
}


text:
package com.facebook.buck.cxx.toolchain.nativelink;

import com.facebook.buck.cxx.toolchain.CxxPlatform;
import java.util.Optional;

/**
 * Helper interface for nodes which conditionally support the {@link NativeLinkTarget} interface.
 */
public interface CanProvideNativeLinkTarget {
  Optional<NativeLinkTarget> getNativeLinkTarget(CxxPlatform cxxPlatform);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Contr. Reed Herb. 23: 430 (1975)

#### Original name
Oidium verbenae Thüm. & P.C. Bolle

### Remarks
null


text:
package com.moilioncircle.redis.replicator.cmd.parser;

import org.junit.Test;

import com.moilioncircle.redis.replicator.cmd.impl.DelCommand;
import com.moilioncircle.redis.replicator.cmd.impl.HDelCommand;
import com.moilioncircle.redis.replicator.cmd.impl.LRemCommand;
import com.moilioncircle.redis.replicator.cmd.impl.SRemCommand;
import com.moilioncircle.redis.replicator.cmd.impl.UnLinkCommand;
import com.moilioncircle.redis.replicator.cmd.impl.ZRemCommand;

/**
 * @author Leon Chen
 * @since 2.1.0
 */
public class DelParserTest extends AbstractParserTest {
    @Test
    public void parse() {
        {
            DelParser parser = new DelParser();
            DelCommand cmd = parser.parse(toObjectArray("del key1 key2".split(" ")));
            assertEquals("key1", cmd.getKeys()[0]);
            assertEquals("key2", cmd.getKeys()[1]);
            UnLinkParser parser1 = new UnLinkParser();
            UnLinkCommand cmd1 = parser1.parse(toObjectArray("unlink key1 key2".split(" ")));
            assertEquals("key1", cmd1.getKeys()[0]);
            assertEquals("key2", cmd1.getKeys()[1]);
        }

        {
            HDelParser parser = new HDelParser();
            HDelCommand cmd = parser.parse(toObjectArray("hdel key f1 f2".split(" ")));
            assertEquals("key", cmd.getKey());
            assertEquals("f1", cmd.getFields()[0]);
            assertEquals("f2", cmd.getFields()[1]);
        }

        {
            LRemParser parser = new LRemParser();
            LRemCommand cmd = parser.parse(toObjectArray("lrem key 1 val".split(" ")));
            assertEquals("key", cmd.getKey());
            assertEquals("val", cmd.getValue());
            assertEquals(1, cmd.getIndex());
        }

        {
            SRemParser parser = new SRemParser();
            SRemCommand cmd = parser.parse(toObjectArray("srem key m1 m2".split(" ")));
            assertEquals("key", cmd.getKey());
            assertEquals("m1", cmd.getMembers()[0]);
            assertEquals("m2", cmd.getMembers()[1]);
        }

        {
            ZRemParser parser = new ZRemParser();
            ZRemCommand cmd = parser.parse(toObjectArray("zrem key m1 m2".split(" ")));
            assertEquals("key", cmd.getKey());
            assertEquals("m1", cmd.getMembers()[0]);
            assertEquals("m2", cmd.getMembers()[1]);
        }
    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sida 19:845. 2001

#### Original name
Yucca newberryi McKelvey

### Remarks
null


text:
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Vocabularies;
using Microsoft.OData.Edm.Vocabularies.V1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace OdataToEntity.ModelBuilder
{
    internal sealed class EntityTypeInfo
    {
        private readonly bool _isDbQuery;
        private readonly List<KeyValuePair<PropertyInfo, EdmStructuralProperty>> _keyProperties;
        private readonly OeEdmModelMetadataProvider _metadataProvider;
        private readonly List<FKeyInfo> _navigationClrProperties;

        public EntityTypeInfo(OeEdmModelMetadataProvider metadataProvider, Type clrType, EdmEntityType edmType, bool isRefModel, bool isDbQuery)
        {
            _metadataProvider = metadataProvider;
            ClrType = clrType;
            EdmType = edmType;
            IsRefModel = isRefModel;
            _isDbQuery = isDbQuery;

            _keyProperties = new List<KeyValuePair<PropertyInfo, EdmStructuralProperty>>(1);
            _navigationClrProperties = new List<FKeyInfo>();
        }

        private void AddDbQueryKeys()
        {
            EdmType.AddKeys(EdmType.StructuralProperties());
        }
        private void AddKeys()
        {
            if (_keyProperties.Count == 0)
            {
                PropertyInfo? key = OeModelBuilderHelper.GetConventionalKeyProperty(ClrType);
                if (key == null)
                {
                    if (EdmType.Key().Any() || ClrType.IsAbstract)
                        return;

                    throw new InvalidOperationException("Key property not matching");
                }

                var edmProperty = (EdmStructuralProperty)EdmType.GetPropertyIgnoreCase(key.Name);
                _keyProperties.Add(new KeyValuePair<PropertyInfo, EdmStructuralProperty>(key, edmProperty));
            }

            if (_keyProperties.Count == 1)
            {
                EdmType.AddKeys(_keyProperties[0].Value);
                return;
            }

            var keys = new ValueTuple<EdmStructuralProperty, int>[_keyProperties.Count];
            for (int i = 0; i < _keyProperties.Count; i++)
            {
                int order = _metadataProvider.GetOrder(_keyProperties[i].Key);
                if (order == -1)
                {
                    EdmType.AddKeys(_keyProperties.Select(p => p.Value));
                    return;
                }

                keys[i] = new ValueTuple<EdmStructuralProperty, int>(_keyProperties[i].Value, order);
            }
            EdmType.AddKeys(keys.OrderBy(p => p.Item2).Select(p => p.Item1));
        }
        public void BuildStructuralProperties(EdmModel edmModel, Dictionary<Type, EntityTypeInfo> entityTypes,
            Dictionary<Type, EdmEnumType> enumTypes, Dictionary<Type, EdmComplexType> complexTypes)
        {
            foreach (PropertyInfo clrProperty in _metadataProvider.GetProperties(ClrType))
                if (!_metadataProvider.IsNotMapped(clrProperty))
                {
                    EdmStructuralProperty? edmProperty = BuildStructuralProperty(entityTypes, enumTypes, complexTypes, clrProperty);
                    if (edmProperty != null && _metadataProvider.IsDatabaseGenerated(clrProperty))
                    {
                        var databaseGenerated = new EdmVocabularyAnnotation(edmProperty, CoreVocabularyModel.ComputedTerm, new EdmBooleanConstant(true));
                        edmModel.SetVocabularyAnnotation(databaseGenerated);
                    }
                }

            if (_isDbQuery)
                AddDbQueryKeys();
            else
                AddKeys();
        }
        private EdmStructuralProperty? BuildStructuralProperty(Dictionary<Type, EntityTypeInfo> entityTypes,
            Dictionary<Type, EdmEnumType> enumTypes, Dictionary<Type, EdmComplexType> complexTypes, PropertyInfo clrProperty)
        {
            bool isNullable = !_metadataProvider.IsRequired(clrProperty);
            IEdmTypeReference? typeRef = PrimitiveTypeHelper.GetPrimitiveTypeRef(clrProperty, isNullable);
            if (typeRef == null)
            {
                Type? underlyingType = null;
                if (clrProperty.PropertyType.IsEnum ||
                    (underlyingType = Nullable.GetUnderlyingType(clrProperty.PropertyType)) != null && underlyingType.IsEnum)
                {
                    Type clrPropertyType = underlyingType ?? clrProperty.PropertyType;
                    if (!enumTypes.TryGetValue(clrPropertyType, out EdmEnumType? edmEnumType))
                    {
                        edmEnumType = OeEdmModelBuilder.CreateEdmEnumType(clrPropertyType);
                        enumTypes.Add(clrPropertyType, edmEnumType);
                    }
                    typeRef = new EdmEnumTypeReference(edmEnumType, underlyingType != null);
                }
                else
                {
                    if (complexTypes.TryGetValue(clrProperty.PropertyType, out EdmComplexType? edmComplexType))
                        typeRef = new EdmComplexTypeReference(edmComplexType, clrProperty.PropertyType.IsClass);
                    else
                    {
                        FKeyInfo? fkeyInfo = FKeyInfo.Create(_metadataProvider, entityTypes, this, clrProperty);
                        if (fkeyInfo != null)
                            _navigationClrProperties.Add(fkeyInfo);
                        return null;
                    }
                }
            }
            else
            {
                if (clrProperty.PropertyType == typeof(DateTime?) && enumTypes.ContainsKey(typeof(DateTime?)))
                {
                    var edmType = enumTypes[typeof(DateTime?)];
                    typeRef = new EdmEnumTypeReference(edmType, true);
                }
            }

            EdmStructuralProperty edmProperty = clrProperty is Infrastructure.OeShadowPropertyInfo ?
                new OeEdmStructuralShadowProperty(EdmType, clrProperty.Name, typeRef, clrProperty) :
                new EdmStructuralProperty(EdmType, clrProperty.Name, typeRef);
            EdmType.AddProperty(edmProperty);
            if (_metadataProvider.IsKey(clrProperty))
                _keyProperties.Add(new KeyValuePair<PropertyInfo, EdmStructuralProperty>(clrProperty, edmProperty));

            return edmProperty;
        }
        public override String ToString()
        {
            return ClrType.FullName ?? ClrType.Name;
        }

        public Type ClrType { get; }
        public EdmEntityType EdmType { get; }
        public bool IsRefModel { get; }
        public IReadOnlyList<FKeyInfo> NavigationClrProperties => _navigationClrProperties;
    }
}


text:
function f = dropletTracking()
%DROPLETTRACKING starts the DropletTracking App

    tr = DropletTracking();
    dm = tr.open();

    f = dm.getFigure();
end