text:
package jsystem.treeui;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;

import jsystem.framework.FrameworkOptions;
import jsystem.framework.JSystemProperties;
import jsystem.framework.report.ListenerstManager;
import jsystem.framework.sut.SimpleSutEditor;
import jsystem.framework.sut.SutEditor;
import jsystem.framework.sut.SutFactory;
import jsystem.runner.ErrorLevel;
import jsystem.treeui.error.ErrorPanel;
import jsystem.treeui.suteditor.TabbedSutXmlEditor;
import jsystem.utils.FileUtils;
import jsystem.utils.StringUtils;

import org.w3c.dom.Document;

public class SutEditorManager {

	private static SutEditorManager manager = null;

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

	private SutEditorManager() {
		// singleton
	}

	/**
	 */
	public static SutEditorManager getInstance() {
		if (manager == null) {
			manager = new SutEditorManager();
		}
		return manager;
	}

	public void launchEditor(){
		launchEditor(getEditor());
	}

	public void launchProcessedEditor(){
		launchProcessedEditor(getEditor());
	}

	/**
	 * Support launch of preset editor.
	 */
	public void launchEditor(final SutEditor editor) {
		if (!validateSUTFile()){
			return;
		}
		WaitDialog.launchWaitDialog("SUT editing ...", null,"(close sut editor to continue)",false);
		(new Thread() {
			public void run() {
				try {
					if (editor == null) {
						return;
					}
					Document doc = null;
					try {
						doc = editor.editSut(SutFactory.getInstance().getSutInstance().getOriginalDocument(), true);
						if (doc == null) {
							return;
						}
						File sutFile = SutFactory.getInstance().getSutFile();
						FileUtils.saveDocumentToFile(doc, sutFile);
						SutFactory.getInstance().setSut(sutFile.getName());
						copySutToTestsFolder(sutFile);
						ListenerstManager.getInstance().sutChanged(sutFile.getName());
					} catch (Exception e) {
						ErrorPanel.showErrorDialog("SUT Editor Fail", StringUtils.getStackTrace(e), ErrorLevel.Error);
						return;
					}
				} finally {
					WaitDialog.endWaitDialog();
				}

			}

			private void copySutToTestsFolder(File sutFile) {
				File classDir = new File(JSystemProperties.getCurrentTestsPath());
				if (sutFile.getAbsolutePath().startsWith(classDir.getAbsolutePath())) {
					File sutSrcFile = new File(JSystemProperties.getInstance().getPreference(
							FrameworkOptions.RESOURCES_SOURCE_FOLDER)
							+ sutFile.getAbsolutePath().substring(classDir.getAbsolutePath().length()));
					try {
						FileUtils.copyFile(sutFile, sutSrcFile);
					} catch (Exception e) {
						log.log(Level.SEVERE, "Failed updating SUT file", e);
					}
				}
			}
		}).start();
	}

	public void launchProcessedEditor(final SutEditor editor) {
		if (!validateSUTFile()){
			return;
		}
		if (editor == null) {
			return;
		}
		try {
			editor.editSut(SutFactory.getInstance().getSutInstance().getDocument(), false);
		} catch (Exception e) {
			ErrorPanel.showErrorDialog("SUT Editor Fail", StringUtils.getStackTrace(e), ErrorLevel.Error);
			return;
		}
	}

	/**
	 * Returns an instance of SutEditor according to the following flow:
	 *
	 * 1. Checks whether an SUT editor is defined in the jsystem.properties 2.
	 * If an editor is defined checks whether the editor can edit the current
	 * SUT; if so returns the defined editor. If the editor can not edit the
	 * current SUT, an error message is given to the user. 3. If an sut editor
	 * is not defined in the jsystem.properties file the method first checks if
	 * the TabbedSutXmlEditor can be used if so if not, the SimpleSutEditor is
	 * returned.
	 */
	private SutEditor getEditor() {
		SutEditor editor = null;
		try {
			String sutEditor = JSystemProperties.getInstance().getPreference(FrameworkOptions.SUT_EDITOR);
			if (sutEditor != null) {
				editor = (SutEditor) Class.forName(sutEditor).newInstance();
				if (!editor.isEditable(SutFactory.getInstance().getSutInstance().getDocument())) {
					ErrorPanel.showErrorDialog("SUT Error", "SUT can not be edited by " + sutEditor, ErrorLevel.Error);
					editor = null;
				}
			} else {
				editor = new TabbedSutXmlEditor();
				if (!editor.isEditable(SutFactory.getInstance().getSutInstance().getDocument())) {
					editor = new SimpleSutEditor();
				}
			}
		} catch (Exception e) {
			ErrorPanel.showErrorDialog("Failed to open SUT file. This can be a result of a corrupted SUT file or invalid editor class name.\nPlease check the SUT file structure and make sure the property " + FrameworkOptions.SUT_EDITOR.toString() +" in the jsystem.properties file holds a valid class name", StringUtils.getStackTrace(e), ErrorLevel.Error);
			editor = null;
		}
		return editor;
	}

	/**
	 */
	private boolean validateSUTFile() {
		try {
			FileUtils.readDocumentFromFile(SutFactory.getInstance().getSutFile());
		}catch (Exception e){
			ErrorPanel.showErrorDialog("Failed to open SUT file. " + e.getMessage(),StringUtils.getStackTrace(e), ErrorLevel.Error);
			return false;
		}
		return true;
	}
}


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

using Amazon.Util;

namespace Amazon.Auth.AccessControlPolicy
{
    ///
    /// A factory for creating conditions to be used in the policy.
    ///
    public partial class ConditionFactory
    {
        private ConditionFactory() { }

        #region Common Keys
        ///
        /// Condition key for the current time.
        /// <para>
        /// This condition key should only be used with <see cref="Amazon.Auth.AccessControlPolicy.ConditionFactory.DateComparisonType"/> enum.
        /// </para>
        ///
        public const string CURRENT_TIME_CONDITION_KEY = "aws:CurrentTime";

        ///
        /// Condition key for whether or not an incoming request is using a secure
        /// transport to make the request (i.e. HTTPS instead of HTTP).
        /// <para>
        /// This condition key should only be used with the boolean overload of NewCondition.
        /// </para>
        ///
        public const string SECURE_TRANSPORT_CONDITION_KEY = "aws:SecureTransport";

        ///
        /// Condition key for the source IP from which a request originates.
        /// <para>
        /// This condition key should only be used with <see cref="Amazon.Auth.AccessControlPolicy.ConditionFactory.IpAddressComparisonType"/> enum.
        /// </para>
        ///
        public const string SOURCE_IP_CONDITION_KEY = "aws:SourceIp";

        ///
        /// Condition key for the user agent included in a request.
        /// <para>
        /// This condition key should only be used with <see cref="Amazon.Auth.AccessControlPolicy.ConditionFactory.StringComparisonType"/>
        /// enum.
        /// </para>
        ///
        public const string USER_AGENT_CONDITION_KEY = "aws:UserAgent";

        ///
        /// Condition key for the current time, in epoch seconds.
        /// <para>
        /// This condition key should only be used with <see cref="Amazon.Auth.AccessControlPolicy.ConditionFactory.NumericComparisonType"/> enum.
        /// objects.
        /// </para>
        ///
        public const string EPOCH_TIME_CONDITION_KEY = "aws:EpochTime";

        ///
        /// Condition key for the referrer specified by a request.
        /// <para>
        /// This condition key should only be used with <see cref="Amazon.Auth.AccessControlPolicy.ConditionFactory.StringComparisonType"/>
        /// objects.
        /// </para>
        ///
        public const string REFERRER_CONDITION_KEY = "aws:Referer";

        ///
        /// Condition key for the Amazon Resource Name (ARN) of the source specified
        /// in a request. The source ARN indicates which resource is affecting the
        /// resource listed in your policy. For example, an SNS topic is the source
        /// ARN when publishing messages from the topic to an SQS queue.
        /// <para>
        /// This condition key should only be used with <see cref="Amazon.Auth.AccessControlPolicy.ConditionFactory.ArnComparisonType"/> enum.
        /// </para>
        ///
        public const string SOURCE_ARN_CONDITION_KEY = "aws:SourceArn";
        #endregion

        #region ArnComparisonType
        ///
        /// Enumeration of the supported ways an ARN comparison can be evaluated.
        ///
        public enum ArnComparisonType
        {
            /// Exact matching
            ArnEquals,

            ///
            /// Loose case-insensitive matching of the ARN. Each of the six
            /// colon-delimited components of the ARN is checked separately and each
            /// can include a multi-character match wildcard (*) or a
            /// single-character match wildcard (?).
            ///
            ArnLike,

            /// Negated form of ArnEquals
            ArnNotEquals,

            /// Negated form of ArnLike
            ArnNotLike
        };
        #endregion

        #region DateComparisonType
        ///
        /// Enumeration of the supported ways a date comparison can be evaluated.
        ///
        public enum DateComparisonType
        {
            DateEquals,
            DateGreaterThan,
            DateGreaterThanEquals,
            DateLessThan,
            DateLessThanEquals,
            DateNotEquals
        };
        #endregion

        #region IpAddressComparisonType
        ///
        /// Enumeration of the supported ways an IP address comparison can be evaluated.
        ///
        public enum IpAddressComparisonType
        {
            ///
            /// Matches an IP address against a CIDR IP range, evaluating to true if
            /// the IP address being tested is in the condition's specified CIDR IP
            /// range.
            ///
            IpAddress,

            ///
            /// Negated form of IpAddress
            ///
            NotIpAddress
        }
        #endregion

        #region NumericComparisonType
        ///
        /// Enumeration of the supported ways a numeric comparison can be evaluated
        ///
        public enum NumericComparisonType
        {
            NumericEquals,
            NumericGreaterThan,
            NumericGreaterThanEquals,
            NumericLessThan,
            NumericLessThanEquals,
            NumericNotEquals
        };
        #endregion

        #region StringComparisonType
        ///
        /// Enumeration of the supported ways a string comparison can be evaluated.
        ///
        public enum StringComparisonType
        {
            ///
            /// Case-sensitive exact string matching
            ///
            StringEquals,

            ///
            /// Case-insensitive string matching
            ///
            StringEqualsIgnoreCase,

            ///
            /// Loose case-insensitive matching. The values can include a
            /// multi-character match wildcard (*) or a single-character match
            /// wildcard (?) anywhere in the string.
            ///
            StringLike,

            ///
            /// Negated form of StringEquals.
            ///
            StringNotEquals,

            ///
            /// Negated form of StringEqualsIgnorecase.
            ///
            StringNotEqualsIgnoreCase,

            ///
            /// Negated form of StringLike.
            ///
            StringNotLike
        }
        #endregion

        ///
        /// Constructs a new access control policy condition that compares ARNs (Amazon Resource Names).
        ///
        /// <param name="key"> The access policy condition key specifying where to get the first ARN for the comparison</param>
        /// <param name="type">The type of comparison to perform.</param>
        /// <param name="value">The second ARN to compare against. When using ArnLike or ArnNotLike this may contain the
        ///     multi-character wildcard (*) or the single-character wildcard</param>
        public static Condition NewCondition(ArnComparisonType type, string key, string value)
        {
            return new Condition(type.ToString(), key, value);
        }

        ///
        /// Constructs a new access policy condition that performs a boolean
        /// comparison.
        ///
        /// <param name="key">The access policy condition key specifying where to get the
        ///            first boolean value for the comparison (ex: aws:SecureTransport).</param>
        /// <param name="value">The boolean to compare against.</param>
        public static Condition NewCondition(string key, bool value)
        {
            return new Condition("Bool", key, value.ToString().ToLower());
        }

        ///
        /// Constructs a new access policy condition that compares the current time
        /// (on the AWS servers) to the specified date.
        ///
        /// <param name="type">The type of comparison to perform. For example,
        ///            DateComparisonType.DateLessThan will cause this policy
        ///            condition to evaluate to true if the current date is less than
        ///            the date specified in the second argument.</param>
        /// <param name="date">The date to compare against.</param>
        public static Condition NewCondition(DateComparisonType type, DateTime date)
        {
            return new Condition(type.ToString(), CURRENT_TIME_CONDITION_KEY, date.ToString(AWSSDKUtils.ISO8601DateFormat));
        }

        ///
        /// Constructs a new access policy condition that compares the source IP
        /// address of the incoming request to an AWS service against the specified
        /// CIDR range. The condition evaluates to true (meaning the policy statement
        /// containing it will be applied) if the incoming source IP address is
        /// within that range.
        /// <para>
        /// To achieve the opposite effect (i.e. cause the condition to evaluate to
        /// true when the incoming source IP is not in the specified CIDR
        /// range) use the alternate constructor form and specify
        /// IpAddressComparisonType.NotIpAddress.
        /// </para>
        ///
        /// <param name="ipAddressRange">The CIDR IP range involved in the policy condition.</param>
        public static Condition NewIpAddressCondition(string ipAddressRange)
        {
            return NewCondition(IpAddressComparisonType.IpAddress, ipAddressRange);
        }

        ///
        /// Constructs a new access policy condition that compares the source IP
        /// address of the incoming request to an AWS service against the specified
        /// CIDR range. When the condition evaluates to true (i.e. when the incoming
        /// source IP address is within the CIDR range or not) depends on the
        /// specified IpAddressComparisonType.
        ///
        /// <param name="type">The type of comparison to to perform.</param>
        /// <param name="ipAddressRange">The CIDR IP range involved in the policy condition.</param>
        public static Condition NewCondition(IpAddressComparisonType type, string ipAddressRange)
        {
            return new Condition(type.ToString(), SOURCE_IP_CONDITION_KEY, ipAddressRange);
        }

        ///
        /// Constructs a new access policy condition that compares two numbers.
        ///
        /// <param name="type">The type of comparison to perform.</param>
        /// <param name="key">The access policy condition key specifying where to get the
        ///           first number for the comparison.</param>
        /// <param name="value">The second number to compare against.</param>
        public static Condition NewCondition(NumericComparisonType type, string key, string value)
        {
            return new Condition(type.ToString(), key, value);
        }

        ///
        /// Constructs a new access control policy condition that compares two
        /// strings.
        ///
        /// <param name="type">The type of comparison to perform</param>
        /// <param name="key">The access policy condition key specifying where to get the
        ///            first string for the comparison (ex: aws:UserAgent).
        /// </param>
        /// <param name="value">The second string to compare against. When using
        ///            StringComparisonType.StringLike or
        ///            StringComparisonType.StringNotLike this may contain
        ///            the multi-character wildcard (*) or the single-character
        ///            wildcard (?).
        /// </param>
        public static Condition NewCondition(StringComparisonType type, string key, string value)
        {
            return new Condition(type.ToString(), key, value);
        }

        ///
        /// Constructs a new access policy condition that compares the Amazon
        /// Resource Name (ARN) of the source of an AWS resource that is modifying
        /// another AWS resource with the specified pattern.
        /// <para>
        /// For example, the source ARN could be an Amazon SNS topic ARN that is
        /// sending messages to an Amazon SQS queue. In that case, the SNS topic ARN
        /// would be compared the ARN pattern specified here.
        /// </para>
        /// <para>
        /// The endpoint pattern may optionally contain the multi-character wildcard
        ///* (*) or the single-character wildcard (?). Each of the six colon-delimited
        /// components of the ARN is checked separately and each can include a
        /// wildcard.
        /// </para>
        ///
        /// Policy policy = new Policy("MyQueuePolicy");
        /// policy.WithStatements(new Statement(Statement.StatementEffect.Allow)
        ///     .WithPrincipals(new Principal("*")).WithActionIdentifiers(SQSActionIdentifiers.SendMessage)
        ///     .WithResources(new Resource(myQueueArn))
        ///     .WithConditions(ConditionFactory.NewSourceArnCondition(myTopicArn)));
        ///
        ///
        /// <param name="arnPattern">The ARN pattern against which the source ARN will be compared.
        ///     Each of the six colon-delimited components of the ARN is
        ///     checked separately and each can include a wildcard.</param>
        /// <returns>A new access control policy condition that compares the ARN of
        ///        the source specified in an incoming request with the ARN pattern
        ///        specified here.</returns>
        public static Condition NewSourceArnCondition(string arnPattern)
        {
            return NewCondition(ArnComparisonType.ArnLike, SOURCE_ARN_CONDITION_KEY, arnPattern);
        }

        ///
        /// Constructs a new access control policy condition that tests if the
        /// incoming request was sent over a secure transport (HTTPS).
        ///
        /// <returns>A new access control policy condition that tests if the incoming
        ///                 request was sent over a secure transport (HTTPS).</returns>
        public static Condition NewSecureTransportCondition()
        {
            return NewCondition(SECURE_TRANSPORT_CONDITION_KEY, true);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package hudson.maven;

import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.Functions;
import org.junit.Assert;
import org.jvnet.hudson.test.Bug;
import org.jvnet.hudson.test.ExtractResourceSCM;
import org.jvnet.hudson.test.ExtractResourceWithChangesSCM;
import org.jvnet.hudson.test.ExtractChangeLogSet;

import hudson.Launcher;
import hudson.Util;
import hudson.maven.reporters.MavenArtifactRecord;
import hudson.maven.reporters.MavenFingerprinter;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Job;
import hudson.model.PermalinkProjectAction;
import hudson.model.Result;
import hudson.tasks.Fingerprinter.FingerprintAction;
import hudson.tasks.Maven.MavenInstallation;
import java.io.File;

import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
import static org.junit.Assert.*;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

/**
 * @author Andrew Bayer
 */
public class MavenMultiModuleTest {

    @Rule public JenkinsRule j = new JenkinsRule();

    /**
     * NPE in {@code build.getProject().getWorkspace()} for {@link MavenBuild}.
     */
    @Bug(4192)
    @Test public void multiModMavenWsExists() throws Exception {
        j.configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_21);
        MavenModuleSet m = j.createMavenProject();
        m.getReporters().add(new TestReporter());
        m.setScm(new ExtractResourceSCM(getClass().getResource("maven-multimod.zip")));
	    assertFalse("MavenModuleSet.isNonRecursive() should be false", m.isNonRecursive());
        j.buildAndAssertSuccess(m);
    }

    @Bug(18846)
    @Test public void symlinksUpdated() throws Exception {
        Assume.assumeFalse(Functions.isWindows());
        j.configureDefaultMaven();
        MavenModuleSet mms = j.createMavenProject();
        mms.setScm(new ExtractResourceSCM(MavenMultiModuleTest.class.getResource("maven-multimod.zip")));
        j.buildAndAssertSuccess(mms);
        MavenModule mm = mms.getModule("org.jvnet.hudson.main.test.multimod:moduleA");
        j.buildAndAssertSuccess(mms);
        assertEquals(2, mms.getLastStableBuild().number);
        assertEquals(mms.getLastBuild().getId(), Util.resolveSymlink(new File(mms.getRootDir(), "builds/2")));
        assertEquals("2", Util.resolveSymlink(new File(mms.getRootDir(), "builds/lastStableBuild")));
        assertEquals("builds/lastStableBuild", Util.resolveSymlink(new File(mms.getRootDir(), "lastStable")));
        assertEquals("[lastBuild, lastStableBuild, lastSuccessfulBuild]", permalinks(mms).toString());
        assertEquals(2, mm.getLastStableBuild().number);
        assertEquals(mm.getLastBuild().getId(), Util.resolveSymlink(new File(mm.getRootDir(), "builds/2")));
        assertEquals("2", Util.resolveSymlink(new File(mm.getRootDir(), "builds/lastStableBuild")));
        assertEquals("builds/lastStableBuild", Util.resolveSymlink(new File(mm.getRootDir(), "lastStable")));
        assertEquals("[lastBuild, lastStableBuild, lastSuccessfulBuild]", permalinks(mm).toString());
    }
    private static Set<String> permalinks(Job<?,?> j) {
        Set<String> r = new TreeSet<String>();
        for (PermalinkProjectAction.Permalink l : j.getPermalinks()) {
            if (l.resolve(j) != null) {
                r.add(l.getId());
            }
        }
        return r;
    }

    @Test public void incrementalMultiModMaven() throws Exception {
        j.configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_21);
        MavenModuleSet m = j.createMavenProject();
        m.getReporters().add(new TestReporter());
        m.getReporters().add(new MavenFingerprinter());
    	m.setScm(new ExtractResourceWithChangesSCM(getClass().getResource("maven-multimod.zip"),
    						   getClass().getResource("maven-multimod-changes.zip")));

    	j.buildAndAssertSuccess(m);

    	// Now run a second build with the changes.
    	m.setIncrementalBuild(true);
        j.buildAndAssertSuccess(m);

    	MavenModuleSetBuild pBuild = m.getLastBuild();
    	ExtractChangeLogSet changeSet = (ExtractChangeLogSet) pBuild.getChangeSet();

    	assertFalse("ExtractChangeLogSet should not be empty.", changeSet.isEmptySet());

    	for (MavenBuild modBuild : pBuild.getModuleLastBuilds().values()) {
    	    String parentModuleName = modBuild.getParent().getModuleName().toString();
    	    if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod:moduleA")) {
    	        assertEquals("moduleA should have Result.NOT_BUILT", Result.NOT_BUILT, modBuild.getResult());
    	    }
    	    else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod:moduleB")) {
    	        assertEquals("moduleB should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
    	    }
    	    else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod:moduleC")) {
    	        assertEquals("moduleC should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
    	    }
    	}

	    long summedModuleDuration = 0;
	    for (MavenBuild modBuild : pBuild.getModuleLastBuilds().values()) {
	        summedModuleDuration += modBuild.getDuration();
	    }
	    assertTrue("duration of moduleset build should be greater-equal than sum of the module builds",
	            pBuild.getDuration() >= summedModuleDuration);

	    assertFingerprintWereRecorded(pBuild);
    }

    private void assertFingerprintWereRecorded(MavenModuleSetBuild modulesetBuild) {
        boolean mustHaveFingerprints = false;
        for (MavenBuild moduleBuild : modulesetBuild.getModuleLastBuilds().values()) {
            if (moduleBuild.getResult() != Result.NOT_BUILT && moduleBuild.getResult() != Result.ABORTED) {
                assertFingerprintWereRecorded(moduleBuild);
                mustHaveFingerprints = true;
            }
        }

        if (mustHaveFingerprints) {
            FingerprintAction action = modulesetBuild.getAction(FingerprintAction.class);
            Assert.assertNotNull(action);
            Assert.assertFalse(action.getFingerprints().isEmpty());
        }
    }

    private void assertFingerprintWereRecorded(MavenBuild moduleBuild) {
        FingerprintAction action = moduleBuild.getAction(FingerprintAction.class);
        Assert.assertNotNull(action);
        Assert.assertFalse(action.getFingerprints().isEmpty());

        MavenArtifactRecord artifactRecord = moduleBuild.getAction(MavenArtifactRecord.class);
        Assert.assertNotNull(artifactRecord);
        String fingerprintName = artifactRecord.mainArtifact.groupId + ":" + artifactRecord.mainArtifact.fileName;

        Assert.assertTrue("Expected fingerprint " + fingerprintName + " in module build " + moduleBuild,
              action.getFingerprints().containsKey(fingerprintName));

        // we should assert more - i.e. that all dependencies are fingerprinted, too,
        // but it's complicated to find out the dependencies of the build
    }

    @Bug(5357)
    @Test public void incrRelMultiModMaven() throws Exception {
        j.configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_21);
        MavenModuleSet m = j.createMavenProject();
        m.setRootPOM("parent/pom.xml");
        m.getReporters().add(new TestReporter());
        m.setScm(new ExtractResourceWithChangesSCM(getClass().getResource("maven-multimod-rel-base.zip"),
						   getClass().getResource("maven-multimod-changes.zip")));

        j.buildAndAssertSuccess(m);

        // Now run a second build with the changes.
        m.setIncrementalBuild(true);
        j.buildAndAssertSuccess(m);

        MavenModuleSetBuild pBuild = m.getLastBuild();
        ExtractChangeLogSet changeSet = (ExtractChangeLogSet) pBuild.getChangeSet();

        assertFalse("ExtractChangeLogSet should not be empty.", changeSet.isEmptySet());

        for (MavenBuild modBuild : pBuild.getModuleLastBuilds().values()) {
            String parentModuleName = modBuild.getParent().getModuleName().toString();
            if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod:moduleA")) {
                assertEquals("moduleA should have Result.NOT_BUILT", Result.NOT_BUILT, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod:moduleB")) {
                assertEquals("moduleB should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod:moduleC")) {
                assertEquals("moduleC should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
        }

        long summedModuleDuration = 0;
        for (MavenBuild modBuild : pBuild.getModuleLastBuilds().values()) {
            summedModuleDuration += modBuild.getDuration();
        }
        assertTrue("duration of moduleset build should be greater-equal than sum of the module builds",
        pBuild.getDuration() >= summedModuleDuration);
    }

    @Bug(6544)
    @Ignore("kutzi 10/10/11 ignore test until I can figure out why it fails sometimes")
    @Test public void estimatedDurationForIncrementalMultiModMaven()
            throws Exception {
        j.configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_21);
        MavenModuleSet m = j.createMavenProject();
        m.getReporters().add(new TestReporter());
        m.setScm(new ExtractResourceWithChangesSCM(getClass().getResource(
                "maven-multimod.zip"), getClass().getResource(
                "maven-multimod-changes.zip")));

        j.buildAndAssertSuccess(m);

        // Now run a second, incremental build with the changes.
        m.setIncrementalBuild(true);
        j.buildAndAssertSuccess(m);

        MavenModuleSetBuild lastBuild = m.getLastBuild();
        MavenModuleSetBuild previousBuild = lastBuild.getPreviousBuild();
        assertNull("There should be only one previous build", previousBuild.getPreviousBuild());

        // Since the estimated duration is calculated based on the previous builds
        // and there was only one previous build (which built all modules) and this build
        // did only build one module, the estimated duration of this build must be
        // smaller than the duration of the previous build.
        // (It's highly unlikely that the durations are equal, but I've already seen it fail.
        // Therefore <= instead of <)
        assertTrue("Estimated duration should be <= " + previousBuild.getDuration()
                + ", but is " + lastBuild.getEstimatedDuration(),
                lastBuild.getEstimatedDuration() <= previousBuild.getDuration());
    }

    /**
     * NPE in {@code getChangeSetFor(m)} in {@link MavenModuleSetBuild} when incremental build is
     * enabled and a new module is added.
     */
    @Test public void newModMultiModMaven() throws Exception {
        j.configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_21);
        MavenModuleSet m = j.createMavenProject();
        m.getReporters().add(new TestReporter());
        m.setScm(new ExtractResourceWithChangesSCM(getClass().getResource("maven-multimod.zip"),
                getClass().getResource("maven-multimod-changes.zip")));

        m.setIncrementalBuild(true);
        j.buildAndAssertSuccess(m);
    }

    /**
     * When "-N' or "--non-recursive" show up in the goals, any child modules should be ignored.
     */
    @Bug(4491)
    @Test public void multiModMavenNonRecursiveParsing() throws Exception {
        j.configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_21);
        MavenModuleSet m = j.createMavenProject();
        m.setGoals("clean install -N");
        m.getReporters().add(new TestReporter());
        m.setScm(new ExtractResourceSCM(getClass().getResource("maven-multimod.zip")));

        j.buildAndAssertSuccess(m);

        MavenModuleSetBuild pBuild = m.getLastBuild();

        for (MavenBuild modBuild : pBuild.getModuleLastBuilds().values()) {
            String parentModuleName = modBuild.getParent().getModuleName().toString();
            if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod:multimod-top")) {
                assertEquals("moduleA should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod:moduleA")) {
                assertEquals("moduleA should have Result.NOT_BUILT", Result.NOT_BUILT, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod:moduleB")) {
                assertEquals("moduleB should have Result.NOT_BUILT", Result.NOT_BUILT, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod:moduleC")) {
                assertEquals("moduleC should have Result.NOT_BUILT", Result.NOT_BUILT, modBuild.getResult());
            }

        }

    }

    /**
     * Module failures in build X should lead to those modules being re-run in build X+1, even if
     * incremental build is enabled and nothing changed in those modules.
     */
    @Bug(4152)
    @Test public void incrementalMultiModWithErrorsMaven() throws Exception {
        j.configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_21);
        MavenModuleSet m = j.createMavenProject();
        m.setIncrementalBuild(true);
        m.getReporters().add(new TestReporter());
        m.setScm(new ExtractResourceWithChangesSCM(getClass().getResource("maven-multimod-incr.zip"),
						   getClass().getResource("maven-multimod-changes.zip")));

        j.assertBuildStatus(Result.UNSTABLE, m.scheduleBuild2(0).get());
        MavenModuleSetBuild pBuild = m.getLastBuild();

        for (MavenBuild modBuild : pBuild.getModuleLastBuilds().values()) {
            String parentModuleName = modBuild.getParent().getModuleName().toString();
            if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleA")) {
                assertEquals("moduleA should have Result.UNSTABLE", Result.UNSTABLE, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleB")) {
                assertEquals("moduleB should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleC")) {
                assertEquals("moduleC should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleD")) {
                assertEquals("moduleD should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
        }

        // Now run a second build with the changes.
        j.assertBuildStatus(Result.UNSTABLE, m.scheduleBuild2(0).get());

    	pBuild = m.getLastBuild();
    	ExtractChangeLogSet changeSet = (ExtractChangeLogSet) pBuild.getChangeSet();

    	assertFalse("ExtractChangeLogSet should not be empty.", changeSet.isEmptySet());
    	// changelog contains a change for module B
    	assertEquals("Parent build should have Result.UNSTABLE", Result.UNSTABLE, pBuild.getResult());

    	for (MavenBuild modBuild : pBuild.getModuleLastBuilds().values()) {
    	    String parentModuleName = modBuild.getParent().getModuleName().toString();
    	    // A must be build again, because it was UNSTABLE before
    	    if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleA")) {
    	        assertEquals("moduleA should have Result.UNSTABLE", Result.UNSTABLE, modBuild.getResult());
    	    }
    	    // B must be build, because it has changes
    	    else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleB")) {
    	        assertEquals("moduleB should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
    	    }
    	    // C must be build, because it depends on B
    	    else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleC")) {
    	        assertEquals("moduleC should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
    	    }
    	    // D must not be build
    	    else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleD")) {
    	        assertEquals("moduleD should have Result.NOT_BUILT", Result.NOT_BUILT, modBuild.getResult());
    	    }
    	}
    }

    /**
     * If "deploy modules" is checked and aggregator build failed
     * then all modules build this time, have to be build next time, again.
     */
    @Bug(5121)
    @Test public void incrementalRedeployAfterAggregatorError() throws Exception {
        j.configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_21);
        MavenModuleSet m = j.createMavenProject();
        m.setIncrementalBuild(true);
        m.getReporters().add(new TestReporter());
        m.getPublishers().add(new DummyRedeployPublisher());
        m.setScm(new ExtractResourceWithChangesSCM(getClass().getResource("maven-multimod-incr.zip"),
                           getClass().getResource("maven-multimod-changes.zip")));

        j.assertBuildStatus(Result.UNSTABLE, m.scheduleBuild2(0).get());
        MavenModuleSetBuild pBuild = m.getLastBuild();

        for (MavenBuild modBuild : pBuild.getModuleLastBuilds().values()) {
            String parentModuleName = modBuild.getParent().getModuleName().toString();
            if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleA")) {
                assertEquals("moduleA should have Result.UNSTABLE", Result.UNSTABLE, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleB")) {
                assertEquals("moduleB should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleC")) {
                assertEquals("moduleC should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleD")) {
                assertEquals("moduleD should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
        }

        // Now run a second build.
        j.assertBuildStatus(Result.UNSTABLE, m.scheduleBuild2(0).get());

        pBuild = m.getLastBuild();
        ExtractChangeLogSet changeSet = (ExtractChangeLogSet) pBuild.getChangeSet();

        assertFalse("ExtractChangeLogSet should not be empty.", changeSet.isEmptySet());
        // changelog contains a change for module B
        assertEquals("Parent build should have Result.UNSTABLE", Result.UNSTABLE, pBuild.getResult());

        for (MavenBuild modBuild : pBuild.getModuleLastBuilds().values()) {
            String parentModuleName = modBuild.getParent().getModuleName().toString();
            // A must be build again, because it was UNSTABLE before
            if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleA")) {
                assertEquals("moduleA should have Result.UNSTABLE", Result.UNSTABLE, modBuild.getResult());
            }
            // B must be build, because it has changes
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleB")) {
                assertEquals("moduleB should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
            // C must be build, because it depends on B
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleC")) {
                assertEquals("moduleC should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
            // D must be build again, because it needs to be deployed now
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleD")) {
                assertEquals("moduleD should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
        }
    }

    /**
     * Test failures in a child module should lead to the parent being marked as unstable.
     */
    @Bug(4378)
    @Test public void multiModWithTestFailuresMaven() throws Exception {
        j.configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_21);
        MavenModuleSet m = j.createMavenProject();
        m.getReporters().add(new TestReporter());
        m.setScm(new ExtractResourceSCM(getClass().getResource("maven-multimod-incr.zip")));

        j.assertBuildStatus(Result.UNSTABLE, m.scheduleBuild2(0).get());

        MavenModuleSetBuild pBuild = m.getLastBuild();

        assertEquals("Parent build should have Result.UNSTABLE", Result.UNSTABLE, pBuild.getResult());

        for (MavenBuild modBuild : pBuild.getModuleLastBuilds().values()) {
            String parentModuleName = modBuild.getParent().getModuleName().toString();
            if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleA")) {
                assertEquals("moduleA should have Result.UNSTABLE", Result.UNSTABLE, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleB")) {
                assertEquals("moduleB should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleC")) {
                assertEquals("moduleC should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
            else if (parentModuleName.equals("org.jvnet.hudson.main.test.multimod.incr:moduleD")) {
                assertEquals("moduleD should have Result.SUCCESS", Result.SUCCESS, modBuild.getResult());
            }
        }
    }

    @Bug(8484)
    @Test public void multiModMavenNonRecursive() throws Exception {
        j.configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_21);
        MavenModuleSet m = j.createMavenProject();
        m.getReporters().add(new TestReporter());
        m.setScm(new ExtractResourceSCM(getClass().getResource("maven-multimod.zip")));
        m.setGoals( "-N validate" );
        assertTrue("MavenModuleSet.isNonRecursive() should be true", m.isNonRecursive());
        j.buildAndAssertSuccess(m);
        assertEquals("not only one module", 1, m.getModules().size());
    }

    @Bug(17713)
    @Test public void modulesPageLinks() throws Exception {
        j.configureMaven3();
        MavenModuleSet ms = j.createMavenProject();
        ms.setScm(new ExtractResourceSCM(getClass().getResource("maven-multimod.zip")));
        j.buildAndAssertSuccess(ms);
        MavenModule m = ms.getModule("org.jvnet.hudson.main.test.multimod:moduleA");
        assertNotNull(m);
        assertEquals(1, m.getLastBuild().getNumber());
        JenkinsRule.WebClient wc = j.createWebClient();
        HtmlPage modulesPage = wc.getPage(ms, "modules");
        modulesPage.getAnchorByText(m.getDisplayName()).openLinkInNewWindow();
    }

    /*
    @Test public void parallelMultiModMavenWsExists() throws Exception {
        configureDefaultMaven();
        MavenModuleSet m = createMavenProject();
	m.setAggregatorStyleBuild(false);
        m.getReporters().add(new TestReporter());
        m.setScm(new ExtractResourceSCM(getClass().getResource("maven-multimod.zip")));
        assertBuildStatusSuccess(m.scheduleBuild2(0).get());

	for (MavenModule mod : m.sortedActiveModules) {
	    while (mod.getLastBuild() == null) {
		Thread.sleep(500);
	    }

	    while (mod.getLastBuild().isBuilding()) {
		Thread.sleep(500);
	    }

	    assertBuildStatusSuccess(mod.getLastBuild());
	}

    }

    @Test public void privateRepoParallelMultiModMavenWsExists() throws Exception {
        configureDefaultMaven();
        MavenModuleSet m = createMavenProject();
	m.setAggregatorStyleBuild(false);
	m.setUsePrivateRepository(true);
        m.getReporters().add(new TestReporter());
        m.setScm(new ExtractResourceSCM(getClass().getResource("maven-multimod.zip")));
        assertBuildStatusSuccess(m.scheduleBuild2(0).get());

	for (MavenModule mod : m.sortedActiveModules) {
	    while (mod.getLastBuild() == null) {
		Thread.sleep(500);
	    }

	    while (mod.getLastBuild().isBuilding()) {
		Thread.sleep(500);
	    }

	    assertBuildStatusSuccess(mod.getLastBuild());
	}

    }
    */
    private static class TestReporter extends MavenReporter {
        @Override
        public boolean end(MavenBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            assertNotNull(build.getProject().getWorkspace());
            assertNotNull(build.getWorkspace());
            return true;
        }
    }

    private static class DummyRedeployPublisher extends RedeployPublisher {
        public DummyRedeployPublisher() {
            super("", "", false, false);
        }

        @Override
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
                BuildListener listener) throws InterruptedException,
                IOException {
            return true;
        }
    }
}


text:
import React, {createElement, Component} from 'react';
import Provider from 'react-redux';
import { createStore, applyMiddleware } from 'redux';

const localState = (component, localReducer, mws=[]) => {

  class LocalProvider extends Component {
    constructor(props, context) {
        super(props, context);
        this.parentStore = context.store;
        this.listener = this.listener.bind(this);
        this.localStore = createStore(localReducer,
            applyMiddleware.apply(null, [this.listener, ...mws]));
        this.overrideGetState();
    }

    overrideGetState(){
        const localGetState = this.localStore.getState;
        this.localStore.getState = () => ({
                ...this.parentStore.getState(),
                local: localGetState()
            });
    }

    getChildContext() {
        return { store: this.localStore };
    }

    listener() {
        return (next) => (action) => {
            let returnValue = next(action);
            this.parentStore.dispatch(action);
            return returnValue;
        };
    };

    render() {
        return createElement(component, this.props);
    }
  }
  LocalProvider.contextTypes = {store: React.PropTypes.object};
  LocalProvider.childContextTypes = {store: React.PropTypes.object};
  return LocalProvider;
};

export default localState;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />

  <title>Class: KMError</title>

  <link rel="stylesheet" href="./rdoc.css" type="text/css" media="screen" />

          Home
          Classes
          Methods

In Files

lib/km.rb

Parent

StandardError

Files

Gemfile

README.rdoc

Rakefile

Class/Module Index

        <form action="#" method="get" accept-charset="utf-8" class="initially-hidden">
        <fieldset>
          <legend>Quicksearch</legend>
          <input type="text" name="quicksearch" value=""
            class="quicksearch-field" />
        </fieldset>
        </form>

KMTS

KMTS::IdentError

KMTS::InitError

KMTS::SaaS

Accept

Hash

Helper

KMError

Object

String

No matching classes.

KMError

[Validate]

Generated with the Darkfish
      Rdoc Generator 2.


text:
const Sequelize = require('sequelize');

exports.getModel = (db) => {
  return db.define('match', {
    user_id: {
      type: Sequelize.INTEGER,
      references: {
        model: 'users',
        key: 'id',
        deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
      }
    },
    game_id: {
      type: Sequelize.INTEGER,
      references: {
        model: 'games',
        key: 'id',
        deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
      }
    },
    assertions: {
      type: Sequelize.INTEGER,
      allowNull: false
    }
  });
};


text:
#import <Foundation/NSObject.h>
#import <Foundation/NSRange.h>
#import <CoreFoundation/CFCalendar.h>

@class NSDateComponents,NSTimeZone,NSLocale,NSDate;

enum {
	NSEraCalendarUnit = kCFCalendarUnitEra,
	NSYearCalendarUnit = kCFCalendarUnitYear,
	NSMonthCalendarUnit = kCFCalendarUnitMonth,
	NSDayCalendarUnit = kCFCalendarUnitDay,
	NSHourCalendarUnit = kCFCalendarUnitHour,
	NSMinuteCalendarUnit = kCFCalendarUnitMinute,
	NSSecondCalendarUnit = kCFCalendarUnitSecond,
	NSWeekCalendarUnit = kCFCalendarUnitWeek,
	NSWeekdayCalendarUnit = kCFCalendarUnitWeekday,
    NSWeekdayOrdinalCalendarUnit = kCFCalendarUnitWeekdayOrdinal,
//   NSQuarterCalendarUnit = kCFCalendarUnitQuarter,
};
typedef NSUInteger NSCalendarUnit;

FOUNDATION_EXPORT NSString * const NSGregorianCalendar;

@interface NSCalendar : NSObject <NSCopying> {
   NSString   *_identifier;
   NSUInteger    _firstWeekday;
   NSUInteger    _minimumDaysInFirstWeek;
   NSTimeZone *_timeZone;
   NSLocale   *_locale;
}

+currentCalendar;

-initWithCalendarIdentifier:(NSString *)identifier;

-(NSString *)calendarIdentifier;
-(NSUInteger)firstWeekday;
-(NSUInteger)minimumDaysInFirstWeek;
-(NSTimeZone *)timeZone;
-(NSLocale *)locale;

-(void)setFirstWeekday:(NSUInteger)weekday;
-(void)setMinimumDaysInFirstWeek:(NSUInteger)days;
-(void)setTimeZone:(NSTimeZone *)timeZone;
-(void)setLocale:(NSLocale *)locale;

-(NSRange)minimumRangeOfUnit:(NSCalendarUnit)unit;
-(NSRange)maximumRangeOfUnit:(NSCalendarUnit)unit;
-(NSRange)rangeOfUnit:(NSCalendarUnit)unit inUnit:(NSCalendarUnit)inUnit forDate:(NSDate *)date;
-(NSUInteger)ordinalityOfUnit:(NSCalendarUnit)unit inUnit:(NSCalendarUnit)inUnit forDate:(NSDate *)date;

-(NSDateComponents *)components:(NSUInteger)flags fromDate:(NSDate *)date;
-(NSDateComponents *)components:(NSUInteger)flags fromDate:(NSDate *)fromDate toDate:(NSDate *)toDate options:(NSUInteger)options;

-(NSDate *)dateByAddingComponents:(NSDateComponents *)components toDate:(NSDate *)date options:(NSUInteger)options;
-(NSDate *)dateFromComponents:(NSDateComponents *)components;

@end


text:
<?php

namespace WSDL\Parser;

use Ouzo\Utilities\Strings;
use ReflectionClass;
use ReflectionMethod;

/**
 * ClassParser
 *
 * @author Piotr Olaszewski <piotroo89@gmail.com>
 */
class ClassParser
{
    /**
     * @var ReflectionClass
     */
    private $reflectedClass;
    /**
     * @var MethodParser[]
     */
    private $methodDocComments = array();

    public function __construct($className)
    {
        $this->reflectedClass = new ReflectionClass($className);
    }

    public function parse()
    {
        $this->allPublicMethodDocComment();
    }

    private function allPublicMethodDocComment()
    {
        $reflectionClassMethods = $this->reflectedClass->getMethods();
        foreach ($reflectionClassMethods as $reflectionMethod) {
            if ($this->canParseMethod($reflectionMethod)) {
                $methodName = $reflectionMethod->getName();
                $methodDocComment = $reflectionMethod->getDocComment();
                $this->methodDocComments[] = new MethodParser($methodName, $methodDocComment);
            }
        }
    }

    /**
     * @param ReflectionMethod $method
     * @return bool
     */
    private function canParseMethod(ReflectionMethod $method)
    {
        return
            Strings::contains($method->getDocComment(), '@WebMethod') &&
            $method->isPublic() &&
            !$method->isConstructor() &&
            !$method->isDestructor() &&
            !Strings::contains($method->getName(), '__');
    }

    /**
     * @return MethodParser[]
     */
    public function getMethods()
    {
        return $this->methodDocComments;
    }
}


text:
require 'rack/mount'
require 'forwardable'
require 'active_support/core_ext/object/to_query'
require 'action_dispatch/routing/deprecated_mapper'

module ActionDispatch
  module Routing
    class RouteSet #:nodoc:
      PARAMETERS_KEY = 'action_dispatch.request.path_parameters'

      class Dispatcher #:nodoc:
        def initialize(options={})
          @defaults = options[:defaults]
          @glob_param = options.delete(:glob)
          @controllers = {}
        end

        def call(env)
          params = env[PARAMETERS_KEY]
          prepare_params!(params)

          # Just raise undefined constant errors if a controller was specified as default.
          unless controller = controller(params, @defaults.key?(:controller))
            return [404, {'X-Cascade' => 'pass'}, []]
          end

          dispatch(controller, params[:action], env)
        end

        def prepare_params!(params)
          merge_default_action!(params)
          split_glob_param!(params) if @glob_param
        end

        # If this is a default_controller (i.e. a controller specified by the user)
        # we should raise an error in case it's not found, because it usually means
        # an user error. However, if the controller was retrieved through a dynamic
        # segment, as in :controller(/:action), we should simply return nil and
        # delegate the control back to Rack cascade. Besides, if this is not a default
        # controller, it means we should respect the @scope[:module] parameter.
        def controller(params, default_controller=true)
          if params && params.key?(:controller)
            controller_param = params[:controller]
            controller_reference(controller_param)
          end
        rescue NameError => e
          raise ActionController::RoutingError, e.message, e.backtrace if default_controller
        end

      private

        def controller_reference(controller_param)
          unless controller = @controllers[controller_param]
            controller_name = "#{controller_param.camelize}Controller"
            controller = @controllers[controller_param] =
              ActiveSupport::Dependencies.ref(controller_name)
          end
          controller.get
        end

        def dispatch(controller, action, env)
          controller.action(action).call(env)
        end

        def merge_default_action!(params)
          params[:action] ||= 'index'
        end

        def split_glob_param!(params)
          params[@glob_param] = params[@glob_param].split('/').map { |v| URI.unescape(v) }
        end
      end

      # A NamedRouteCollection instance is a collection of named routes, and also
      # maintains an anonymous module that can be used to install helpers for the
      # named routes.
      class NamedRouteCollection #:nodoc:
        include Enumerable
        attr_reader :routes, :helpers, :module

        def initialize
          clear!
        end

        def helper_names
          self.module.instance_methods.map(&:to_s)
        end

        def clear!
          @routes = {}
          @helpers = []

          @module ||= Module.new do
            instance_methods.each { |selector| remove_method(selector) }
          end
        end

        def add(name, route)
          routes[name.to_sym] = route
          define_named_route_methods(name, route)
        end

        def get(name)
          routes[name.to_sym]
        end

        alias []=   add
        alias []    get
        alias clear clear!

        def each
          routes.each { |name, route| yield name, route }
          self
        end

        def names
          routes.keys
        end

        def length
          routes.length
        end

        def reset!
          old_routes = routes.dup
          clear!
          old_routes.each do |name, route|
            add(name, route)
          end
        end

        def install(destinations = [ActionController::Base, ActionView::Base], regenerate = false)
          reset! if regenerate
          Array(destinations).each do |dest|
            dest.__send__(:include, @module)
          end
        end

        private
          def url_helper_name(name, kind = :url)
            :"#{name}_#{kind}"
          end

          def hash_access_name(name, kind = :url)
            :"hash_for_#{name}_#{kind}"
          end

          def define_named_route_methods(name, route)
            {:url => {:only_path => false}, :path => {:only_path => true}}.each do |kind, opts|
              hash = route.defaults.merge(:use_route => name).merge(opts)
              define_hash_access route, name, kind, hash
              define_url_helper route, name, kind, hash
            end
          end

          def define_hash_access(route, name, kind, options)
            selector = hash_access_name(name, kind)

            # We use module_eval to avoid leaks
            @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1
              def #{selector}(options = nil)                                      # def hash_for_users_url(options = nil)
                options ? #{options.inspect}.merge(options) : #{options.inspect}  #   options ? {:only_path=>false}.merge(options) : {:only_path=>false}
              end                                                                 # end
              protected :#{selector}                                              # protected :hash_for_users_url
            END_EVAL
            helpers << selector
          end

          # Create a url helper allowing ordered parameters to be associated
          # with corresponding dynamic segments, so you can do:
          #
          #   foo_url(bar, baz, bang)
          #
          # Instead of:
          #
          #   foo_url(:bar => bar, :baz => baz, :bang => bang)
          #
          # Also allow options hash, so you can do:
          #
          #   foo_url(bar, baz, bang, :sort_by => 'baz')
          #
          def define_url_helper(route, name, kind, options)
            selector = url_helper_name(name, kind)
            hash_access_method = hash_access_name(name, kind)

            @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1
              def #{selector}(*args)
                options =  #{hash_access_method}(args.extract_options!)

                if args.any?
                  options[:_positional_args] = args
                  options[:_positional_keys] = #{route.segment_keys.inspect}
                end

                url_for(options)
              end
            END_EVAL
            helpers << selector
          end
      end

      attr_accessor :set, :routes, :named_routes
      attr_accessor :disable_clear_and_finalize, :resources_path_names
      attr_accessor :default_url_options, :request_class, :valid_conditions

      def self.default_resources_path_names
        { :new => 'new', :edit => 'edit' }
      end

      def initialize(request_class = ActionDispatch::Request)
        self.routes = []
        self.named_routes = NamedRouteCollection.new
        self.resources_path_names = self.class.default_resources_path_names.dup
        self.controller_namespaces = Set.new
        self.default_url_options = {}

        self.request_class = request_class
        self.valid_conditions = request_class.public_instance_methods.map { |m| m.to_sym }
        self.valid_conditions.delete(:id)
        self.valid_conditions.push(:controller, :action)

        @disable_clear_and_finalize = false
        clear!
      end

      def draw(&block)
        clear! unless @disable_clear_and_finalize

        mapper = Mapper.new(self)
        if block.arity == 1
          mapper.instance_exec(DeprecatedMapper.new(self), &block)
        else
          mapper.instance_exec(&block)
        end

        finalize! unless @disable_clear_and_finalize

        nil
      end

      def finalize!
        return if @finalized
        @finalized = true
        @set.freeze
      end

      def clear!
        # Clear the controller cache so we may discover new ones
        @controller_constraints = nil
        @finalized = false
        routes.clear
        named_routes.clear
        @set = ::Rack::Mount::RouteSet.new(
          :parameters_key => PARAMETERS_KEY,
          :request_class  => request_class
        )
      end

      def install_helpers(destinations = [ActionController::Base, ActionView::Base], regenerate_code = false)
        Array(destinations).each { |d| d.module_eval { include Helpers } }
        named_routes.install(destinations, regenerate_code)
      end

      def url_helpers
        @url_helpers ||= begin
          routes = self

          helpers = Module.new do
            extend ActiveSupport::Concern
            include UrlFor

            @routes = routes
            class << self
              delegate :url_for, :to => '@routes'
            end
            extend routes.named_routes.module

            # ROUTES TODO: install_helpers isn't great... can we make a module with the stuff that
            # we can include?
            # Yes plz - JP
            included do
              routes.install_helpers(self)
              singleton_class.send(:define_method, :_routes) { routes }
            end

            define_method(:_routes) { routes }
          end

          helpers
        end
      end

      def empty?
        routes.empty?
      end

      def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
        route = Route.new(self, app, conditions, requirements, defaults, name, anchor)
        @set.add_route(*route)
        named_routes[name] = route if name
        routes << route
        route
      end

      class Generator #:nodoc:
        attr_reader :options, :recall, :set, :script_name, :named_route

        def initialize(options, recall, set, extras = false)
          @script_name = options.delete(:script_name)
          @named_route = options.delete(:use_route)
          @options     = options.dup
          @recall      = recall.dup
          @set         = set
          @extras      = extras

          normalize_options!
          normalize_controller_action_id!
          use_relative_controller!
          controller.sub!(%r{^/}, '') if controller
          handle_nil_action!
        end

        def controller
          @controller ||= @options[:controller]
        end

        def current_controller
          @recall[:controller]
        end

        def use_recall_for(key)
          if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
            if named_route_exists?
              @options[key] = @recall.delete(key) if segment_keys.include?(key)
            else
              @options[key] = @recall.delete(key)
            end
          end
        end

        def normalize_options!
          # If an explicit :controller was given, always make :action explicit
          # too, so that action expiry works as expected for things like
          #
          #   generate({:controller => 'content'}, {:controller => 'content', :action => 'show'})
          #
          # (the above is from the unit tests). In the above case, because the
          # controller was explicitly given, but no action, the action is implied to
          # be "index", not the recalled action of "show".

          if options[:controller]
            options[:action]     ||= 'index'
            options[:controller]   = options[:controller].to_s
          end

          if options[:action]
            options[:action] = options[:action].to_s
          end
        end

        # This pulls :controller, :action, and :id out of the recall.
        # The recall key is only used if there is no key in the options
        # or if the key in the options is identical. If any of
        # :controller, :action or :id is not found, don't pull any
        # more keys from the recall.
        def normalize_controller_action_id!
          @recall[:action] ||= 'index' if current_controller

          use_recall_for(:controller) or return
          use_recall_for(:action) or return
          use_recall_for(:id)
        end

        # if the current controller is "foo/bar/baz" and :controller => "baz/bat"
        # is specified, the controller becomes "foo/baz/bat"
        def use_relative_controller!
          if !named_route && different_controller?
            old_parts = current_controller.split('/')
            size = controller.count("/") + 1
            parts = old_parts[0...-size] << controller
            @controller = @options[:controller] = parts.join("/")
          end
        end

        # This handles the case of :action => nil being explicitly passed.
        # It is identical to :action => "index"
        def handle_nil_action!
          if options.has_key?(:action) && options[:action].nil?
            options[:action] = 'index'
          end
          recall[:action] = options.delete(:action) if options[:action] == 'index'
        end

        def generate
          path, params = @set.set.generate(:path_info, named_route, options, recall, opts)

          raise_routing_error unless path

          params.reject! {|k,v| !v }

          return [path, params.keys] if @extras

          path << "?#{params.to_query}" if params.any?
          "#{script_name}#{path}"
        rescue Rack::Mount::RoutingError
          raise_routing_error
        end

        def opts
          parameterize = lambda do |name, value|
            if name == :controller
              value
            elsif value.is_a?(Array)
              value.map { |v| Rack::Mount::Utils.escape_uri(v.to_param) }.join('/')
            else
              return nil unless param = value.to_param
              param.split('/').map { |v| Rack::Mount::Utils.escape_uri(v) }.join("/")
            end
          end
          {:parameterize => parameterize}
        end

        def raise_routing_error
          raise ActionController::RoutingError, "No route matches #{options.inspect}"
        end

        def different_controller?
          return false unless current_controller
          controller.to_param != current_controller.to_param
        end

        private
          def named_route_exists?
            named_route && set.named_routes[named_route]
          end

          def segment_keys
            set.named_routes[named_route].segment_keys
          end
      end

      # Generate the path indicated by the arguments, and return an array of
      # the keys that were not used to generate it.
      def extra_keys(options, recall={})
        generate_extras(options, recall).last
      end

      def generate_extras(options, recall={})
        generate(options, recall, true)
      end

      def generate(options, recall = {}, extras = false)
        Generator.new(options, recall, self, extras).generate
      end

      RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :port, :trailing_slash]

      def url_for(options)
        finalize!
        options = (options || {}).reverse_merge!(default_url_options)

        handle_positional_args(options)

        rewritten_url = ""

        path_segments = options.delete(:_path_segments)

        unless options[:only_path]
          rewritten_url << (options[:protocol] || "http")
          rewritten_url << "://" unless rewritten_url.match("://")
          rewritten_url << rewrite_authentication(options)

          raise "Missing host to link to! Please provide :host parameter or set default_url_options[:host]" unless options[:host]

          rewritten_url << options[:host]
          rewritten_url << ":#{options.delete(:port)}" if options.key?(:port)
        end

        path_options = options.except(*RESERVED_OPTIONS)
        path_options = yield(path_options) if block_given?
        path = generate(path_options, path_segments || {})

        # ROUTES TODO: This can be called directly, so script_name should probably be set in the routes
        rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path)
        rewritten_url << "##{Rack::Mount::Utils.escape_uri(options[:anchor].to_param.to_s)}" if options[:anchor]

        rewritten_url
      end

      def call(env)
        finalize!
        @set.call(env)
      end

      def recognize_path(path, environment = {})
        method = (environment[:method] || "GET").to_s.upcase
        path = Rack::Mount::Utils.normalize_path(path) unless path =~ %r{://}

        begin
          env = Rack::MockRequest.env_for(path, {:method => method})
        rescue URI::InvalidURIError => e
          raise ActionController::RoutingError, e.message
        end

        req = @request_class.new(env)
        @set.recognize(req) do |route, matches, params|
          params.each do |key, value|
            if value.is_a?(String)
              value = value.dup.force_encoding(Encoding::BINARY) if value.encoding_aware?
              params[key] = URI.unescape(value)
            end
          end

          dispatcher = route.app
          while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do
            dispatcher = dispatcher.app
          end

          if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, false)
            dispatcher.prepare_params!(params)
            return params
          end
        end

        raise ActionController::RoutingError, "No route matches #{path.inspect}"
      end

      private
        def handle_positional_args(options)
          return unless args = options.delete(:_positional_args)

          keys = options.delete(:_positional_keys)
          keys -= options.keys if args.size < keys.size - 1 # take format into account

          args = args.zip(keys).inject({}) do |h, (v, k)|
            h[k] = v
            h
          end

          # Tell url_for to skip default_url_options
          options.merge!(args)
        end

        def rewrite_authentication(options)
          if options[:user] && options[:password]
            "#{Rack::Utils.escape(options.delete(:user))}:#{Rack::Utils.escape(options.delete(:password))}@"
          else
            ""
          end
        end
    end
  end
end


text:
package androidx.media2.player;

import androidx.annotation.NonNull;

/**
 * An immutable object that represents the linear correlation between the media time
 * and the system time. It contains the media clock rate, together with the media timestamp
 * of an anchor frame and the system time when that frame was presented or is committed
 * to be presented.
 *

 * The phrase "present" means that audio/video produced on device is detectable by an external
 * observer off device.
 * The time is based on the implementation's best effort, using whatever knowledge
 * is available to the system, but cannot account for any delay unknown to the implementation.
 * The anchor frame could be any frame, including a just-rendered frame, or even a theoretical
 * or in-between frame, based on the source of the MediaTimestamp.
 * When the anchor frame is a just-rendered one, the media time stands for
 * current position of the playback or recording.
 *
 * @see MediaPlayer#getTimestamp
 */
public final class MediaTimestamp {
    /**
     * An unknown media timestamp value
     */
    public static @NonNull final MediaTimestamp TIMESTAMP_UNKNOWN =
            new MediaTimestamp(-1, -1, 0.0f);

    /**
     * Get the media time of the anchor in microseconds.
     */
    public long getAnchorMediaTimeUs() {
        return mMediaTimeUs;
    }

    /**
     * Get the {@link java.lang.System#nanoTime system time} corresponding to the media time
     * in nanoseconds.
     */
    public long getAnchorSystemNanoTime() {
        return mNanoTime;
    }

    /**
     * Get the rate of the media clock in relation to the system time.
     *

     * It is 1.0 if media clock advances in sync with the system clock;
     * greater than 1.0 if media clock is faster than the system clock;
     * less than 1.0 if media clock is slower than the system clock.
     */
    public float getMediaClockRate() {
        return mClockRate;
    }

    private final long mMediaTimeUs;
    private final long mNanoTime;
    private final float mClockRate;

    /* package */ MediaTimestamp(long mediaUs, long systemNs, float rate) {
        mMediaTimeUs = mediaUs;
        mNanoTime = systemNs;
        mClockRate = rate;
    }

    /* package */ MediaTimestamp() {
        mMediaTimeUs = 0;
        mNanoTime = 0;
        mClockRate = 1.0f;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }

        final MediaTimestamp that = (MediaTimestamp) obj;
        return (this.mMediaTimeUs == that.mMediaTimeUs)
                && (this.mNanoTime == that.mNanoTime)
                && (this.mClockRate == that.mClockRate);
    }

    @Override
    public int hashCode() {
        int result = Long.valueOf(mMediaTimeUs).hashCode();
        result = (int) (31 * result + mNanoTime);
        result = (int) (31 * result + mClockRate);
        return result;
    }

    @Override
    public String toString() {
        return getClass().getName()
                + "{AnchorMediaTimeUs=" + mMediaTimeUs
                + " AnchorSystemNanoTime=" + mNanoTime
                + " ClockRate=" + mClockRate
                + "}";
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<data xmlns="ns:workflow" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns:workflow resource:WorkflowData">
	<ruleAttributes xmlns="ns:workflow/RuleAttribute" xsi:schemaLocation="ns:workflow/RuleAttribute resource:RuleAttribute">

		<ruleAttribute>
			<name>XMLSearchableAttribute</name>
			<className>org.kuali.rice.kew.docsearch.xml.StandardGenericXMLSearchableAttribute</className>
			XML Searchable attribute
			<description>XML Searchable attribute</description>
			<type>SearchableXmlAttribute</type>
			<searchingConfig>
				<fieldDef name="givenname" title="First name">
					<display>
						<type>text</type>
					</display>
					<validation required="true">
						<regex>^[a-zA-Z ]+$</regex>
						<message>Invalid first name</message>
					</validation>
					<fieldEvaluation>
						<xpathexpression>//putWhateverWordsIwantInsideThisTag/givenname/value</xpathexpression>
					</fieldEvaluation>
				</fieldDef>
				<xmlSearchContent>
					<putWhateverWordsIwantInsideThisTag>
						<givenname>
							<value>%givenname%</value>
						</givenname>
					</putWhateverWordsIwantInsideThisTag>
				</xmlSearchContent>
			</searchingConfig>
		</ruleAttribute>
		<ruleAttribute>
			<name>BlankDropDownSearchAttribute</name>
			<className>org.kuali.rice.kew.docsearch.xml.StandardGenericXMLSearchableAttribute</className>
			DepartmentSearchAttribute
			<description>DepartmentSearchAttribute</description>
			<type>SearchableXmlAttribute</type>
			<searchingConfig>
				<fieldDef name="department" title="Department">
					<display>
						<type>select</type>
						<values title=""></values>
						<values title="African American/African Diaspora Studies">AAAD</values>
						<values title="African Studies">AFRI</values>
						<values title="American Studies">AMST</values>
						<values title="Ancient Studies">ANCS</values>
					</display>
					<fieldEvaluation>
						<xpathexpression>normalize-space(substring-before(//department, ' '))</xpathexpression>
					</fieldEvaluation>
				</fieldDef>
			</searchingConfig>
		</ruleAttribute>
	</ruleAttributes>
	<ruleTemplates xmlns="ns:workflow/RuleTemplate" xsi:schemaLocation="ns:workflow/RuleTemplate resource:RuleTemplate">
		<ruleTemplate>
			<name>searchTemplate</name>
			<description>search template</description>

		</ruleTemplate>
	</ruleTemplates>
	<documentTypes xmlns="ns:workflow/DocumentType" xsi:schemaLocation="ns:workflow/DocumentType resource:DocumentType">
		<documentType>
			<name>SearchDocType</name>
			<description>SearchDocType</description>
			SearchDocType
			<postProcessorName>org.kuali.rice.kew.postprocessor.DefaultPostProcessor</postProcessorName>
			<docHandler>_blank</docHandler>
			<superUserGroupName namespace="KR-WKFLW">TestWorkgroup</superUserGroupName>
			<blanketApproveGroupName namespace="KR-WKFLW">TestWorkgroup</blanketApproveGroupName>
			<defaultExceptionGroupName namespace="KR-WKFLW">TestWorkgroup</defaultExceptionGroupName>
			<active>true</active>
			<policies>
				<policy>
					<name>DEFAULT_APPROVE</name>
					<value>false</value>
				</policy>
			</policies>
			<attributes>
				<attribute>
					<name>XMLSearchableAttribute</name>
				</attribute>
			</attributes>
			<routePaths>
				<routePath>
					<start name="Initial" nextNode="First" />
					<requests name="First" />
				</routePath>
			</routePaths>
			<routeNodes>
				<start name="Initial">
					<activationType>P</activationType>
				</start>
				<requests name="First">
					<activationType>S</activationType>
					<ruleTemplate>searchTemplate</ruleTemplate>
				</requests>
			</routeNodes>
		</documentType>
	</documentTypes>
	<rules xmlns="ns:workflow/Rule" xsi:schemaLocation="ns:workflow/Rule resource:Rule">
		<rule>
			<documentType>SearchDocType</documentType>
			<ruleTemplate>searchTemplate</ruleTemplate>
			<description>Search attribute rule test</description>
			<forceAction>false</forceAction>
			<responsibilities>
				<responsibility>
					<user>jhopf</user>
					<actionRequested>A</actionRequested>
					<priority>1</priority>
				</responsibility>
			</responsibilities>
		</rule>
	</rules>
</data>


text:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#include "injfile.h"

#include "util/human.h"

struct injfile_t * injfile_init(void * ptr, size_t bytes) {
    /* This function will return ptr casted to (injfile_t *), but first it will perform a few checks and fix the
     * pointers to strings and lists. */
    struct injfile_t * inj = (struct injfile_t *)(ptr);

    /* Check if the file has a complete header. */
    if (bytes < sizeof(struct injfile_t))
        return NULL;

    /* Check magic. */
    if (strncmp(inj->magic, "adbi3inj", 8) != 0)
        return NULL;

    /* Check version. */
    if (inj->version != 0x0210)
        return NULL;

    /* Check code size */
    if (inj->code_offset + inj->code_size > bytes)
        return NULL;

    /* TODO: Perform remaining checks. */

    /* Create pointers from offsets. */
#define fix_ptr(x) inj->x = (inj->x ## _offset) ? ((void *) (((char *) inj) + (inj->x ## _offset))) : NULL;
    fix_ptr(code);
    fix_ptr(name);
    fix_ptr(comment);
    fix_ptr(adbi);
    fix_ptr(imports);
    fix_ptr(exports);
    fix_ptr(tpoints);
    fix_ptr(strings);
    fix_ptr(lines);
#undef fix_ptr

    return inj;
}

struct injfile_t * injfile_load(const char * path) {
    struct injfile_t * ret = NULL;
    void * buf = NULL;
    FILE * f = NULL;
    long size;

    if (!(f = fopen(path, "rb"))) {
        error("Error opening %s for reading: %s.", path, strerror(errno));
        goto out;
    }

    if (fseek(f, 0, SEEK_END) != 0) {
        error("Error seeking end of %s: %s.", path, strerror(errno));
        goto out;
    }

    if ((size = ftell(f)) < 0) {
        error("Error reading size of %s: %s.", path, strerror(errno));
        goto out;
    }

    if (fseek(f, 0, SEEK_SET) != 0) {
        error("Error seeking start of %s: %s.", path, strerror(errno));
        goto out;
    }

    if (!(buf = malloc(size))) {
        error("Error allocating memory for %s (%li bytes).", path, size);
        goto out;
    }

    size_t got = fread(buf, 1, size, f);

    if ((long) got != size) {
        if (feof(f))
            error("Error reading %s (%li bytes): unexpected end of file (got %zi bytes).", path, size, got);
        else if (ferror(f))
            error("Error reading %s (%li bytes): %s.", path, size, strerror(ferror(f)));

        goto out;
    }

    ret = injfile_init(buf, size);

out:
    if (f)
        fclose(f);
    if (!ret)
        free(buf);
    return ret;
}

void injfile_unload(struct injfile_t * injfile) {
    free(injfile);
}

void injfile_iter_tpoints(const struct injfile_t * injfile, injfile_tpoint_callback_t callback) {
    const struct injfile_tracepoint_t * tpoint;
    if (injfile->tpoints)
        for (tpoint = injfile->tpoints; tpoint->address; ++tpoint) {
            callback(tpoint->address, tpoint->handler_fn);
        }
}

static void injfile_iter_symbols(const struct injfile_symbol_t * symbol, injfile_symbol_callback_t callback) {
    if (symbol)
        for (; symbol->name[0]; ++symbol) {
            callback(symbol->name, symbol->offset);
        }
}

void injfile_iter_imports(const struct injfile_t * injfile, injfile_symbol_callback_t callback) {
    injfile_iter_symbols(injfile->imports, callback);
}

void injfile_iter_exports(const struct injfile_t * injfile, injfile_symbol_callback_t callback) {
    injfile_iter_symbols(injfile->exports, callback);
}

void injfile_iter_adbi(const struct injfile_t * injfile, injfile_symbol_callback_t callback) {
    injfile_iter_symbols(injfile->adbi, callback);
}

static offset_t injfile_get_symbol(const struct injfile_symbol_t * symbol, const char * name) {
    if (symbol)
        for (; symbol->name[0]; ++symbol) {
            if (strncmp(name, symbol->name, 28) == 0)
                return symbol->offset;
        }
    return -1;
}

offset_t injfile_get_import(const struct injfile_t * injfile, const char * name) {
    return injfile_get_symbol(injfile->imports, name);
}

offset_t injfile_get_export(const struct injfile_t * injfile, const char * name) {
    return injfile_get_symbol(injfile->exports, name);
}

offset_t injfile_get_adbi(const struct injfile_t * injfile, const char * name) {
    assert(injfile);
    return injfile_get_symbol(injfile->adbi, name);
}

/* Check if the inj file represents a library injectable. */
bool injfile_is_library(const struct injfile_t * injfile) {
    return (injfile->flags & INJFILE_FLAG_LIBRARY);
}

static const char * injfile_get_string(const struct injfile_t * injfile, uint32_t offset) {
    if (!injfile->strings) {
        /* no strings */
        return "<error>";
    }
    return injfile->strings + offset;
}

bool injfile_addr2line(const struct injfile_t * injfile, offset_t offset, const char ** filename,
                       uint32_t * line) {
    if (!injfile->lines) {
        /* no line information at all */
        return false;
    }

    struct injfile_lineinfo_t * li;

    for (li = injfile->lines; (li->addr | li->file | li->line); ++li) {
        if (li->addr > offset) {
            /* previous entry is the one we are looking for */
            break;
        }
    }

    if (!(li->addr | li->file | li->line) || (li->addr > offset)) {
        /* reached first element with address greater than given offset or last element */
        if (li == injfile->lines) {
            /* li has no previous element */
            return false;
        }

        --li;
        if (line)
            *line = li->line;
        if (filename)
            *filename = injfile_get_string(injfile, li->file);

        return true;
    }

    return false;
}


text:
Compute Pascal's triangle up to a given number of rows.

In Pascal's Triangle each number is computed by adding the numbers to
the right and left of the current position in the previous row.

```text
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1
# ... etc
```

## Setup

Go through the setup instructions for Javascript to install the necessary
dependencies:

[https://exercism.io/tracks/javascript/installation](https://exercism.io/tracks/javascript/installation)

## Requirements

Please `cd` into exercise directory before running all below commands.

Install assignment dependencies:

```bash
$ npm install
```

## Making the test suite pass

Execute the tests with:

```bash
$ npm test
```

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by changing `xtest` to
`test`.

## Submitting Solutions

Once you have a solution ready, you can submit it using:

```bash
exercism submit pascals-triangle.js
```

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have
completed the exercise.

## Exercise Source Credits

Pascal's Triangle at Wolfram Math World [http://mathworld.wolfram.com/PascalsTriangle.html](http://mathworld.wolfram.com/PascalsTriangle.html)


text:
@interface TumblrCreatePostViewController : UIViewController

@property (nonatomic, retain) TKBlog *blog;

- (id)init;

- (TKPost *)post;

@end


text:
onadata.apps.viewer.management.commands package
===============================================

Submodules
----------

onadata.apps.viewer.management.commands.import module
-----------------------------------------------------

.. automodule:: onadata.apps.viewer.management.commands.import
    :members:
    :undoc-members:
    :show-inheritance:

onadata.apps.viewer.management.commands.import_forms module
-----------------------------------------------------------

.. automodule:: onadata.apps.viewer.management.commands.import_forms
    :members:
    :undoc-members:
    :show-inheritance:

onadata.apps.viewer.management.commands.mark_start_times module
---------------------------------------------------------------

.. automodule:: onadata.apps.viewer.management.commands.mark_start_times
    :members:
    :undoc-members:
    :show-inheritance:

onadata.apps.viewer.management.commands.set_uuid_in_xml module
--------------------------------------------------------------

.. automodule:: onadata.apps.viewer.management.commands.set_uuid_in_xml
    :members:
    :undoc-members:
    :show-inheritance:

onadata.apps.viewer.management.commands.sync_mongo module
---------------------------------------------------------

.. automodule:: onadata.apps.viewer.management.commands.sync_mongo
    :members:
    :undoc-members:
    :show-inheritance:

onadata.apps.viewer.management.commands.update_delete_from_mongo module
-----------------------------------------------------------------------

.. automodule:: onadata.apps.viewer.management.commands.update_delete_from_mongo
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: onadata.apps.viewer.management.commands
    :members:
    :undoc-members:
    :show-inheritance:


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

public static class ConnectionMode {

    public static bool IsOffline() {
        if (!PlayerPrefs.HasKey("OfflineMode"))
            SetOnlineMode();
        return PlayerPrefs.GetInt("OfflineMode") == 1;
    }

    public static bool IsOnline() {
        return !IsOffline();
    }

    public static void SetOfflineMode() {
        PlayerPrefs.SetInt("OfflineMode", 1);
    }

    public static void SetOnlineMode() {
        PlayerPrefs.SetInt("OfflineMode", 0);
    }
}


text:
package com.sksamuel.elastic4s.alias

case class GetAliasDefinition(aliases: Seq[String],
                              indices: Seq[String] = Nil) {
  def on(indices: String*): GetAliasDefinition = copy(indices = indices)
}


text:
// Generated source
package org.jetbrains.wip.protocol.dom;

/**
 * Sets attribute for an element with given id.
 */
public final class SetAttributeValue extends org.jetbrains.wip.protocol.WipRequest {
  /**
   * @param nodeId Id of the element to set attribute for.
   * @param name Attribute name.
   * @param value Attribute value.
   */
  public SetAttributeValue(int nodeId, String name, String value) {
    writeInt("nodeId", nodeId);
    writeString("name", name);
    writeString("value", value);
  }
  @Override
  public String getMethodName() {
    return "DOM.setAttributeValue";
  }
}


text:
package demo.hw.client;

import java.io.File;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.ProtocolException;
import org.apache.hello_world_soap12_http.Greeter;
import org.apache.hello_world_soap12_http.PingMeFault;
import org.apache.hello_world_soap12_http.SOAPService;
import org.apache.hello_world_soap12_http.types.FaultDetail;

public final class Client {

    private static final QName SERVICE_NAME
        = new QName("http://apache.org/hello_world_soap12_http", "SOAPService");

    private Client() {
    }

    public static void main(String args[]) throws Exception {

        if (args.length == 0) {
            System.out.println("please specify wsdl");
            System.exit(1);
        }

        URL wsdlURL;
        File wsdlFile = new File(args[0]);
        if (wsdlFile.exists()) {
            wsdlURL = wsdlFile.toURI().toURL();
        } else {
            wsdlURL = new URL(args[0]);
        }

        System.out.println(wsdlURL);
        SOAPService ss = new SOAPService(wsdlURL, SERVICE_NAME);
        Greeter port = ss.getSoapPort();
        String resp;

        System.out.println("Invoking sayHi...");
        resp = port.sayHi();
        System.out.println("Server responded with: " + resp);
        System.out.println();

        System.out.println("Invoking greetMe...");
        resp = port.greetMe(System.getProperty("user.name"));
        System.out.println("Server responded with: " + resp);
        System.out.println();

        System.out.println("Invoking greetMe with invalid length string, expecting exception...");
        try {
            resp = port.greetMe("Invoking greetMe with invalid length string, expecting exception...");
        } catch (ProtocolException e) {
            System.out.println("Expected exception has occurred: " + e.getClass().getName());
        }

        System.out.println();

        System.out.println("Invoking greetMeOneWay...");
        port.greetMeOneWay(System.getProperty("user.name"));
        System.out.println("No response from server as method is OneWay");
        System.out.println();

        try {
            System.out.println("Invoking pingMe, expecting exception...");
            port.pingMe();
        } catch (PingMeFault ex) {
            System.out.println("Expected exception: PingMeFault has occurred: " + ex.getMessage());
            FaultDetail detail = ex.getFaultInfo();
            System.out.println("FaultDetail major:" + detail.getMajor());
            System.out.println("FaultDetail minor:" + detail.getMinor());
        }
        System.exit(0);
    }

}


text:
<?php

class ModelTest extends TestCase
{

    function testInsertAndUpdateAndDelete()
    {
        $user = new User();
        $mapper = new UserMapper($this->adapter);
        $user->name = 'model';
        $result_save = $mapper->save($user);

        $id = $mapper->getConnection()->lastInsertId();
        $user->id = $id;
        $user->name = 'model update';
        $result_update = $mapper->save($user);

        $result_load = $mapper->loadById($id);
        $result_delete = $mapper->delete($user);
        $result_delete_load = $mapper->loadById($id);

        $this->assertEquals($result_save, 1);
        $this->assertEquals($result_update, 1);
        $this->assertEquals((bool)$result_load, true);
        $this->assertEquals($result_delete, 1);
        $this->assertEquals((bool)$result_delete_load, false);
    }

}


text:
import nova.conf
from nova import test

CONF = nova.conf.CONF

class DevicesConfTestCase(test.NoDBTestCase):

    def test_register_dynamic_opts(self):
        self.flags(enabled_vgpu_types=['nvidia-11', 'nvidia-12'],
                   group='devices')

        self.assertNotIn('vgpu_nvidia-11', CONF)
        self.assertNotIn('vgpu_nvidia-12', CONF)

        nova.conf.devices.register_dynamic_opts(CONF)

        self.assertIn('vgpu_nvidia-11', CONF)
        self.assertIn('vgpu_nvidia-12', CONF)
        self.assertEqual([], getattr(CONF, 'vgpu_nvidia-11').device_addresses)
        self.assertEqual([], getattr(CONF, 'vgpu_nvidia-12').device_addresses)


text:
#ifndef INCLUDED_com_haxepunk_utils_Touch
#define INCLUDED_com_haxepunk_utils_Touch

#ifndef HXCPP_H
#include <hxcpp.h>
#endif

HX_DECLARE_CLASS3(com,haxepunk,utils,Touch)
namespace com{
namespace haxepunk{
namespace utils{

class HXCPP_CLASS_ATTRIBUTES  Touch_obj : public hx::Object{
	public:
		typedef hx::Object super;
		typedef Touch_obj OBJ_;
		Touch_obj();
		Void __construct(Float x,Float y,int id);

	public:
		static hx::ObjectPtr< Touch_obj > __new(Float x,Float y,int id);
		static Dynamic __CreateEmpty();
		static Dynamic __Create(hx::DynamicArray inArgs);
		~Touch_obj();

		HX_DO_RTTI;
		static void __boot();
		static void __register();
		void __Mark(HX_MARK_PARAMS);
		void __Visit(HX_VISIT_PARAMS);
		::String __ToString() const { return HX_CSTRING("Touch"); }

		virtual Void update( );
		Dynamic update_dyn();

		virtual bool get_pressed( );
		Dynamic get_pressed_dyn();

		virtual Float get_sceneY( );
		Dynamic get_sceneY_dyn();

		virtual Float get_sceneX( );
		Dynamic get_sceneX_dyn();

		Float time;
		Float y;
		Float x;
		int id;
};

} // end namespace com
} // end namespace haxepunk
} // end namespace utils

#endif /* INCLUDED_com_haxepunk_utils_Touch */


text:
#include <sys/stat.h>

#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/ext/base/file_utils.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/utils.h"

#if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) || \
    PERFETTO_BUILDFLAG(PERFETTO_COMPILER_GCC)
#include <unistd.h>
#else
#include <corecrt_io.h>
#include <io.h>
#endif

namespace perfetto {
namespace base {
namespace {
constexpr size_t kBufSize = 2048;
}

bool ReadFileDescriptor(int fd, std::string* out) {
  // Do not override existing data in string.
  size_t i = out->size();

  struct stat buf {};
  if (fstat(fd, &buf) != -1) {
    if (buf.st_size > 0)
      out->resize(i + static_cast<size_t>(buf.st_size));
  }

  ssize_t bytes_read;
  for (;;) {
    if (out->size() < i + kBufSize)
      out->resize(out->size() + kBufSize);

    bytes_read = PERFETTO_EINTR(read(fd, &((*out)[i]), kBufSize));
    if (bytes_read > 0) {
      i += static_cast<size_t>(bytes_read);
    } else {
      out->resize(i);
      return bytes_read == 0;
    }
  }
}

bool ReadFileStream(FILE* f, std::string* out) {
  return ReadFileDescriptor(fileno(f), out);
}

bool ReadFile(const std::string& path, std::string* out) {
  base::ScopedFile fd = base::OpenFile(path, O_RDONLY);
  if (!fd)
    return false;

  return ReadFileDescriptor(*fd, out);
}

ssize_t WriteAll(int fd, const void* buf, size_t count) {
  size_t written = 0;
  while (written < count) {
    ssize_t wr = PERFETTO_EINTR(
        write(fd, static_cast<const char*>(buf) + written, count - written));
    if (wr == 0)
      break;
    if (wr < 0)
      return wr;
    written += static_cast<size_t>(wr);
  }
  return static_cast<ssize_t>(written);
}

bool FlushFile(int fd) {
  PERFETTO_DCHECK(fd != 0);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
    PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
  return !PERFETTO_EINTR(fdatasync(fd));
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return !PERFETTO_EINTR(_commit(fd));
#else
  return !PERFETTO_EINTR(fsync(fd));
#endif
}

}  // namespace base
}  // namespace perfetto


text:
* [IBM Watson Text To Speech - API Reference](https://cloud.ibm.com/apidocs/text-to-speech?code=swift)
* [IBM Watson Text To Speech - Documentation](https://cloud.ibm.com/docs/text-to-speech/index.html)
* [IBM Watson Text To Speech - Service Page](https://www.ibm.com/cloud/watson-text-to-speech)

The IBM Watson Text to Speech service synthesizes natural-sounding speech from input text in a variety of languages and voices that speak with appropriate cadence and intonation.

The following example demonstrates how to use the Text to Speech service:

```swift
import TextToSpeechV1

let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let textToSpeech = TextToSpeech(authenticator: authenticator)
textToSpeech.serviceURL = "{url}"

textToSpeech.synthesize(text: "Hello World", voice: "en-US_AllisonV3Voice", accept: "audio/wav") {
  response, error in

  guard let audio = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  let audioFile = URL(fileURLWithPath: NSTemporaryDirectory() + "hello_world.wav")
  do {
    try audio.write(to: audioFile)
    // Audio saved to file hello_world.wav.
  } catch {
    print("Error writing: \(error)")
  }
}
```
For details on all API operations, including Swift examples, [see the API reference.](https://cloud.ibm.com/apidocs/text-to-speech?code=swift)


text:
<!DOCTYPE html>

<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Powerboard Employee Portal</title>
<link rel="stylesheet" href="<?php echo base_url();?>css/bootstrap.min.css" />
<link rel="stylesheet" href="<?php echo base_url();?>css/styles.css" />

            <a style="padding: 0;" class="navbar-brand" href="<?php echo base_url();?>main">
                <img src="<?php echo base_url();?>img/logo.jpg" />

            <li class="
            <?php
                if(!$this->uri->segment(2)) {
                    if($this->uri->segment(1) == 'main') {echo 'active';};
                }
            ?>">
                <a href="<?php echo base_url();?>main"> Home

            <?php if($this->session->userdata('group_id') <= 2) : ?>

                <a href="<?php echo base_url();?>admin/dashboard"> Dashboard

            <?php endif;?>

                <a href="<?php echo base_url();?>authenticate/logout"> Logout