text:
// TODO: Add GoogleServices-Info.plist from Firebase iOS project, Right click Build Action, Mark as Bundle Resource

using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;
using UserNotifications;

using Firebase.CloudMessaging;

namespace FCM.iOS
{
	[Register("AppDelegate")]
	public class AppDelegate : Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, IUNUserNotificationCenterDelegate
	{
		public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions)
		{
			Xamarin.Forms.Forms.Init();

			LoadApplication(new App());

			// get permission for notification
			if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
			{
				// iOS 10
				var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
				UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) =>
				{
					Console.WriteLine(granted);
				});

				// For iOS 10 display notification (sent via APNS)
				UNUserNotificationCenter.Current.Delegate = this;
			}
			else
			{

				var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
				var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);

				UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
			}

			UIApplication.SharedApplication.RegisterForRemoteNotifications();

			// Firebase component initialize
			Firebase.Analytics.App.Configure();

			Firebase.InstanceID.InstanceId.Notifications.ObserveTokenRefresh((sender, e) =>
			{
				var newToken = Firebase.InstanceID.InstanceId.SharedInstance.Token;
				// if you want to send notification per user, use this token
				System.Diagnostics.Debug.WriteLine(newToken);

				connectFCM();
			});

			return base.FinishedLaunching(uiApplication, launchOptions);
		}

		public override void DidEnterBackground(UIApplication uiApplication)
		{
			Messaging.SharedInstance.Disconnect();
		}

		public override void OnActivated(UIApplication uiApplication)
		{
			connectFCM();
			base.OnActivated(uiApplication);
		}

		public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
		{
#if DEBUG
			Firebase.InstanceID.InstanceId.SharedInstance.SetApnsToken(deviceToken, Firebase.InstanceID.ApnsTokenType.Sandbox);
#endif
#if RELEASE
			Firebase.InstanceID.InstanceId.SharedInstance.SetApnsToken(deviceToken, Firebase.InstanceID.ApnsTokenType.Prod);
#endif
		}

		// iOS 9 <=, fire when recieve notification foreground
		public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
		{
			Messaging.SharedInstance.AppDidReceiveMessage(userInfo);

			// Generate custom event
			NSString[] keys = { new NSString("Event_type") };
			NSObject[] values = { new NSString("Recieve_Notification") };
			var parameters = NSDictionary<NSString, NSObject>.FromObjectsAndKeys(keys, values, keys.Length);

			// Send custom event
			Firebase.Analytics.Analytics.LogEvent("CustomEvent", parameters);

			if (application.ApplicationState == UIApplicationState.Active)
			{
				System.Diagnostics.Debug.WriteLine(userInfo);
				var aps_d = userInfo["aps"] as NSDictionary;
				var alert_d = aps_d["alert"] as NSDictionary;
				var body = alert_d["body"] as NSString;
				var title = alert_d["title"] as NSString;
				debugAlert(title, body);
			}
		}

		// iOS 10, fire when recieve notification foreground
		[Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
		public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
		{
			var title = notification.Request.Content.Title;
			var body = notification.Request.Content.Body;
			debugAlert(title, body);
		}

		private void connectFCM()
		{
			Messaging.SharedInstance.Connect((error) =>
			{
				if (error == null)
				{
					//TODO: Change Topic to what is required
					Messaging.SharedInstance.Subscribe("/topics/all");
				}
				System.Diagnostics.Debug.WriteLine(error != null ? "error occured" : "connect success");
			});
		}

		private void debugAlert(string title, string message)
		{
			var alert = new UIAlertView(title ?? "Title", message ?? "Message", null, "Cancel", "OK");
			alert.Show();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.sd.xml;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.sd.io.DataHelper;
import org.sd.util.tree.Tree;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Utilities for interacting with a dom.
 *

 * @author Spence Koehler
 */
public class DomUtil {

  /**
   *  Get the first child that is an DomElement under the given domElement
   *  or null.
   */
  public static DomElement getFirstChild(DomElement domElement) {
    DomElement result = null;

    if (domElement != null && domElement.hasChildNodes()) {
      final NodeList childNodes = domElement.getChildNodes();
      for (int i = 0; i < childNodes.getLength(); ++i) {
        final Node childNode = childNodes.item(i);
        if (childNode.getNodeType() == DomNode.ELEMENT_NODE) {
          result = (DomElement)childNode;
          break;
        }
      }
    }

    return result;
  }

  /**
   *  Returns the integer value of the node's text or the default value or throws
   *  and expection if the existing text in a found element cannot be parsed as an
   *  integer.
   */
  public static int getSelectedNodeInt(DomElement domElement, String xPath, int defaultValue) {
    final DomNode selectedNode = (DomNode)domElement.selectSingleNode(xPath);
    return getNodeInt(selectedNode, defaultValue);
  }

  /**
   *  Returns the integer value of the node's text or the default value or throws
   *  and expection if the existing text cannot be parsed as an integer.
   */
  public static int getNodeInt(DomNode domNode, int defaultValue) {
    int result = defaultValue;

    if (domNode != null) {
      final String text = domNode.getTextContent();
      if (text != null && !"".equals(text)) {
        result = Integer.parseInt(text);
      }
    }

    return result;
  }

  /**
   *  Utility to get the trimmed node text under a dom node.
   *
   *  This trims extra whitespace around node text and inserts a single
   *  space character between node texts.
   *
   *  NOTE: Currently text is not trimmed within a text node's String.
   */
  public static String getTrimmedNodeText(DomNode domNode) {
    final DomTextWalker textWalker = new DomTextWalker(domNode);
    return textWalker.getTrimmedNodeText();
  }

  /**
   *  Get the position of the deep node's trimmed text as an offset within
   *  the ancestor's node text.
   */
  public static int getTextPos(DomNode ancestorNode, DomNode deepNode) {
    final DomTextWalker textWalker = new DomTextWalker(ancestorNode);
    return textWalker.getTextPos(deepNode);
  }

  /**
   *  Given a dom node over text, find the deepest dom node that fully
   *  encompasses the portion of text from startPos to endPos.
   */
  public static DomNode getDeepestNode(DomNode topNode, int startPos, int endPos) {
    int[] newStartPos = new int[]{0};
    int[] newEndPos = new int[]{0};
    return getDeepestNode(topNode, startPos, endPos, newStartPos, newEndPos);
  }

  /**
   *  Given a dom node over text, find the text nodes that contain the
   *  consecutive text from startPos to endPos.
   *
   *  @param topNode The top dom node over the text
   *  @param startPos The starting position of text under the topNode (inclusive)
   *  @param endPos The ending position of text under the topNode (exclusive)
   *  @param newStartPos The starting position of text within result[0].
   *  @param newEndPos The ending position of text within result[N-1].
   *
   *  @return The list of consecutive non-empty text nodes encompassing the text.
   */
  public static List<DomText> getTextNodes(DomNode topNode, int startPos, int endPos, int[] newStartPos, int[] newEndPos) {
    final DomTextWalker textWalker = new DomTextWalker(topNode);
    return textWalker.getTextNodes(startPos, endPos, newStartPos, newEndPos);
  }

  /**
   *  Given a dom node over text, find the deepest dom node that fully
   *  encompasses the portion of text from startPos to endPos.
   *
   *  Return in the reference parameters the new starting and ending position
   *  of the text with respect to the returned node.
   */
  public static DomNode getDeepestNode(DomNode topNode, int startPos, int endPos, int[] newStartPos, int[] newEndPos) {
    DomNode result = topNode;

    if (topNode.getNodeType() == DomNode.TEXT_NODE) return result;

    final DomTextWalker textWalker = new DomTextWalker(topNode);
    final List<DomText> textNodes = textWalker.getTextNodes(startPos, endPos, newStartPos, newEndPos);

    if (textNodes != null) {
      final DomNode startNode = textNodes.get(0);
      final DomNode endNode = textNodes.get(textNodes.size() - 1);

      if (startNode != null && endNode != null) {
        if (startNode != endNode) {
          result = getDeepestCommonAncestor(startNode, endNode);

          if (result != startNode) {
            if (result == topNode) {
              // back where we started from, no need to waste cycles computing
              newStartPos[0] = startPos;
              newEndPos[0] = endPos;
            }
            else {
              // shift newStartPos and newEndPos relative to result
              newStartPos[0] += DomUtil.getTextPos(result, startNode);
              newEndPos[0] = newStartPos[0] + (endPos - startPos);
            }
          }
        }
        else {
          result = startNode;
        }
      }
    }

    return result;
  }

  /**
   *  Determine whether the given DomNode is a non-empty text node.
   */
  public static boolean isNonEmptyTextNode(Node domNode) {
    boolean result = false;

    if (domNode.getNodeType() == Node.TEXT_NODE) {
      final String nodeText = domNode.getNodeValue();
      result = nodeText != null && !"".equals(nodeText.trim());
    }

    return result;
  }

  /**
   *  Create an dom element with the given name, optionally adding as a child of refNode.
   */
  public static DomElement createElement(DomNode refNode, String name, boolean addAsChild) {
    final DomElement newElement = (DomElement)refNode.getOwnerDocument().createElement(name);

    if (addAsChild) {
      refNode.appendChild(newElement);
    }

    return newElement;
  }

  /**
   *  Add an attribute to the given dom node.
   */
  public static DomAttribute addAttribute(DomElement domElement, String attrName, String attrValue) {
    domElement.setAttribute(attrName, attrValue);
    return (DomAttribute)domElement.getAttributeNode(attrName);
  }

  /**
   *  Prune the given DomNode from its document.
   */
  public static void pruneNode(DomNode domNode) {
    final Node parentNode = domNode.getParentNode();

    if (parentNode != null) {
      parentNode.removeChild(domNode);
    }
  }

  /**
   *  Get the depth of the given node in its DOM tree, where the root
   *  (DocumentElement) is at depth 0.
   */
  public static int getDepth(DomNode domNode) {
    int result = -1;

    final short nodeType = domNode.getNodeType();
    if (nodeType == DomNode.ELEMENT_NODE) {
      result = domNode.getDepth() + 1;
    }
    else if (nodeType == DomNode.DOCUMENT_NODE) {
      result = 0;
    }

    return result;
  }

  /**
   *  Get the DomNode instances from the root to the given node (inclusive).
   */
  public static LinkedList<DomNode> getRootPath(DomNode domNode) {
    final LinkedList<DomNode> result = new LinkedList<DomNode>();

    while (domNode != null) {
      result.addFirst(domNode);
      domNode = (DomNode)domNode.getParentNode();
    }

    return result;
  }

  /**
   *  Build a path String for the domNode, optionally including sibling
   *  index information and text content.
   */
  public static String buildPathString(DomNode domNode, boolean indexFlag, boolean textFlag) {
    final LinkedList<DomNode> rootPath = DomUtil.getRootPath(domNode);
    return buildPathString(rootPath, indexFlag, textFlag);
  }

  /**
   *  Build a path String for the rootPath, optionally including sibling
   *  index information and text content.
   */
  public static String buildPathString(LinkedList<DomNode> rootPath, boolean indexFlag, boolean textFlag) {
    final StringBuilder result = new StringBuilder();

    for (DomNode curDomNode : rootPath) {
      final short nodeType = curDomNode.getNodeType();
      if (nodeType == DomNode.TEXT_NODE) {
        if (textFlag) {
          result.append("='").append(curDomNode.getNodeValue()).append('\'');
        }
      }
      else {
        if (result.length() > 0) result.append('/');
        result.append(curDomNode.getNodeName());

        if (indexFlag) {
          final int sibNum = DomUtil.getRelativeSiblingNumber(curDomNode);
          result.append('[').append(sibNum).append(']');
        }
      }
    }

    return result.toString();
  }

  public static DomNode findDomNode(DomElement rootElement, String indexedPathString) {
    DomNode result = rootElement;

    final String[] pathPieces = indexedPathString.split("/");
    final int[] pathIndex = new int[]{0};
    final String rootTag = parseIndexedPathPiece(pathPieces[0], pathIndex);

    if (!rootElement.getNodeName().equals(rootTag) || DomUtil.getRelativeSiblingNumber(rootElement) != pathIndex[0]) {
      // rootElement doesn't align with first indexedPathString
      return null;
    }

    for (int pathPieceIndex = 1; pathPieceIndex < pathPieces.length; ++pathPieceIndex) {
      final String pathPiece = pathPieces[pathPieceIndex];
      final String pieceTag = parseIndexedPathPiece(pathPiece, pathIndex);

      result = findChild(result, pieceTag, pathIndex[0]);

      if (result == null) break;
    }

    return result;
  }

  public static String parseIndexedPathPiece(String pathPiece, int[] index) {
    String result = pathPiece;
    index[0] = 0;

    final int lbPos = pathPiece.indexOf('[');
    if (lbPos >= 0) {
      result = pathPiece.substring(0, lbPos);

      final int rbPos = pathPiece.lastIndexOf(']');
      if (rbPos >= 0) {
        final String indexString = pathPiece.substring(lbPos + 1, rbPos).trim();
        if (!"".equals(indexString)) {
          index[0] = Integer.parseInt(indexString);
        }
      }
    }

    return result;
  }

  public static DomNode findChild(DomNode parent, String nodeName, int relativeSibNum) {
    DomNode result = null;

    if (parent.hasChildNodes()) {
      int sibNum = -1;
      final NodeList childNodes = parent.getChildNodes();
      for (int childNum = 0; childNum < childNodes.getLength(); ++childNum) {
        final Node childNode = childNodes.item(childNum);
        if (childNode == null || childNode.getNodeType() != DomNode.ELEMENT_NODE) continue;
        if (nodeName.equals(childNode.getNodeName())) {
          ++sibNum;
          if (sibNum == relativeSibNum) {
            result = (DomNode)childNode;
            break;
          }
        }
      }
    }

    return result;
  }

  /**
   *  Get the deepest common ancestor of the two nodes (inclusive of either
   *  node.)
   */
  public static DomNode getDeepestCommonAncestor(DomNode node1, DomNode node2) {
    if (node1 == null || node2 == null) return null;
    if (node1 == node2) return node1;

    final LinkedList<DomNode> rootPath1 = DomUtil.getRootPath(node1);
    final LinkedList<DomNode> rootPath2 = DomUtil.getRootPath(node2);

    int dcaIndex = getDeepestCommonAncestorIndex(rootPath1, rootPath2);

    return (dcaIndex >= 0) ? rootPath1.get(dcaIndex) : null;
  }

  /**
   *  Get the index of the deepest common ancestor accross the given rootPaths.
   */
  public static int getDeepestCommonAncestorIndex(LinkedList<DomNode> rootPath1, LinkedList<DomNode> rootPath2) {
    if (rootPath1 == null || rootPath2 == null) return -1;

    int result = -1;

    final Iterator<DomNode> pathEnumerator1 = rootPath1.iterator();
    final Iterator<DomNode> pathEnumerator2 = rootPath2.iterator();

    int curIndex = 0;
    while (pathEnumerator1.hasNext() && pathEnumerator2.hasNext()) {
      final DomNode curNode1 = pathEnumerator1.next();
      final DomNode curNode2 = pathEnumerator2.next();

      if (curNode1 != curNode2) {
        // paths diverge here
        break;
      }
      else {
        result = curIndex++;
      }
    }

    return result;
  }

  /**
   *  Find the child node of the parent that is an ancestor of descendant.
   */
  public static DomNode findChildNode(DomNode parent, DomNode descendant) {
    final LinkedList<DomNode> rootPath = getRootPath(descendant);
    return findChildNode(rootPath, parent, descendant);
  }

  /**
   *  Find the child node of the parent that is an ancestor of descendant
   *  using the given rootPath.
   */
  public static DomNode findChildNode(LinkedList<DomNode> rootPath, DomNode parent, DomNode descendant) {
    if (parent == descendant) return null;

    DomNode result = null;

    final int pIdx = rootPath.indexOf(parent);
    if (pIdx != -1 && pIdx + 1 < rootPath.size()) {
      result = rootPath.get(pIdx + 1);
    }

    return result;
  }

  /**
   *  Get the absolute sibling number of the given node, including counting
   *  text nodes.
   */
  public static int getAbsoluteSiblingNumber(DomNode domNode) {
    int result = 0;

    Node curNode = domNode;

    while (curNode.getPreviousSibling() != null) {
      curNode = curNode.getPreviousSibling();
      if (curNode.getNodeType() == Node.ELEMENT_NODE) ++result;
    }

    return result;
  }

  /**
   *  Get the relative sibling number of the given node, which is defined as
   *  the occurrence among (not-necessarily consecutive) siblings of the
   *  domNode's name.
   */
  public static int getRelativeSiblingNumber(DomNode domNode) {
    int result = 0;

    final String nodeName = domNode.getNodeName();
    Node curNode = domNode;

    while (curNode.getPreviousSibling() != null) {
      curNode = curNode.getPreviousSibling();

      if (curNode.getNodeType() == Node.ELEMENT_NODE) {
        if (nodeName.equals(curNode.getNodeName())) {
          ++result;
        }
      }
    }

    return result;
  }

  /**
   * Get the subtree's xml that includes the path from the root to the node
   * and the node's entire subTree.
   *
   * @return null if domNode is null; otherwise, the subTree string.
   */
  public static String getSubtreeXml(DomNode domNode) {
    if (domNode == null) return null;

    Tree<XmlLite.Data> nodeTree = domNode.asTree();
    String nodeXml = null;

    try {
      nodeXml = XmlLite.asXml(nodeTree, false);
    }
    catch (IOException e) {
      System.err.println("Warning: couldn't convert tree to xml text!");
      e.printStackTrace(System.err);
      nodeXml = null;
    }

    if (nodeXml == null) return null;

    final StringBuilder result = new StringBuilder();

    result.append(nodeXml);
    for (nodeTree = nodeTree.getParent(); nodeTree != null; nodeTree = nodeTree.getParent()) {
      // for each parent
      final XmlLite.Data data = nodeTree.getData();
      // insert open tag in front
      result.insert(0, data.toString());
      // append close tag at end
      final XmlLite.Tag tag = data.asTag();
      result.append("</").append(tag.name).append('>');
    }

    return result.toString();
  }

  /**
   * Write the (possibly null) domNode to the output.
   *

   * Write the node and its full subtree as well as its path back to its
   * root.
   */
  public static void writeDomNode(DataOutput dataOutput, DomNode domNode) throws IOException {
    if (domNode == null) {
      dataOutput.writeBoolean(false);
      return;
    }

    final Tree<XmlLite.Data> nodeTree = domNode.asTree();
    dataOutput.writeInt(nodeTree.depth());

    final String xmlString = getSubtreeXml(domNode);
    DataHelper.writeString(dataOutput, xmlString);
  }

  /**
   * Read the (possibly null) domNode from the input.
   *

   * The node will be returned with its subtree along with its path back to the
   * root preserved.
   */
  public static DomNode readDomNode(DataInput dataInput) throws IOException {

    final boolean hasData = dataInput.readBoolean();
    if (!hasData) return null;

    final int nodeDepth = dataInput.readInt();

    final String xmlString = DataHelper.readString(dataInput);
    Tree<XmlLite.Data> xmlTree = XmlFactory.buildXmlTree(xmlString, true, false);

    for (int depth = 0; depth < nodeDepth; ++depth) {
      if (xmlTree.numChildren() != 1) {
        xmlTree = null;
        break;
      }
      xmlTree = xmlTree.getChildren().get(0);
    }

    return xmlTree == null ? null : xmlTree.getData().asDomNode();
  }
}


text:
from myapp import app
app.run(debug=True)


text:
using Newtonsoft.Json;

namespace OfficeDevPnP.Core.Pages
{
#if !SP2013 && !SP2016
    /// <summary>
    /// Base class representing the json control data that will describe a control versus the zones and sections on a page
    /// </summary>
    public class ClientSideCanvasPosition
    {

        /// <summary>
        /// Gets or sets JsonProperty "zoneIndex"
        /// </summary>
        [JsonProperty(PropertyName = "zoneIndex")]
        public float ZoneIndex { get; set; }
        /// <summary>
        /// Gets or sets JsonProperty "sectionIndex"
        /// </summary>
        [JsonProperty(PropertyName = "sectionIndex")]
        public int SectionIndex { get; set; }
        /// <summary>
        /// Gets or sets JsonProperty "sectionFactor"
        /// </summary>
        [JsonProperty(PropertyName = "sectionFactor", NullValueHandling = NullValueHandling.Ignore)]
        public int? SectionFactor { get; set; }

#if !SP2019
        /// <summary>
        /// Gets or sets JsonProperty "layoutIndex"
        /// </summary>
        [JsonProperty(PropertyName = "layoutIndex", NullValueHandling = NullValueHandling.Ignore)]
        public int? LayoutIndex { get; set; }
#endif
    }
#endif
}


text:
#import <Foundation/Foundation.h>
#import "RMXRemoteController.h"

@class RMXVariable;

/** A Firebase implementation of Remote Controllers.  */
@interface RMXFirebaseRemoteController : NSObject<RMXRemoteController>

@end


text:
from myspider.analyze import Analyze

text = 'q23rjfkjt9032u4jr3849612_)*&nbb'
rule = '\\d{4}'
analyze1 = Analyze('display')
analyze2 = Analyze('regeexpr')

def test_analyze(analyze, text, rule):
    print analyze.analyze(text, rule)

test_analyze(analyze1, text, rule)
test_analyze(analyze2, text, rule)


text:
/**
 * @ngdoc directive
 * @name umbraco.directives.directive:umbConfirm
 * @function
 * @description
 * A confirmation dialog
 *
 * @restrict E
 */
function confirmDirective() {
    return {
        restrict: "E",    // restrict to an element
        replace: true,   // replace the html element with the template
        templateUrl: 'views/directives/umb-confirm.html',
        scope: {
            onConfirm: '=',
            onCancel: '=',
            caption: '@'
        },
        link: function (scope, element, attr, ctrl) {

        }
    };
}
angular.module('umbraco.directives').directive("umbConfirm", confirmDirective);


text:
package org.jbpm.dashboard.renderer.client.panel.widgets;

import java.util.HashMap;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.dashbuilder.common.client.error.ClientRuntimeError;
import org.dashbuilder.displayer.client.Displayer;
import org.jbpm.dashboard.renderer.client.panel.i18n.DashboardConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.server.api.exception.KieServicesHttpException;
import org.kie.workbench.common.workbench.client.resources.i18n.DefaultWorkbenchConstants;
import org.mockito.Mock;

import static org.mockito.Mockito.*;

@RunWith(GwtMockitoTestRunner.class)
public class DisplayerContainerTest {

    private DisplayerContainer container;

    @Mock
    private DisplayerContainerView view;

    @Mock
    private Displayer currentDisplayer;

    @Before
    public void setup() {
        container = spy(new DisplayerContainer(new HashMap<>(),
                                               false));
        container.view = view;
        container.currentDisplayer = currentDisplayer;
    }

    @Test
    public void testShowErrorWhenIsKieServerForbiddenException() {
        final ClientRuntimeError clientRuntimeError = makeClientRuntimeError(makeHttpException(403));

        container.showError(clientRuntimeError);

        verify(view).showError(DefaultWorkbenchConstants.INSTANCE.KieServerError403(),
                               clientRuntimeError.getCause());
    }

    @Test
    public void testShowErrorWhenIsKieServerUnauthorizedException() {
        final ClientRuntimeError clientRuntimeError = makeClientRuntimeError(makeHttpException(401));

        container.showError(clientRuntimeError);

        verify(view).showError(DefaultWorkbenchConstants.INSTANCE.KieServerError401(),
                               clientRuntimeError.getCause());
    }

    @Test
    public void testShowErrorWhenIsNotKieServerUnauthorizedException() {
        final ClientRuntimeError clientRuntimeError = makeClientRuntimeError(new Throwable());

        doNothing().when(container).showErrorPopup(any());

        container.showError(clientRuntimeError);

        verify(view).showEmpty(currentDisplayer);
        verify(container).showErrorPopup(DashboardConstants.INSTANCE.dashboardCouldNotBeLoaded());
    }

    private KieServicesHttpException makeHttpException(final int httpCode) {
        return new KieServicesHttpException("",
                                            httpCode,
                                            "",
                                            "");
    }

    private ClientRuntimeError makeClientRuntimeError(final Throwable throwable) {
        return new ClientRuntimeError("",
                                      throwable);
    }
}


text:
.leaflet-backdrop {
    position: absolute;
    display: block;
    width: 100%;
    height: 100%;
}


text:
local_path=$(cd $(dirname $0);pwd)
source $local_path/Common
xpk_path=$local_path/../testapp
diffidSameVersionApp="diffid_same_version_tests"

getPkgid $diffidSameVersionApp
get_uninstall=`pkgcmd -u -n  $pkg_id -q`
pkgcmd -i -t xpk -p  $xpk_path/$diffidSameVersionApp.xpk -q
if [[ $? -eq 0 ]]; then
                echo "Install Pass"
        else
                echo "Install Fail"
                exit 1
fi

getPkgid $diffidSameVersionApp
get_uninstall=`pkgcmd -u -n  $pkg_id -q`
if [[ $? -eq 0 ]]; then
                echo "Uninstall Pass"
        else
                echo "Unistall Fail"
                exit 1
fi


text:
function otherScripts(){

}
function clickHandlers(){

    $('#tableOpenOffers').on('click', '.edit', function() {
        var offerId = $(this).closest('tr').attr('id');
        if (offerId) {
            var win = window.open('/b2b_teklif?id=' + offerId, '_blank');
            win.focus();
         }
    });
}
function formHandlers(){
}


text:
<?php

/**
 * @file
 * Contains \Drupal\field\FieldConfigAccessControlHandler.
 */

namespace Drupal\field;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Defines the access control handler for the field entity type.
 *
 * @see \Drupal\field\Entity\FieldConfig
 */
class FieldConfigAccessControlHandler extends EntityAccessControlHandler {

  /**
   * {@inheritdoc}
   */
  protected function checkAccess(EntityInterface $entity, $operation, $langcode, AccountInterface $account) {
    if ($operation == 'delete') {
      $field_storage_entity = $entity->getFieldStorageDefinition();
      if ($field_storage_entity->isLocked()) {
        return AccessResult::forbidden()->cacheUntilEntityChanges($field_storage_entity);
      }
      else {
        return AccessResult::allowedIfHasPermission($account, 'administer ' . $entity->entity_type . ' fields')->cacheUntilEntityChanges($field_storage_entity);
      }
    }
    return AccessResult::allowedIfHasPermission($account, 'administer ' . $entity->entity_type . ' fields');
  }

}


text:
<Alloy>
	<Window class="container">
		<ImageView id="topbg" image="/lib/top_clear.png"></ImageView>
		<ScrollView id="scroll_view" contentWidth="auto" width="100%">
			<ImageView id="back" image="/lib/back.png" onClick="back" onTouchstart="touch_start_back"  onTouchend="touch_end_back"></ImageView>
			<ImageView id="in_house_image" image="/lib/main_page/in_house_image.png" width="100%"></ImageView>
		</ScrollView>
		<ImageView id="id_house_camera" image="/lib/main_page/house_camera.png" bottom="5%" left="5%" onClick="show_cam"></ImageView>
	</Window>
</Alloy>


text:
package kikaha.core.modules.smart;

import static org.junit.Assert.*;
import java.io.IOException;
import javax.inject.*;
import io.undertow.server.HttpHandler;
import kikaha.core.*;
import kikaha.core.test.KikahaRunner;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 *
 */
@Singleton
@RunWith(KikahaRunner.class)
public class CORSFilterModuleTest {

	final DeploymentContext context = new DeploymentContext();

	@Inject
	CORSFilterModule module;

	@Inject
	NotFoundHandler notFoundHandler;

	@Test
	public void ensureThatHaveDeployedTheCORSModule() throws IOException {
		module.load( null, context );
		assertNotNull( context.rootHandler() );
		assertEquals( CORSFilterHttpHandler.class, context.rootHandler().getClass() );
	}

	@Test
	public void ensureThatDeployedModulePointsToOriginalRootHandlerAsNextHandlerInTheChain() throws IOException {
		final HttpHandler originalHandler = context.rootHandler();
		module.load( null, context );

		final CORSFilterHttpHandler newHandler = (CORSFilterHttpHandler)context.rootHandler();
		assertEquals( originalHandler, newHandler.next );
	}

	@Test
	public void ensureThatDeployedModulePointsToNotFoundHandlerAsFailureHandler() throws IOException {
		module.load( null, context );

		final CORSFilterHttpHandler newHandler = (CORSFilterHttpHandler)context.rootHandler();
		assertEquals( notFoundHandler, newHandler.notFound );
	}

	@Test
	public void ensureThatDeployedModuleHaveReadGETAndPOSTAsAllowedMethodsFromDefaultConfig() throws IOException {
		module.load( null, context );

		final CORSFilterHttpHandler newHandler = (CORSFilterHttpHandler)context.rootHandler();
		assertEquals( 1, newHandler.config.allowedMethods.size() );
		assertTrue( newHandler.config.allowedMethods.contains("GET") );
	}

	@Test
	public void ensureThatDeployedModuleHaveReadValidOriginsFromConfig() throws IOException {
		module.load( null, context );

		final CORSFilterHttpHandler newHandler = (CORSFilterHttpHandler)context.rootHandler();
		assertEquals( 2, newHandler.config.allowedOriginMatchers.size() );
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using STM.Interfaces;
using System.Threading;
using STM.Implementation.Exceptions;
using System.Diagnostics;
using STM.Implementation.Common;

namespace STM.Implementation.Lockbased
{
    public static class STMSystem
    {
        internal static readonly int TIME_OUT = 100;
        /// <summary>
        /// Max attempts. Set to same as Clojure
        /// </summary>
        internal static readonly int MAX_ATTEMPTS = 10000;

        #region Atomic

        public static T Atomic<T>(Func<T> stmAction)
        {
            return AtomicInternal(new List<Func<T>> {stmAction});
        }

        public static T Atomic<T>(Func<T> stmAction, params Func<T>[] orElses)
        {
            var atomics = new List<Func<T>>(orElses.Length+1) {stmAction};
            atomics.AddRange(orElses);
            return AtomicInternal(atomics);
        }

        public static void Atomic(Action stmAction)
        {
            AtomicInternal(new List<Func<bool>>()
            {
                () =>
                {
                    stmAction();
                    return true;
                }
            });
        }

        public static void Atomic(Action stmAction, params Action[] orElses)
        {
            var atomics = new List<Func<bool>>(orElses.Length + 1)
            {
                () =>
                {
                    stmAction();
                    return true;
                }
            };

            //Convert orElseblocks from Action to Func<bool>
            atomics.AddRange(orElses.Select<Action,Func<bool>>(orElseBlcok =>
                () =>
                {
                    orElseBlcok();
                    return true;
                }
            ));

            AtomicInternal(atomics);
        }

        private static T AtomicInternal<T>(IList<Func<T>> stmActions)
        {
            Debug.Assert(stmActions.Count > 0);
            var result = default(T);
            var index = 0;
            var overAllReadSet = new ReadSet();
            var ovarAllReadstamp = -1;
            var nrAttempts = 0;

            while (true)
            {
                var stmAction = stmActions[index];

                //Start new or nested transaction
                var prevTransaction = Transaction.LocalTransaction;
                var me = prevTransaction.Status == TransactionStatus.Active ?
                    Transaction.StartNestedTransaction(prevTransaction) :
                    Transaction.StartTransaction();

                if (index == 0)
                {
                    ovarAllReadstamp = me.ReadStamp;
                }

                try
                {
                    //Execute transaction body
                    result = stmAction();

                    if (me.Commit())
                    {
                        return result;
                    }

                }
                catch (STMAbortException)
                {
                    //Skips straight to abort a reexecute
                }
                catch (STMRetryException)
                {
                    index = HandleRetry(stmActions, me, index, overAllReadSet, ovarAllReadstamp);
                }
                catch (Exception) //Catch non stm related exceptions which occurs in transactions
                {
                    //Throw exception of transaction can commit
                    //Else abort and rerun transaction
                    if (me.Commit())
                    {
                        throw;
                    }
                }

                nrAttempts++;
                me.Abort();

                //If the transaction is nested restore the parent as current transaction before retrying
                if (me.IsNested)
                {
                    Transaction.LocalTransaction = me.Parent;
                }

                if (nrAttempts == MAX_ATTEMPTS)
                {
                    throw new STMMaxAttemptException("Fatal error: max attempts reached");
                }
            }
        }

        #endregion Atomic

        #region Retry

        public static void Retry()
        {
            var transaction = Transaction.LocalTransaction;
            if (transaction.Status == TransactionStatus.Committed)
                return;

            throw new STMRetryException();
        }

        private static int HandleRetry<T>(IList<Func<T>> stmActions, Transaction me, int index, ReadSet overAllReadSet, int originalReadstamp)
        {
            if (stmActions.Count == 1) //Optimized for when there are no orelse blocks
            {
                WaitOnReadset(me, me.ReadSet);
            }
            else if (stmActions.Count == index + 1) //Final orelse block
            {
                overAllReadSet.Merge(me.ReadSet);
                WaitOnReadset(me, overAllReadSet,originalReadstamp);
                index = 0;
            }
            else //Non final atomic or orelse blocks
            {
#if DEBUG
                Console.WriteLine("Transaction: " + me.ID + " ORELSE jump");
#endif
                overAllReadSet.Merge(me.ReadSet);
                index++;
            }

            return index;
        }

        private static void WaitOnReadset(Transaction me, ReadSet readSet)
        {
            WaitOnReadset(me,readSet,me.ReadStamp);
        }

        private static void WaitOnReadset(Transaction me, ReadSet readSet, int readstamp)
        {

#if DEBUG
            Console.WriteLine("ENTERED WAIT ON RETRY: " + me.ID);
#endif

            if (readSet.Count == 0)
            {
                throw new STMInvalidRetryException();
            }

            var waiton = new WaitHandle[readSet.Count()];

            var i = 0;
            foreach (var item in readSet)
            {
                waiton[i] = item.Key.RegisterWaitHandle();
                i++;
            }

            if (!readSet.Validate(me,readstamp))
            {
                return;
            }

#if DEBUG
            Console.WriteLine("WAIT ON RETRY: " + me.ID);
#endif
            WaitHandle.WaitAny(waiton);
#if DEBUG
            Console.WriteLine("WAIT ON RETRY: " + me.ID);
#endif
        }

        #endregion Retry

    }
}


text:
public class CyclePwm3 {
  static {
    try {
      System.loadLibrary("mraajava");
    } catch (UnsatisfiedLinkError e) {
      System.err.println(
          "Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" +
          e);
      System.exit(1);
    }
  }
  public static void main(String argv[]) throws InterruptedException {
    mraa.mraa.init();
    mraa.Pwm pwm = new mraa.Pwm(3);
    pwm.period_us(200);
    pwm.enable(true);

    float value = 0;
    while (true) {
      value += 0.01;
      pwm.write(value);
      Thread.sleep(50);
      if (value >= 1) {
        value = 0;
      }
    }
  }
}


text:
/*
import browserenv from './browser_env.js';
import {interpretSync} from '../iron.js';

document.addEventListener('DOMContentLoaded', () => {
  let main = document.getElementById('ironscript-main').text;
  interpretSync(main, 'ironscript-main', browserenv());
}, false);
*/

import Package from './package.js';
export function runPackage (pkgstr) {
	console.log("Powered by Ironscript 1.2.2");
	console.log("visit https://ironscript.gitgub.io for more info");
  let p = new Package(pkgstr);
}


text:
import java.util.Scanner;

public class Main{

    public static void main(String[] args){
        Scanner scanner=new Scanner(System.in);
        while(scanner.hasNext()){
             int []minNum=new int[1];
             int []maxNum=new int[1];
             getNearPrim(scanner.nextInt(),minNum,maxNum);
             System.out.println(minNum[0]);
             System.out.println(maxNum[0]);
        }
    }

    public static void getNearPrim(int num,int[] minNum,int []maxNum){
        if(num<=2||num/2==0){
            throw new IllegalArgumentException("num mast more than 2 and is odd");
        }
        int mid=num>>1;
        int minPrime=mid;
        int maxPrime=mid;
        while(maxPrime<num){
            if(isPrime(minPrime)&&isPrime(maxPrime)){
                minNum[0]=minPrime;
                maxNum[0]=maxPrime;
                break;
            }
            maxPrime++;
            minPrime--;
        }
    }

    private static boolean isPrime(int num){
        for(int i=2;i<num;i++){
            if(num%i==0){
                return false;
            }
        }
        return true;
    }
}


text:
package uk.ac.ebi.pride.utilities.data.controller.impl.ControllerImpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.jmzml.model.mzml.*;
import uk.ac.ebi.jmzml.xml.io.MzMLUnmarshallerException;
import uk.ac.ebi.pride.utilities.data.controller.DataAccessController;
import uk.ac.ebi.pride.utilities.data.controller.DataAccessException;
import uk.ac.ebi.pride.utilities.data.controller.DataAccessMode;
import uk.ac.ebi.pride.utilities.data.controller.DataAccessUtilities;
import uk.ac.ebi.pride.utilities.data.controller.cache.CacheEntry;
import uk.ac.ebi.pride.utilities.data.controller.cache.strategy.MzMlCachingStrategy;
import uk.ac.ebi.pride.utilities.data.controller.impl.Transformer.MzMLTransformer;
import uk.ac.ebi.pride.utilities.data.core.*;
import uk.ac.ebi.pride.utilities.data.core.Chromatogram;
import uk.ac.ebi.pride.utilities.data.core.DataProcessing;
import uk.ac.ebi.pride.utilities.data.core.InstrumentConfiguration;
import uk.ac.ebi.pride.utilities.data.core.ParamGroup;
import uk.ac.ebi.pride.utilities.data.core.ReferenceableParamGroup;
import uk.ac.ebi.pride.utilities.data.core.Sample;
import uk.ac.ebi.pride.utilities.data.core.Software;
import uk.ac.ebi.pride.utilities.data.core.SourceFile;
import uk.ac.ebi.pride.utilities.data.core.Spectrum;
import uk.ac.ebi.pride.utilities.data.io.file.MzMLUnmarshallerAdaptor;
import uk.ac.ebi.pride.utilities.data.utils.MD5Utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * MzMlControllerImpl provides methods to access mzML files.
 * <p/>
 * @author Rui Wang
 * @author  Yasset Perez-Riverol
 */
public class MzMLControllerImpl extends CachedDataAccessController {

    private static final Logger logger = LoggerFactory.getLogger(MzMLControllerImpl.class);
    /**
     * Pattern for validating mzML format
     */
    private static final Pattern mzMLHeaderPattern = Pattern.compile("^[^<]*(<\\?xml [^>]*>\\s*(<!--[^>]*-->\\s*)*)?<(mzML)|(indexedmzML) xmlns=.*", Pattern.MULTILINE);

    /**
     * Reader for getting information from mzML file
     */
    private MzMLUnmarshallerAdaptor unmarshaller = null;

    /**
     * Construct a data access controller using a given mzML file
     *
     * @param file mzML file
     */
    public MzMLControllerImpl(File file) {
        super(file, DataAccessMode.CACHE_AND_SOURCE);
        initialize();
    }

    private void initialize() {
        File file = (File) this.getSource();
        // create unmarshaller
        unmarshaller = new MzMLUnmarshallerAdaptor(file);

        // set data source name
        this.setName(file.getName());
        // set the type
        this.setType(DataAccessController.Type.XML_FILE);
        // set the content categories
        this.setContentCategories(DataAccessController.ContentCategory.SPECTRUM,
                DataAccessController.ContentCategory.CHROMATOGRAM,
                DataAccessController.ContentCategory.SAMPLE,
                DataAccessController.ContentCategory.INSTRUMENT,
                DataAccessController.ContentCategory.SOFTWARE,
                DataAccessController.ContentCategory.DATA_PROCESSING);
        // create cache builder
        setCachingStrategy(new MzMlCachingStrategy());
        // populate cache
        populateCache();
    }

    /**
     * Get the backend data reader
     *
     * @return MzMLUnmarshallerAdaptor mzML reader
     */
    public MzMLUnmarshallerAdaptor getUnmarshaller() {
        return unmarshaller;
    }

    /**
     * Get the unique id for this data access controller
     * It generates a MD5 hash using the absolute path of the file
     * This will guarantee the same id if the file path is the same
     *
     * @return String  unique id
     */
    @Override
    public String getUid() {
        String uid = super.getUid();
        if (uid == null) {
            // create a new UUID
            File file = (File) this.getSource();
            try {
                uid = MD5Utils.generateHash(file.getAbsolutePath());
            } catch (NoSuchAlgorithmException e) {
                String msg = "Failed to generate unique id for mzML file";
                logger.error(msg, e);
            }
        }
        return uid;
    }

    /**
     * Get a list of cvlookups, these are not cached
     *
     * @return List<CvLookup>  a list of cvlookups
     */
    public List<CVLookup> getCvLookups() {
        try {
            CVList rawCvList = unmarshaller.getCVList();
            return MzMLTransformer.transformCVList(rawCvList);
        } catch (Exception e) {
            String msg = "Exception while trying to read a list of cv lookups";
            logger.error(msg, e);
            throw new DataAccessException(msg, e);
        }
    }

    /**
     * Get Referenceable paramgroup, this concept is only available in mzML
     * It is a paramgroup with id and this is not cached
     *
     * @return ReferenceableParamGroup param group
     */
    public ReferenceableParamGroup getReferenceableParamGroup() {

        try {
            ReferenceableParamGroupList rawRefParamGroup = unmarshaller.getReferenceableParamGroupList();
            return MzMLTransformer.transformReferenceableParamGroupList(rawRefParamGroup);
        } catch (Exception e) {
            String msg = "Exception while trying to read referenceable param group";
            logger.error(msg, e);
            throw new DataAccessException(msg, e);
        }
    }

    /**
     * Get a list of samples by checking the cache first
     *
     * @return List<Sample>    a list of samples
     */
    @Override
    public List<Sample> getSamples() {
        ExperimentMetaData metaData = super.getExperimentMetaData();

        if (metaData == null) {
            try {
                SampleList rawSample = unmarshaller.getSampleList();
                return MzMLTransformer.transformSampleList(rawSample);
            } catch (Exception e) {
                String msg = "Exception while trying to read samples";
                logger.error(msg, e);
                throw new DataAccessException(msg, e);
            }
        } else {
            return metaData.getSamples();
        }
    }

    /**
     * Get a list of person contacts
     *
     * @return List<Person>    list of persons
     */
    public List<Person> getPersonContacts() {
        try {
            FileDescription rawFileDesc = unmarshaller.getFileDescription();
            // List of Persons
            return MzMLTransformer.transformFileDescriptionToPerson(rawFileDesc);
        } catch (Exception e) {
            String msg = "Error while getting a list of person contacts";
            logger.error(msg, e);
            throw new DataAccessException(msg, e);
        }
    }

    /**
     * Get a list of Organization contacts
     *
     * @return List<Organization>    list of persons
     */
    public List<Organization> getOrganizationContacts() {
        try {
            FileDescription rawFileDesc = unmarshaller.getFileDescription();
            // List of Organization
            return MzMLTransformer.transformFileDescriptionOrganization(rawFileDesc);
        } catch (Exception e) {
            String msg = "Error while getting a list of organizational contacts";
            logger.error(msg, e);
            throw new DataAccessException(msg, e);
        }
    }

    /**
     * Get a List of SourceFiles
     *
     * @return List<SourceFile> List of SourceFile
     */
    public List<SourceFile> getSourceFiles() {
        try {
            FileDescription rawFileDesc = unmarshaller.getFileDescription();
            // List of Persons
            return MzMLTransformer.transformFileDescriptionToFileSource(rawFileDesc);
        } catch (Exception e) {
            String msg = "Error while getting a list of source files";
            logger.error(msg, e);
            throw new DataAccessException(msg, e);
        }
    }

    /**
     * This summarizes the different types of spectra that can be expected
     * in the file. This is expected to aid processing software in skipping
     * files that do not contain appropriate spectrum types for it. It should
     * also describe the nativeID format used in the file by referring to an
     * appropriate CV term.
     *
     * @return ParamGroup A list of CvTerms Related with the File Content
     */
    public ParamGroup getFileContent() {
        try {
            FileDescription rawFileDesc = unmarshaller.getFileDescription();
            return MzMLTransformer.transformFileDescriptionToFileContent(rawFileDesc);
        } catch (Exception e) {
            String msg = "Error while getting a list of file content";
            logger.error(msg, e);
            throw new DataAccessException(msg, e);
        }
    }

    /**
     * Get a List of Softwares
     *
     * @return List<Software> List of Softwares
     */
    public List<Software> getSoftwares() {
        ExperimentMetaData metaData = super.getExperimentMetaData();

        if (metaData == null) {
            try {
                SoftwareList rawSoftware = unmarshaller.getSoftwares();
                return MzMLTransformer.transformSoftwareList(rawSoftware);
            } catch (Exception e) {
                String msg = "Error while getting a list of software";
                logger.error(msg, e);
                throw new DataAccessException(msg, e);
            }
        } else {
            return metaData.getSoftwares();
        }
    }

    /**
     * Get a list of scan settings by checking the cache first
     *
     * @return List<ScanSetting>   a list of scan settings
     */
    public List<ScanSetting> getScanSettings() {
        MzGraphMetaData metaData = super.getMzGraphMetaData();

        if (metaData == null) {
            try {
                ScanSettingsList rawScanSettingList = unmarshaller.getScanSettingsList();
                return MzMLTransformer.transformScanSettingList(rawScanSettingList);
            } catch (Exception e) {
                String msg = "Error while getting a list of scan settings";
                logger.error(msg, e);
                throw new DataAccessException(msg, e);
            }
        } else {
            return metaData.getScanSettings();
        }
    }

    /**
     * Get a list of instrument configurations by checking the cache first
     *
     * @return List<Instrumentconfiguration>   a list of instrument configurations
     */
    public List<InstrumentConfiguration> getInstrumentConfigurations() {
        MzGraphMetaData metaData = super.getMzGraphMetaData();

        if (metaData == null) {
            try {
                InstrumentConfigurationList rawInstrumentList = unmarshaller.getInstrumentConfigurationList();
                return MzMLTransformer.transformInstrumentConfigurationList(rawInstrumentList);
            } catch (Exception e) {
                String msg = "Error while getting a list of instrument configurations";
                logger.error(msg, e);
                throw new DataAccessException(msg, e);
            }
        } else {
            return metaData.getInstrumentConfigurations();
        }
    }

    /**
     * Get a list of data processings by checking the cache first
     *
     * @return List<DataProcessing>    a list of data processings
     */
    public List<DataProcessing> getDataProcessings() {
        MzGraphMetaData metaData = super.getMzGraphMetaData();

        if (metaData == null) {
            try {
                uk.ac.ebi.jmzml.model.mzml.DataProcessingList rawDataProcList = unmarshaller.getDataProcessingList();
                return MzMLTransformer.transformDataProcessingList(rawDataProcList);
            } catch (Exception e) {
                String msg = "Error while getting a list of data processings";
                logger.error(msg, e);
                throw new DataAccessException(msg, e);
            }
        } else {
            return metaData.getDataProcessings();
        }

    }

    /**
     * In case of mzMl the additional parameters are related with the getFileContent
     * This are a set of CVTerms related with the Content in the MzML File. Also we add the
     * the Date of the Run as a CvParam, it is very important to know when this information was
     * generated.
     *
     * @return ParamGroup  param group
     */
    @Override
    public ParamGroup getAdditional() {
        ParamGroup paramGroup = null;
        ParamGroup fileContent = getFileContent();
        if (fileContent != null) {
            paramGroup = fileContent;
        }
        Date dateCreation = unmarshaller.getCreationDate();
        if (dateCreation != null && paramGroup != null) {
            paramGroup.addCvParam(MzMLTransformer.transformDateToCvParam(dateCreation));

        }
        return paramGroup;
    }

    /**
     * Get spectrum using a spectrum id, gives the option to choose whether to use cache.
     * This implementation provides a way of by passing the cache.
     *
     * @param id       spectrum id
     * @param useCache true means to use cache
     * @return Spectrum spectrum object
     */
    @Override
    Spectrum getSpectrumById(Comparable id, boolean useCache) {
        Spectrum spectrum = super.getSpectrumById(id, useCache);
        if (spectrum == null) {
            try {
//                System.out.println(id);
                uk.ac.ebi.jmzml.model.mzml.Spectrum
                        rawSpec = unmarshaller.getSpectrumById(id.toString());

                spectrum = MzMLTransformer.transformSpectrum(rawSpec);
                if (useCache) {
                    getCache().store(CacheEntry.SPECTRUM, id, spectrum);
                    getCache().store(CacheEntry.SPECTRUM_LEVEL_PRECURSOR_CHARGE,id, DataAccessUtilities.getPrecursorCharge(spectrum.getPrecursors()));
                }
            } catch (MzMLUnmarshallerException ex) {
                logger.error("Get spectrum by id", ex);
                throw new DataAccessException("Exception while trying to read Spectrum using Spectrum ID", ex);
            }
        }
        return spectrum;
    }

    /**
     * Get chromatogram using a chromatogram id, gives the option to choose whether to use cache.
     * This implementation provides a way of by passing the cache.
     *
     * @param id       chromatogram id
     * @param useCache true means to use cache
     * @return Chromatogram chromatogram object
     */
    @Override
    public Chromatogram getChromatogramById(Comparable id, boolean useCache) {
        Chromatogram chroma = super.getChromatogramById(id, useCache);
        if (chroma == null) {
            try {
                uk.ac.ebi.jmzml.model.mzml.Chromatogram
                        rawChroma = unmarshaller.getChromatogramById(id.toString());
                chroma = MzMLTransformer.transformChromatogram(rawChroma);
                if (useCache) {
                    getCache().store(CacheEntry.CHROMATOGRAM, id, chroma);
                }
            } catch (MzMLUnmarshallerException ex) {
                logger.error("Get chromatogram by id", ex);
                throw new DataAccessException("Exception while trying to read Chromatogram using chromatogram ID", ex);
            }
        }
        return chroma;
    }

    /**
     * Close data access controller by resetting the data reader first
     */
    @Override
    public void close() {
        unmarshaller = null;
        super.close();
    }

    @Override
    public ExperimentMetaData getExperimentMetaData() {

        ExperimentMetaData metaData = super.getExperimentMetaData();

        if (metaData == null) {
            // id , accession and version
            String id = unmarshaller.getMzMLId();
            String accession = unmarshaller.getMzMLAccession();
            String version = unmarshaller.getMzMLVersion();

            // SourceFile List
            List<SourceFile> sourceFileList = getSourceFiles();

            // List of Persons
            List<Person> personList = getPersonContacts();

            // List of Organizations
            List<Organization> organizationList = getOrganizationContacts();

            // Sample list
            List<Sample> samples = getSamples();

            // Software list
            List<Software> softwares = getSoftwares();

            // ScanSettings list
            ParamGroup adittional = getAdditional();

            metaData = new ExperimentMetaData(adittional, id, accession, version, null, samples, softwares, personList, sourceFileList, null, organizationList, null, null, null, null);
        }
        return metaData;
    }

    /**
     * Get the Spectrum Metadata, the ScanSettings, The DataProcessing, and Instrument
     * Configurations.
     *
     * @return MzGraphMetaData is the Metadata related with Spectrum Information
     */
    @Override
    public MzGraphMetaData getMzGraphMetaData() {
        MzGraphMetaData metaData = super.getMzGraphMetaData();
        if (metaData == null) {
            List<ScanSetting> scanSettings = getScanSettings();
            List<DataProcessing> dataProcessings = getDataProcessings();
            List<InstrumentConfiguration> instrumentConfigurations = getInstrumentConfigurations();
            metaData = new MzGraphMetaData(null, null, scanSettings, instrumentConfigurations, dataProcessings);
        }
        return metaData;
    }

    /**
     * The mzML do not contains Identification Metadata, just Spectrum Information
     * @return The MzML do not support Identification Metadata
     */
    @Override
    public IdentificationMetaData getIdentificationMetaData() {
        throw new UnsupportedOperationException("This method is not supported");
    }

    /**
     * This method provide the way to know if the controller contain
     * Identification Data and IdentificationMetadata.
     * @return True if the DataAccessController contains Proteins
     */
    @Override
    public boolean hasProtein() {
        return false;
    }

    /**
     * Check a file is mzML file
     *
     * @param file input file
     * @return boolean true means mzML
     */
    public static boolean isValidFormat(File file) {
        boolean valid = false;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            // read the first ten lines
            StringBuilder content = new StringBuilder();
            for (int i = 0; i < 10; i++) {
                content.append(reader.readLine());
            }

            Matcher matcher = mzMLHeaderPattern.matcher(content);

            valid = matcher.find();
        } catch (Exception e) {
            logger.error("Failed to read file", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // do nothing here
                }
            }
        }

        return valid;
    }

}


text:
<?xml version="1.0" encoding="utf-8" ?>
<Domains>
    <Domain>http://localhost</Domain>
    <Domain>http://ima9ines.com</Domain>
    <Domain>http://epi.ima9ines.com</Domain>
    <Domain>http://banca.fish</Domain>
    <Domain>http://bebibo.vn</Domain>
    <Domain>http://chamechiase.com</Domain>
    <Domain>http://hanarose.com</Domain>
    <Domain>http://www.fbjewel.com.hk</Domain>
</Domains>


text:
// **********************************************************************
//
// <copyright>
//
//  BBN Technologies
//  10 Moulton Street
//  Cambridge, MA 02138
//  (617) 873-8000
//
//  Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source:
// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/PropUtils.java,v
// $
// $RCSfile: PropUtils.java,v $
// $Revision: 1.16 $
// $Date: 2008/09/26 12:07:56 $
// $Author: dietrick $
//
// **********************************************************************

package com.bbn.openmap.util;

/* Java Core */
import java.awt.Color;
import java.awt.Paint;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JFileChooser;

import com.bbn.openmap.Environment;
import com.bbn.openmap.I18n;
import com.bbn.openmap.Layer;
import com.bbn.openmap.PropertyConsumer;

public class PropUtils {

   public static Logger logger = Logger.getLogger("com.bbn.openmap.util.PropUtils");

   /**
    * Parse a list of marker names from a space separated list within a String.
    *

    *
    * @param markerList a string containing a space delimited list of marker
    *        names.
    * @return Vector of marker names.
    */
   public static Vector<String> parseSpacedMarkers(String markerList) {
      return parseMarkers(markerList, " ");
   }

   /**
    * Parse a list of marker names from a space separated list within a String.
    *

    *
    * @param markerList a string containing a list of things to be parsed.
    * @param delim the list of tokens to look for which separate the list
    *        elements.
    * @return Vector of marker names.
    */
   public static Vector<String> parseMarkers(String markerList, String delim) {
      Vector<String> vector = null;

      if (markerList == null) {
         logger.fine("marker list null!");
         return new Vector<String>(0);
      }

      if (logger.isLoggable(Level.FINE)) {
         logger.fine("parsing marker list |" + markerList + "|");
      }

      // First, get rid of the quotation marks;
      markerList = markerList.replace('\"', '\0');
      // Next, tokenize the space delimited string
      StringTokenizer tokens = new StringTokenizer(markerList, delim);
      vector = new Vector<String>(tokens.countTokens());
      while (tokens.hasMoreTokens()) {
         String name = tokens.nextToken().trim();
         vector.addElement(name);
      }
      return vector;
   }

   /**
    * A string used in marker names for property editors, when a custom editor
    * used by an Inspector can set several top-level properties.
    */
   public final static String DUMMY_MARKER_NAME = "DUMMY_MARKER_NAME";
   /** Borrowed from Properties.java */
   public static final String keyValueSeparators = "=: \t\r\n\f";
   /** Borrowed from Properties.java */
   public static final String strictKeyValueSeparators = "=:";
   /** Borrowed from Properties.java */
   public static final String whiteSpaceChars = " \t\r\n\f";
   /** As defined in the OGC Web Mapping Test bed. */
   public static final String propertySeparators = "&";

   /**
    * Take a property list, defined in a single string, and return a Properties
    * object. The properties, as key-value pairs, are separated by another type
    * of symbol. In this method, the key-values are assumed to be separated from
    * other key-value pairs by PropUtils.propertySeparators String characters,
    * and each key is separated from its value by any character in the
    * PropUtils.keyValueSeparators list.
    *
    * @param list the properties list string.
    * @return Properties object containing keys and values.
    * @throws PropertyStringFormatException if a key doesn't have a value.
    */
   public static Properties parsePropertyList(String list)
         throws PropertyStringFormatException {
      return parsePropertyList(list, propertySeparators, keyValueSeparators);
   }

   /**
    * Take a property list, defined in a single string, and return a Properties
    * object. The properties, as key-value pairs, are separated by another type
    * of symbol.
    *
    * @param list the properties list string.
    * @return Properties object containing keys and values.
    * @param propertySeparators the key-values are assumed to be separated from
    *        other key-value pairs by any character in this String.
    * @param keyValueSeparators each key is separated from its value by any
    *        character in this String.
    * @throws PropertyStringFormatException if a key doesn't have a value.
    */
   public static Properties parsePropertyList(String list, String propertySeparators, String keyValueSeparators)
         throws PropertyStringFormatException {

      Properties props = new Properties();

      Vector<String> keyValuePairs = parseMarkers(list, propertySeparators);
      for (int i = 0; i < keyValuePairs.size(); i++) {
         // Next, tokenize the space delimited string
         StringTokenizer tokens = new StringTokenizer(keyValuePairs.elementAt(i), keyValueSeparators);

         try {
            String key = tokens.nextToken().trim();
            String value = tokens.nextToken().trim();
            props.put(key, value);
         } catch (NoSuchElementException nsee) {
            throw new PropertyStringFormatException(list);
         }
      }
      return props;
   }

   /**
    * Copy the contents from one properties object to another.
    *
    * @param from the source Properties object.
    * @param to the destination Properties object.
    */
   public static void copyProperties(Properties from, Properties to) {
      Enumeration<Object> keys = from.keys();

      while (keys.hasMoreElements()) {
         String key = (String) keys.nextElement();
         to.put(key, from.getProperty(key));
      }
   }

   /**
    * Load the named file from the named directory into the given
    * Properties instance. If the file is not found a warning is
    * issued. If an IOException occurs, a fatal error is printed.
    *
    * @param props the instance to receive the loaded properties
    * @param dir the directory where the properties file resides
    * @param file the name of the file
    * @return true if the properties file exists and was loaded.
    */
   public static boolean loadProperties(Properties props, String dir, String file) {
      File propsFile = new File(dir, file);

      try {
         InputStream propsStream = new FileInputStream(propsFile);
         props.load(propsStream);
         if (logger.isLoggable(Level.FINE)) {
            logger.fine("Found " + propsFile);
         }
         return true;

      } catch (java.io.FileNotFoundException e) {
         if (logger.isLoggable(Level.FINE)) {
            logger.fine("File not found -  \"" + propsFile + "\"");
         }
      } catch (java.io.IOException e) {
         logger.warning("Caught IO Exception reading \"" + propsFile + "\"");
         e.printStackTrace();
      } catch (java.security.AccessControlException ace) {
      }
      return false;
   }

   /**
    * Loads properties from a java resource. This will load the named resource
    * identifier into the given properties instance.
    *
    * @param properties the Properties instance to receive the properties.
    * @param propsIn an InputStream to read properties from
    * @return true if the properties file exists and was loaded.
    */
   public static boolean loadProperties(Properties properties, InputStream propsIn) {
      try {
         properties.load(propsIn);
         return true;
      } catch (java.io.IOException e) {
         if (logger.isLoggable(Level.FINE)) {
            logger.warning("Caught IOException loading properties from InputStream.");
         }
         return false;
      }
   }

   /**
    * A function that brings up a file chooser window in order to have the user
    * look for a valid Java properties file.
    *
    * @return properties object with selected file contents.
    */
   public static Properties promptUserForProperties() {
      JFileChooser fileChooser = new JFileChooser();
      int retvalue = fileChooser.showOpenDialog(null);
      Properties props = new Properties();
      if (retvalue != JFileChooser.APPROVE_OPTION) {
         return props;
      }
      try {
         FileInputStream inputStream = new FileInputStream(fileChooser.getSelectedFile());
         props.load(inputStream);
         return props;
      } catch (Exception ioe) {
         System.err.println("PropUtils.promptUserForProperties: Exception reading properties file.");
         System.err.println(ioe.getMessage());
         ioe.printStackTrace();
         return props;
      }
   }

   /**
    * It seems like every PropertyConsumer wrestles with having a prefix or not.
    * This method lets you just get the prefix with a period on the end (for
    * scoping purposes), or just returns an empty String. Either way, you get a
    * String you can slap on the beginning of your defined property names to get
    * a valid property based on what the prefix is.
    */
   public static String getScopedPropertyPrefix(PropertyConsumer pc) {
      return getScopedPropertyPrefix(pc.getPropertyPrefix());
   }

   /**
    * Given the string, check if it's null. If it is, return an empty string. If
    * it isn't, check to see if it ends with a period, and do nothing if it
    * does. If it doesn't end in a period, add one, and then return that. The
    * returned string should be good for prepending to other properties.
    */
   public static String getScopedPropertyPrefix(String pre) {
      if (pre == null || pre.length() == 0) {
         return "";
      } else if (pre.endsWith(".")) {
         return pre;
      } else {
         return pre + ".";
      }
   }

   /**
    * Should be called by a PropertyConsumer in the
    * getPropertiesInfo(Properties) method to create a property marker name for
    * a custom PropertyEditor that will modify several top-level properties,
    * i.e. the com.bbn.openmap.omGraphics.DrawingAttributesPropertyEditor.
    *
    * @param realComponentPropertyPrefix the top-level prefix that the
    *        PropertyConsumer being set with the properties has. Can be null.
    * @param anyDesiredScoper an additional scoping mechanism if there are more
    *        than one custom editors being used for a given getPropertyInfo
    *        call.
    * @return The string that is used for a marker for a custom editor.
    */
   public static String getDummyMarkerForPropertyInfo(String realComponentPropertyPrefix, String anyDesiredScoper) {
      return DUMMY_MARKER_NAME + (anyDesiredScoper != null ? anyDesiredScoper : "") + "."
            + (realComponentPropertyPrefix != null ? realComponentPropertyPrefix : "");
   }

   /**
    * Should be used inside a
    * PropertyConsumerPropertyEditor.setProperties(String, Properties) method to
    * set the real property prefix. The PropertyConsumer that the Inspector is
    * looking at should use the getDummyMarker() call to create the marker for
    * the getPropertyInfor(Properties) call.
    *
    * @param possibleDummyMarker
    * @return the encoded 'real' property prefix for the PropertyConsumer
    *         embedded in the dummy marker, or the possibleDummyMarker if it's
    *         not a dummy marker.
    */
   public static String decodeDummyMarkerFromPropertyInfo(String possibleDummyMarker) {
      if (possibleDummyMarker != null && possibleDummyMarker.startsWith(DUMMY_MARKER_NAME)) {
         int lastDot = possibleDummyMarker.lastIndexOf(".");
         if (lastDot != -1) {
            possibleDummyMarker = possibleDummyMarker.substring(lastDot + 1);
         }
      }
      return possibleDummyMarker;
   }

   /**
    * It kills Properties to have null values set. You can wrap a property value
    * in this in PropertyConsumer.getProperties() to not worry about it. Returns
    * "" if prop == null, else returns what was passed in.
    */
   public static String unnull(String prop) {
      if (prop == null) {
         return "";
      }
      return prop;
   }

   /**
    * Takes a string of `;' separated paths and returns an array of parsed
    * strings. NOTE: this method currently doesn't support appropriate quoting
    * of the `;' character, although it probably should...
    *
    * @param p properties
    * @param propName the name of the property
    * @return Array of strings representing paths.
    */
   public static String[] initPathsFromProperties(Properties p, String propName) {
      return initPathsFromProperties(p, propName, null);
   }

   /**
    * Takes a string of `;' separated paths and returns an array of parsed
    * strings. NOTE: this method currently doesn't support appropriate quoting
    * of the `;' character, although it probably should...
    *
    * @param p properties
    * @param propName the name of the property
    * @param defaultPaths the value of the paths to set if the property doesn't
    *        exist, or if is doesn't contain anything.
    * @return Array of strings representing paths.
    */
   public static String[] initPathsFromProperties(Properties p, String propName, String[] defaultPaths) {
      String[] ret = stringArrayFromProperties(p, propName, ";");

      if (ret == null) {
         ret = defaultPaths;
      }

      return ret;
   }

   /**
    * Return the first letter of the property specified by propName. If that
    * value is null or has length of zero, the default char is returned.
    *
    * @param p
    * @param propName
    * @param defaultValue
    * @return first char from property, or default.
    */
   public static char charFromProperties(Properties p, String propName, char defaultValue) {
      char ret = defaultValue;
      String charString = p.getProperty(propName);
      if (charString != null && charString.length() > 0) {
         return charString.charAt(0);
      }
      return ret;
   }

   /**
    * Gets an integer out of a properties object. Returns the default value if
    * something goes wrong.
    *
    * @param p properties
    * @param propName name of the property associated with the wanted value.
    * @param defaultValue what to return if the property name doesn't exist, or
    *        if the value isn't a numerical value.
    * @return integer value associated with the property.
    */
   public static int intFromProperties(Properties p, String propName, int defaultValue) {
      int ret = defaultValue;
      String intString = p.getProperty(propName);

      if (intString != null) {
         try {
            ret = Integer.parseInt(intString.trim());
         } catch (NumberFormatException e) {
            ret = defaultValue;
         }
      }
      return ret;
   }

   /**
    * Gets an float out of a properties object. Returns the default value if
    * something goes wrong.
    *
    * @param p properties
    * @param propName name of the property associated with the wanted value.
    * @param defaultValue what to return if the property name doesn't exist, or
    *        if the value isn't a numerical value.
    * @return float value associated with the property.
    */
   public static float floatFromProperties(Properties p, String propName, float defaultValue) {
      float ret = defaultValue;
      String floatString = p.getProperty(propName);

      if (floatString != null) {
         try {
            ret = Float.parseFloat(floatString.trim());
         } catch (NumberFormatException e) {
            ret = defaultValue;
         }
      }
      return ret;
   }

   /**
    * Gets an boolean out of a properties object. Returns the default value if
    * something goes wrong.
    *
    * @param p properties
    * @param propName name of the property associated with the wanted value.
    * @param defaultValue what to return if the property name doesn't exist, or
    *        if the value isn't a numerical value.
    * @return boolean value associated with the property.
    */
   public static boolean booleanFromProperties(Properties p, String propName, boolean defaultValue) {
      boolean ret = defaultValue;
      String booleanString = p.getProperty(propName);
      if (booleanString != null) {
         ret = booleanString.trim().equalsIgnoreCase("true");
      }

      return ret;
   }

   /**
    * Creates an object out of a property name. If anything fails, return null.
    *
    * @param p properties
    * @param propName name of class to instantiate.
    * @return null on failure, otherwise, a default constructed instance of the
    *         class named in the property.
    */
   public static Object objectFromProperties(Properties p, String propName) {

      Object ret = null;
      String objectName = p.getProperty(propName);
      if (objectName != null) {
         ret = ComponentFactory.create(objectName);
      }
      return ret;
   }

   /**
    * Takes a string of representing token separated properties and returns an
    * array of parsed strings. NOTE: this method currently doesn't support
    * appropriate quoting of the token, although it probably should...
    *
    * @param p properties
    * @param propName the name of the property
    * @param tok the characters separating the strings.
    * @return Array of strings between the tokens.
    */
   public static String[] stringArrayFromProperties(Properties p, String propName, String tok) {

      String[] ret = null;
      String raw = p.getProperty(propName);

      if (raw != null && raw.length() > 0) {

         try {
            StringTokenizer token = new StringTokenizer(raw, tok);
            int numPaths = token.countTokens();

            ret = new String[numPaths];
            for (int i = 0; i < numPaths; i++) {
               ret[i] = token.nextToken();
            }
            return ret;
         } catch (java.util.NoSuchElementException e) {
            e.printStackTrace();
         }
      }
      return ret;
   }

   /**
    * Gets a double out of a properties object. Returns the default value if
    * something goes wrong.
    *
    * @param p properties
    * @param propName name of the property associated with the wanted value.
    * @param defaultValue what to return if the property name doesn't exist, or
    *        if the value isn't a numerical value.
    * @return double value associated with the property.
    */
   public static double doubleFromProperties(Properties p, String propName, double defaultValue) {
      double ret = defaultValue;
      String doubleString = p.getProperty(propName);

      if (doubleString != null) {
         try {
            ret = Double.parseDouble(doubleString.trim());
         } catch (NumberFormatException e) {
            ret = defaultValue;
         }
      }
      return ret;
   }

   /**
    * Gets a long out of a properties object. Returns the default value if
    * something goes wrong.
    *
    * @param p properties
    * @param propName name of the property associated with the wanted value.
    * @param defaultValue what to return if the property name doesn't exist, or
    *        if the value isn't a numerical value.
    * @return long value associated with the property.
    */
   public static long longFromProperties(Properties p, String propName, long defaultValue) {
      long ret = defaultValue;
      String longString = p.getProperty(propName);

      if (longString != null) {
         try {
            ret = Long.parseLong(longString.trim());
         } catch (NumberFormatException e) {
            ret = defaultValue;
         }
      }
      return ret;
   }

   /**
    * Take a string from a properties file, representing the 24bit RGB or 32bit
    * ARGB hex values for a color, and convert it to a java.awt.Color.
    *
    * @param p properties
    * @param propName the name of the property
    * @param dfault color to use if the property value doesn't work
    * @return java.awt.Color
    * @exception NumberFormatException if the specified string cannot be
    *            interpreted as a hexidecimal integer
    * @see ColorFactory#parseColorFromProperties(Properties, String, String,
    *      boolean)
    */
   public static Color parseColorFromProperties(Properties p, String propName, String dfault)
         throws NumberFormatException {
      return ColorFactory.parseColorFromProperties(p, propName, dfault, false);
   }

   /**
    * Take a string from a properties file, representing the 24bit RGB or 32bit
    * ARGB hex values for a color, and convert it to a java.awt.Color.
    *
    * @param p properties
    * @param propName the name of the property
    * @param dfault color to use if the property value doesn't work
    * @param forceAlpha force using alpha value
    * @return java.awt.Color
    * @exception NumberFormatException if the specified string cannot be
    *            interpreted as a hexidecimal integer
    * @see ColorFactory#parseColorFromProperties(Properties, String, String,
    *      boolean)
    */
   public static Color parseColorFromProperties(Properties p, String propName, String dfault, boolean forceAlpha)
         throws NumberFormatException {
      return ColorFactory.parseColorFromProperties(p, propName, dfault, forceAlpha);
   }

   /**
    * Take a string from a properties file, representing the 24bit RGB or 32bit
    * ARGB hex values for a color, and convert it to a java.awt.Color.
    *
    * @param p properties
    * @param propName the name of the property
    * @param dfault color to use if the property value doesn't work
    * @return java.awt.Color
    * @see ColorFactory#parseColorFromProperties(Properties, String, String,
    *      boolean)
    */
   public static Paint parseColorFromProperties(Properties p, String propName, Paint dfault) {
      return ColorFactory.parseColorFromProperties(p, propName, dfault);
   }

   /**
    * Convert a string representing a 24/32bit hex color value into a Color
    * value. NOTE:
    *

    *
Only 24bit (RGB) java.awt.Color is supported on the JDK 1.1 platform.
    *
Both 24/32bit (ARGB) java.awt.Color is supported on the Java 2
    * platform.
    *

    *
    * @param colorString the 24/32bit hex string value (ARGB)
    * @param forceAlpha force using alpha value
    * @return java.awt.Color (24bit RGB on JDK 1.1, 24/32bit ARGB on JDK1.2)
    * @exception NumberFormatException if the specified string cannot be
    *            interpreted as a hexidecimal integer
    * @see ColorFactory#parseColor(String, boolean)
    */
   public static Color parseColor(String colorString, boolean forceAlpha)
         throws NumberFormatException {
      return ColorFactory.parseColor(colorString, forceAlpha);
   }

   /**
    * Convert a string representing a 24/32bit hex color value into a Color
    * value. NOTE:
    *

    *
Only 24bit (RGB) java.awt.Color is supported on the JDK 1.1 platform.
    *
Both 24/32bit (ARGB) java.awt.Color is supported on the Java 2
    * platform.
    *

    *
    * @param colorString the 24/32bit hex string value (ARGB)
    * @return java.awt.Color (24bit RGB on JDK 1.1, 24/32bit ARGB on JDK1.2)
    * @exception NumberFormatException if the specified string cannot be
    *            interpreted as a hexidecimal integer
    * @see ColorFactory#parseColor(String, boolean)
    */
   public static Color parseColor(String colorString)
         throws NumberFormatException {
      return ColorFactory.parseColor(colorString, false);
   }

   /**
    * Returns a string representing a color, properly buffered for zeros for
    * different alpha values.
    *
    * @param color
    * @return string for color with alpha values.
    */
   public static String getProperty(Color color) {
      StringBuffer hexstring = new StringBuffer(Integer.toHexString(color.getRGB()));
      while (hexstring.length() < 8) {
         hexstring.insert(0, '0');
      }
      return hexstring.toString();
   }

   /**
    * Converts a properties object to an array of Strings. The resulting array
    * will consist of alternating key-value strings.
    *
    * @param props the properties object to convert.
    * @return an array of Strings representing key-value pairs.
    */
   public static String[] getPropertiesAsStringArray(Properties props) {

      int size = props.size();
      String[] ret = new String[size * 2]; // key and value
      int count = 0;
      Enumeration<?> things = props.propertyNames();
      while (things.hasMoreElements()) {
         ret[count] = (String) things.nextElement();
         ret[count + 1] = (String) props.getProperty(ret[count]);
         count += 2;
      }
      return ret;
   }

   /**
    * Returns a URL that names either a resource, a local file, or an internet
    * URL. Resources are checked for in the general classpath.
    *
    * @param name name of the resource, file or URL.
    * @throws java.net.MalformedURLException
    * @return URL
    */
   public static URL getResourceOrFileOrURL(String name)
         throws java.net.MalformedURLException {
      return getResourceOrFileOrURL(null, name);
   }

   /**
    * Returns a URL that names either a resource, a local file, or an internet
    * URL.
    *
    * @param askingClass the object asking for the URL.
    * @param name name of the resource, file or URL.
    * @throws java.net.MalformedURLException
    * @return URL
    */
   public static URL getResourceOrFileOrURL(Object askingClass, String name)
         throws java.net.MalformedURLException {

      return getResourceOrFileOrURL(askingClass.getClass(), name);
   }

   /**
    * Returns a URL that names either a resource, a local file, or an internet
    * URL.
    *
    * @param askingClass the class asking for the URL. Can be null.
    * @param name name of the resource, file or URL.
    * @throws java.net.MalformedURLException
    * @return URL
    */
   public static URL getResourceOrFileOrURL(Class<? extends Object> askingClass, String name)
         throws java.net.MalformedURLException {

      boolean DEBUG = logger.isLoggable(Level.FINE);

      if (name == null) {
         if (DEBUG)
            logger.fine("null file name");
         return null;
      }

      URL retval = null;
      if (DEBUG)
         logger.fine("looking for " + name);

      if (askingClass != null) {
         // First see if we have a resource by that name
         if (DEBUG)
            logger.fine("checking as resource");

         retval = askingClass.getResource(name);
      }
      if (retval == null) {
         // Check the general classpath...
         if (DEBUG)
            logger.fine("checking in general classpath");
         retval = Thread.currentThread().getContextClassLoader().getResource(name);
      }

      // if (retval == null && !Environment.isApplet()) {
      // // Check the classpath plus the share directory, which may
      // // be in the openmap.jar file or in the development
      // // environment.
      // if (DEBUG)
      // logger.fine("checking with ClassLoader");
      // retval = ClassLoader.getSystemResource("share/" + name);
      // }

      if (retval == null && Environment.isApplet()) {
         if (DEBUG)
            logger.fine("checking with URLClassLoader");
         URL[] cba = new URL[1];
         cba[0] = Environment.getApplet().getCodeBase();
         URLClassLoader ucl = URLClassLoader.newInstance(cba);
         retval = ucl.getResource(name);
      }

      // If there was no resource by that name available
      if (retval == null) {
         if (DEBUG)
            logger.fine("not found as resource");

         try {
            java.io.File file = new java.io.File(name);
            if (file.exists()) {
               retval = file.toURI().toURL();
               if (DEBUG)
                  logger.fine("found as file :)");
            } else {
               // Otherwise treat it as a raw URL.
               if (DEBUG)
                  logger.fine("Not a file, checking as URL");
               retval = new URL(name);
               java.io.InputStream is = retval.openStream();
               is.close();
               if (DEBUG)
                  logger.fine("OK as URL :)");
            }
         } catch (java.io.IOException ioe) {
            retval = null;
         } catch (java.security.AccessControlException ace) {
            logger.warning("AccessControlException trying to access " + name);
            retval = null;
         } catch (Exception e) {
            logger.warning("caught exception " + e.getMessage());
            retval = null;
         }
      }

      if (DEBUG) {
         if (retval != null) {
            logger.fine("Resource " + name + "=" + retval.toString());
         } else {
            logger.fine("Resource " + name + " can't be found...");
         }
      }

      return retval;
   }

   /**
    * Simple space saving implementation of common I18n Property Info setting.
    *
    * @param i18n i18n object to use to search for internationalized strings.
    * @param info the properties class being used to set information into.
    * @param classToSetFor class to use for i18n search.
    * @param propertyName property to set for.
    * @param label label to use for GUI (can be null if N/A).
    * @param tooltip tooltip to use for GUI (can be null if N/A).
    * @param editor editor class string to use for GUI (can be null if N/A).
    * @return Properties object passed in, or new one if null Properties passed
    *         in.
    */
   public static Properties setI18NPropertyInfo(I18n i18n, Properties info, Class<? extends Object> classToSetFor,
                                                String propertyName, String label, String tooltip, String editor) {
      if (info == null) {
         info = new Properties();
      }
      if (i18n != null) {
         if (tooltip != null) {
            String internString = i18n.get(classToSetFor, propertyName, I18n.TOOLTIP, tooltip);
            info.put(propertyName, internString);
         }
         if (label != null) {
            String internString = i18n.get(classToSetFor, propertyName, label);
            info.put(propertyName + PropertyConsumer.LabelEditorProperty, internString);
         }
         if (editor != null) {
            info.put(propertyName + PropertyConsumer.ScopedEditorProperty, editor);
         }
      }
      return info;
   }

   public static void putDataPrefixToLayerList(Layer layer, Properties props, String layerListProperty) {
      String dataPrefix = (String) layer.getAttribute(Layer.DataPathPrefixProperty);
      if (dataPrefix != null && dataPrefix.length() > 0) {
         putDataPrefixToLayerList(dataPrefix, props, layerListProperty);
      }
   }

   /**
    * Handle setting the dataPathPrefixes on all layer's properties.
    */
   public static void putDataPrefixToLayerList(String dataPrefix, Properties props, String layerListProperty) {
      Vector<String> layersValue = parseSpacedMarkers(props.getProperty(layerListProperty));

      for (Iterator<String> it = layersValue.iterator(); it.hasNext();) {
         String markerName = getScopedPropertyPrefix(it.next());
         props.setProperty(markerName + Layer.DataPathPrefixProperty, dataPrefix);
      }
   }

   /**
    * Get a List of Objects defined by marker names listed in a property. If the
    * objects are PropertyConsumers, they will be given the properties and their
    * scoped property prefix so they can configure themselves.
    *
    *

    *
    * listProperty=markername1 markername2 markername3
    * markername1.definingProperty=classname1
    * markername2.definingProperty=classname2
    * markername3.definingProperty=classname3
    *
    *

    *
    * @param p Properties object containing all properties
    * @param markerListProperty listProperty in example above
    * @param definingProperty definingProperty in example above, scoped property
    *        when combined with marker name to define the class that should be
    *        created for an object.
    * @return List of objects created from properties
    */
   public static List<?> objectsFromProperties(Properties p, String markerListProperty, String definingProperty) {
      return objectsFromScopedProperties(p, markerListProperty, definingProperty, null);
      //
      // String markerList = p.getProperty(markerListProperty);
      // List<Object> ret = new LinkedList<Object>();
      //
      // if (markerList != null) {
      // Vector<String> markerNames = parseSpacedMarkers(markerList);
      // for (String markerName : markerNames) {
      // String classname = p.getProperty(markerName + "."
      // + definingProperty);
      // if (classname != null) {
      // Object obj = ComponentFactory.create(classname, markerName,
      // p);
      //
      // if (obj != null) {
      // ret.add(obj);
      // }
      // }
      // }
      //
      // }
      //
      // return ret;
   }

   /**
    * Get a List of Objects defined by marker names listed in a property, when
    * this list property has been scoped by a parent object definition. If the
    * objects are PropertyConsumers, they will be given the properties and their
    * scoped property prefix so they can configure themselves.
    *
    *

    *
    * parentMarker.listProperty=markername1 markername2 markername3
    * parentMarker.markername1.definingProperty=classname1
    * parentMarker.markername2.definingProperty=classname2
    * parentMarker.markername3.definingProperty=classname3
    *
    *

    *
    * @param p Properties object containing all properties
    * @param markerListProperty listProperty in example above
    * @param definingProperty definingProperty in example above, scoped property
    *        when combined with marker name to define the class that should be
    *        created for an object.
    * @return List of objects created from properties, where properties are
    *         scoped for each object.
    */
   public static List<?> objectsFromScopedProperties(Properties p, String markerListProperty, String definingProperty,
                                                     String parentMarker) {
      String markerList = p.getProperty(markerListProperty);
      List<Object> ret = new LinkedList<Object>();
      parentMarker = PropUtils.getScopedPropertyPrefix(parentMarker);

      if (markerList != null) {
         Vector<String> markerNames = parseSpacedMarkers(markerList);
         for (String markerName : markerNames) {
            String classname = p.getProperty(parentMarker + markerName + "." + definingProperty);
            if (classname != null) {
               Object obj = ComponentFactory.create(classname, markerName, p);

               if (obj != null) {
                  ret.add(obj);
               }
            }
         }
      }

      return ret;
   }

   /**
    * Add the object property value to properties if it's not null or empty,
    * which assumes it should be set to the default value.
    *
    * @param props Properties to write to
    * @param propertyName the scoped property to enter value under
    * @param value the object to get property from - toString() will be called
    *        if not null.
    */
   public static <T extends Object> void putIfNotDefault(Properties props, String propertyName, T value) {
      putIfNotDefault(props, propertyName, value, null);
   }

   /**
    * Add the object property value to properties if it's not null or default
    * value.
    *
    * @param props Properties to write to
    * @param propertyName the scoped property to enter value under
    * @param value the object to get property from - toString() will be called
    *        if not null.
    * @param def the default value of the property. If not null and value not
    *        null, toString().equals() will be used to determine equality. If
    *        not equal, then value will be set in props.
    */
   public static <T extends Object> void putIfNotDefault(Properties props, String propertyName, T value, T def) {
      if (value != null) {
         String valString = value.toString().trim();
         if (def == null || (def != null && !def.toString().trim().equals(valString))) {
            // empty property strings are a pain...
	     if (valString.length() != 0) {
               props.put(propertyName, valString);
            }
         }
      }
   }
}