text:
package org.kuali.rice.kns.workflow.attribute;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kuali.rice.core.api.util.KeyValue;
import org.kuali.rice.core.api.util.xml.XmlJotter;
import org.kuali.rice.kew.rule.xmlrouting.XPathHelper;
import org.kuali.rice.krad.keyvalues.KeyValuesFinder;
import org.kuali.rice.krad.service.DataDictionaryService;
import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @deprecated Only used by KNS classes, no replacement.
 */
@Deprecated
public class KualiXmlAttributeHelper {
    private static Log LOG = LogFactory.getLog(KualiXmlAttributeHelper.class);
    private static XPath xpath = XPathHelper.newXPath();
    private static final String testVal = "\'/[^\']*\'";// get the individual xpath tests.
    private static final String testVal2 = "/[^/]+/" + "*";// have to do this or the compiler gets confused by end comment.
    private static final String cleanVal = "[^/\']+";// get rid of / and ' in the resulting term.
    private static final String ruledataVal = "ruledata[^\']*\'([^\']*)";
    // TODO - enter JIRA
    // below removes wf:xstreamsafe( and )
    // below separates each wf:xstreamsafe() section into separate 'finds'
    private static final Pattern xPathPattern = Pattern.compile(testVal);
    private static final Pattern termPattern = Pattern.compile(testVal2);
    private static final Pattern cleanPattern = Pattern.compile(cleanVal);
    private static final Pattern targetPattern = Pattern.compile(ruledataVal);

    public static final String ATTRIBUTE_LABEL_BO_REFERENCE_PREFIX = "kuali_dd_label(";
    public static final String ATTRIBUTE_LABEL_BO_REFERENCE_SUFFIX = ")";
    public static final String ATTRIBUTE_SHORT_LABEL_BO_REFERENCE_PREFIX = "kuali_dd_short_label(";
    public static final String ATTRIBUTE_SHORT_LABEL_BO_REFERENCE_SUFFIX = ")";
    private static final String KUALI_VALUES_FINDER_REFERENCE_PREFIX = "kuali_values_finder_class(";
    private static final String KUALI_VALUES_FINDER_REFERENCE_SUFFIX = ")";
    public static final String notFound = "Label Not Found";

    private String lastXPath = "";

    /**
     * This method overrides the super class and modifies the XML that it operates on to put the name and the title in the place
     * where the super class expects to see them, even though they may no longer exist in the original XML.
     *
     * @see org.kuali.rice.kew.rule.xmlrouting.StandardGenericXMLRuleAttribute#getConfigXML()
     */

    public Element processConfigXML(Element root) {
        return this.processConfigXML(root, null);
    }

    /**
     * This method overrides the super class and modifies the XML that it operates on to put the name and the title in the place
     * where the super class expects to see them, overwriting the original title in the XML.
     *
     * @see org.kuali.rice.kew.rule.xmlrouting.StandardGenericXMLRuleAttribute#getConfigXML()
     */

    public Element processConfigXML(Element root, String[] xpathExpressionElements) {

        NodeList fields = root.getElementsByTagName("fieldDef");
        Element theTag = null;
        String docContent = "";

        /**
         * This section will check to see if document content has been defined in the configXML for the document type, by running an
         * XPath. If this is an empty list the xpath expression in the fieldDef is used to define the xml document content that is
         * added to the configXML. The xmldocument content is of this form, when in the document configXML. <xmlDocumentContent>
         * <org.kuali.rice.krad.bo.SourceAccountingLine> <amount> <value>%totaldollarAmount%</value> </amount>
         * </org.kuali.rice.krad.bo.SourceAccountingLine> </xmlDocumentContent> This class generates this on the fly, by creating an XML
         * element for each term in the XPath expression. When this doesn't apply XML can be coded in the configXML for the
         * ruleAttribute.
         *
         * @see org.kuali.rice.kew.plugin.attributes.WorkflowAttribute#getDocContent()
         */

        org.w3c.dom.Document xmlDoc = null;
        if (!xmlDocumentContentExists(root)) { // XML Document content is given because the xpath is non standard
            fields = root.getElementsByTagName("fieldDef");
            xmlDoc = root.getOwnerDocument();
        }
        for (int i = 0; i < fields.getLength(); i++) { // loop over each fieldDef
            String name = null;
            if (!xmlDocumentContentExists(root)) {
                theTag = (Element) fields.item(i);

                /*
                 * Even though there may be multiple xpath test, for example one for source lines and one for target lines, the
                 * xmlDocumentContent only needs one, since it is used for formatting. The first one is arbitrarily selected, since
                 * they are virtually equivalent in structure, most of the time.
                 */

                List<String> xPathTerms = getXPathTerms(theTag);
                if (xPathTerms.size() != 0) {
                    Node iterNode = xmlDoc.createElement("xmlDocumentContent");

                    xmlDoc.normalize();

                    iterNode.normalize();

                    /*
                     * Since this method is run once per attribute and there may be multiple fieldDefs, the first fieldDef is used
                     * to create the configXML.
                     */
                    for (int j = 0; j < xPathTerms.size(); j++) {// build the configXML based on the Xpath
                        // TODO - Fix the document content element generation
                        iterNode.appendChild(xmlDoc.createElement(xPathTerms.get(j)));
                        xmlDoc.normalize();

                        iterNode = iterNode.getFirstChild();
                        iterNode.normalize();

                    }
                    iterNode.setTextContent("%" + xPathTerms.get(xPathTerms.size() - 1) + "%");
                    root.appendChild(iterNode);
                }
            }
            theTag = (Element) fields.item(i);
            // check to see if a values finder is being used to set valid values for a field
            NodeList displayTagElements = theTag.getElementsByTagName("display");
            if (displayTagElements.getLength() == 1) {
                Element displayTag = (Element) displayTagElements.item(0);
                List valuesElementsToAdd = new ArrayList();
                for (int w = 0; w < displayTag.getChildNodes().getLength(); w++) {
                    Node displayTagChildNode = (Node) displayTag.getChildNodes().item(w);
                    if ((displayTagChildNode != null) && ("values".equals(displayTagChildNode.getNodeName()))) {
                        if (displayTagChildNode.getChildNodes().getLength() > 0) {
                            String valuesNodeText = displayTagChildNode.getFirstChild().getNodeValue();
                            String potentialClassName = getPotentialKualiClassName(valuesNodeText, KUALI_VALUES_FINDER_REFERENCE_PREFIX, KUALI_VALUES_FINDER_REFERENCE_SUFFIX);
                            if (StringUtils.isNotBlank(potentialClassName)) {
                                try {
                                    Class finderClass = Class.forName((String) potentialClassName);
                                    KeyValuesFinder finder = (KeyValuesFinder) finderClass.newInstance();
                                    NamedNodeMap valuesNodeAttributes = displayTagChildNode.getAttributes();
                                    Node potentialSelectedAttribute = (valuesNodeAttributes != null) ? valuesNodeAttributes.getNamedItem("selected") : null;
                                    for (Iterator iter = finder.getKeyValues().iterator(); iter.hasNext();) {
                                        KeyValue keyValue = (KeyValue) iter.next();
                                        Element newValuesElement = root.getOwnerDocument().createElement("values");
                                        newValuesElement.appendChild(root.getOwnerDocument().createTextNode(keyValue.getKey()));
                                        // newValuesElement.setNodeValue(KeyValue.getKey().toString());
                                        newValuesElement.setAttribute("title", keyValue.getValue());
                                        if (potentialSelectedAttribute != null) {
                                            newValuesElement.setAttribute("selected", potentialSelectedAttribute.getNodeValue());
                                        }
                                        valuesElementsToAdd.add(newValuesElement);
                                    }
                                } catch (ClassNotFoundException cnfe) {
                                    String errorMessage = "Caught an exception trying to find class '" + potentialClassName + "'";
                                    LOG.error(errorMessage, cnfe);
                                    throw new RuntimeException(errorMessage, cnfe);
                                } catch (InstantiationException ie) {
                                    String errorMessage = "Caught an exception trying to instantiate class '" + potentialClassName + "'";
                                    LOG.error(errorMessage, ie);
                                    throw new RuntimeException(errorMessage, ie);
                                } catch (IllegalAccessException iae) {
                                    String errorMessage = "Caught an access exception trying to instantiate class '" + potentialClassName + "'";
                                    LOG.error(errorMessage, iae);
                                    throw new RuntimeException(errorMessage, iae);
                                }
                            } else {
                                valuesElementsToAdd.add(displayTagChildNode.cloneNode(true));
                            }
                            displayTag.removeChild(displayTagChildNode);
                        }
                    }
                }
                for (Iterator iter = valuesElementsToAdd.iterator(); iter.hasNext();) {
                    Element valuesElementToAdd = (Element) iter.next();
                    displayTag.appendChild(valuesElementToAdd);
                }
            }
            if ((xpathExpressionElements != null) && (xpathExpressionElements.length > 0)) {
                NodeList fieldEvaluationElements = theTag.getElementsByTagName("fieldEvaluation");
                if (fieldEvaluationElements.getLength() == 1) {
                    Element fieldEvaluationTag = (Element) fieldEvaluationElements.item(0);
                    List tagsToAdd = new ArrayList();
                    for (int w = 0; w < fieldEvaluationTag.getChildNodes().getLength(); w++) {
                        Node fieldEvaluationChildNode = (Node) fieldEvaluationTag.getChildNodes().item(w);
                        Element newTagToAdd = null;
                        if ((fieldEvaluationChildNode != null) && ("xpathexpression".equals(fieldEvaluationChildNode.getNodeName()))) {
                            newTagToAdd = root.getOwnerDocument().createElement("xpathexpression");
                            newTagToAdd.appendChild(root.getOwnerDocument().createTextNode(generateNewXpathExpression(fieldEvaluationChildNode.getFirstChild().getNodeValue(), xpathExpressionElements)));
                            tagsToAdd.add(newTagToAdd);
                            fieldEvaluationTag.removeChild(fieldEvaluationChildNode);
                        }
                    }
                    for (Iterator iter = tagsToAdd.iterator(); iter.hasNext();) {
                        Element elementToAdd = (Element) iter.next();
                        fieldEvaluationTag.appendChild(elementToAdd);
                    }
                }
            }
            theTag.setAttribute("title", getBusinessObjectTitle(theTag));

        }
        if (LOG.isDebugEnabled()) {
            LOG.debug(XmlJotter.jotNode(root));
            StringWriter xmlBuffer = new StringWriter();
            try {

                root.normalize();
                Source source = new DOMSource(root);
                Result result = new StreamResult(xmlBuffer);
                TransformerFactory.newInstance().newTransformer().transform(source, result);
            } catch (Exception e) {
                LOG.debug(" Exception when printing debug XML output " + e);
            }
            LOG.debug(xmlBuffer.getBuffer());
        }

        return root;
    }

    private String generateNewXpathExpression(String currentXpathExpression, String[] newXpathExpressionElements) {
        StringBuffer returnableString = new StringBuffer();
        for (int i = 0; i < newXpathExpressionElements.length; i++) {
            String newXpathElement = newXpathExpressionElements[i];
            returnableString.append(newXpathElement);

            /*
             * Append the given xpath expression onto the end of the stringbuffer only in the following cases - if there is only one
             * element in the string array - if there is more than one element in the string array and if the current element is not
             * the last element
             */
            if (((i + 1) != newXpathExpressionElements.length) || (newXpathExpressionElements.length == 1)) {
                returnableString.append(currentXpathExpression);
            }
        }
        return returnableString.toString();
    }

    /**
     * This method gets all of the text from the xpathexpression element.
     *
     * @param root
     * @return
     */
    private String getXPathText(Element root) {
        try {
            String textContent = null;
            Node node = (Node) xpath.evaluate(".//xpathexpression", root, XPathConstants.NODE);
            if (node != null) {
                textContent = node.getTextContent();
            }
            return textContent;
        } catch (XPathExpressionException e) {
            LOG.error("No XPath expression text found in element xpathexpression of configXML for document. " + e);
            return null;
            // throw e; Just writing labels or doing routing report.
        }
    }

    /**
     * This method uses an XPath expression to determine if the content of the xmlDocumentContent is empty
     *
     * @param root
     * @return
     */
    private boolean xmlDocumentContentExists(Element root) {
        try {
            if (((NodeList) xpath.evaluate("//xmlDocumentContent", root, XPathConstants.NODESET)).getLength() == 0) {
                return false;
            }
        } catch (XPathExpressionException e) {
            LOG.error("Error parsing xmlDocumentConfig.  " + e);
            return false;
        }
        return true;
    }

    public static String getPotentialKualiClassName(String testString, String prefixIndicator, String suffixIndicator) {
        if ((StringUtils.isNotBlank(testString)) && (testString.startsWith(prefixIndicator)) && (testString.endsWith(suffixIndicator))) {
            return testString.substring(prefixIndicator.length(), testString.lastIndexOf(suffixIndicator));
        }
        return null;
    }

    /**
     * Method to look up the title of each fieldDef tag in the RuleAttribute xml. This method checks the following items in the
     * following order:
     *

     *
Check for the business object name from {@link #getBusinessObjectName(Element)}. If it is not found or blank and the
     * 'title' attribute of the fieldDef tag is specified then return the value of the 'title' attribute.
     *
Check for the business object name from {@link #getBusinessObjectName(Element)}. If it is found try getting the data
     * dictionary label related to the business object name and the attribute name (found in the xpath expression)
     *
Check for the data dictionary title value using the attribute name (found in the xpath expression) and the KFS stand in
     * business object for attributes (see {@link KFSConstants#STAND_IN_BUSINESS_OBJECT_FOR_ATTRIBUTES}
     *
Check for the data dictionary title value using the xpath attribute name found in the xpath expression section. Use that
     * attribute name to get the label out of the KFS stand in business object for attributes (see
     * {@link KFSConstants#STAND_IN_BUSINESS_OBJECT_FOR_ATTRIBUTES}
     *
Check for the data dictionary title value using the xpath attribute name found in the xpath expression in the
     * wf:ruledata() section. Use that attribute name to get the label out of the KFS stand in business object for attributes (see
     * {@link KFSConstants#STAND_IN_BUSINESS_OBJECT_FOR_ATTRIBUTES}
     *

     *
     * @param root - the element of the fieldDef tag
     */
    private String getBusinessObjectTitle(Element root) {
        String businessObjectName = null;
        String businessObjectText = root.getAttribute("title");
        String potentialClassNameLongLabel = getPotentialKualiClassName(businessObjectText, ATTRIBUTE_LABEL_BO_REFERENCE_PREFIX, ATTRIBUTE_LABEL_BO_REFERENCE_SUFFIX);
        String potentialClassNameShortLabel = getPotentialKualiClassName(businessObjectText, ATTRIBUTE_SHORT_LABEL_BO_REFERENCE_PREFIX, ATTRIBUTE_SHORT_LABEL_BO_REFERENCE_SUFFIX);
        // we assume they want the long label... but allow for the short label
        boolean requestedShortLabel = false;

        if (StringUtils.isNotBlank(potentialClassNameLongLabel)) {
            businessObjectName = potentialClassNameLongLabel;
        } else if (StringUtils.isNotBlank(potentialClassNameShortLabel)) {
            businessObjectName = potentialClassNameShortLabel;
            requestedShortLabel = true;
        }
        if (StringUtils.isNotBlank(businessObjectName)) {
            DataDictionaryService DDService = KRADServiceLocatorWeb.getDataDictionaryService();

            String title = null;
            String targetVal = lastXPath; // Assume the attribute is the last term in the XPath expression

            if (LOG.isErrorEnabled()) {
                LOG.debug("Finding title in BO=" + businessObjectName + " ObjectName=" + targetVal);
            }

            if (StringUtils.isNotBlank(targetVal)) {
                // try to get the label based on the bo name and xpath attribute
                if (requestedShortLabel) {
                    title = DDService.getAttributeShortLabel(businessObjectName, targetVal);
                } else {
                    title = DDService.getAttributeLabel(businessObjectName, targetVal);
                }
                if (StringUtils.isNotBlank(title)) {
                    return title;
                }
            }
            // try to get the label based on the business object and xpath ruledata section
            targetVal = getRuleData(root);
            if (LOG.isErrorEnabled()) {
                LOG.debug("Finding title in BO=" + businessObjectName + " ObjectName=" + targetVal);
            }
            if (StringUtils.isNotBlank(targetVal)) {
                title = DDService.getAttributeLabel(businessObjectName, targetVal);
                if (StringUtils.isNotBlank(title)) {
                    return title;
                }
            }
            // If haven't found a label yet, its probably because there is no xpath. Use the name attribute to determine the BO
            // attribute to use.
            targetVal = root.getAttribute("name");
            if (LOG.isErrorEnabled()) {
                LOG.debug("Finding title in BO=" + businessObjectName + " ObjectName=" + targetVal);
            }
            title = DDService.getAttributeLabel(businessObjectName, targetVal);

            if (StringUtils.isNotBlank(title)) {
                return title;
            }
        }
        // return any potentially hard coded title info
        else if ((StringUtils.isNotBlank(businessObjectText)) && (StringUtils.isBlank(businessObjectName))) {
            return businessObjectText;
        }
        return notFound;

    }

    /**
     * This method gets the contents of the ruledata function in the xpath statement in the XML
     *
     * @param root
     * @return
     */
    private String getRuleData(Element root) {
        String xPathRuleTarget = getXPathText(root);

        // This pattern may need to change to get the last stanza of the xpath
        if (StringUtils.isNotBlank(xPathRuleTarget)) {
            Matcher ruleTarget = targetPattern.matcher(xPathRuleTarget);
            if (ruleTarget.find()) {
                xPathRuleTarget = ruleTarget.group(1);
            }
        }
        return xPathRuleTarget;
    }

    private List<String> getXPathTerms(Element myTag) {

        Matcher xPathTarget;
        String firstMatch;
        List<String> xPathTerms = new ArrayList();
        String allText = getXPathText(myTag);// grab the whole xpath expression
        if (StringUtils.isNotBlank(allText)) {
            xPathTarget = xPathPattern.matcher(allText);
            Matcher termTarget;
            Matcher cleanTarget;
            int theEnd = 0;// Have to define this or the / gets used up with the match and every other term is returned.

            xPathTarget.find(theEnd);
            theEnd = xPathTarget.end() - 1;
            firstMatch = xPathTarget.group();

            termTarget = termPattern.matcher(firstMatch);
            int theEnd2 = 0;
            while (termTarget.find(theEnd2)) { // get each term, clean them up, and add to the list.
                theEnd2 = termTarget.end() - 1;
                cleanTarget = cleanPattern.matcher(termTarget.group());
                cleanTarget.find();
                lastXPath = cleanTarget.group();
                xPathTerms.add(lastXPath);

            }
        }
        return xPathTerms;
    }

    private String getLastXPath(Element root) {
        List<String> tempList = getXPathTerms(root);
        return tempList.get(tempList.size());
    }
}


text:
<!--
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.apache.sling</groupId>
        <artifactId>sling</artifactId>
        <version>26</version>
        <relativePath/>
    </parent>

    <artifactId>org.apache.sling.installer.factory.subsystems-base</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>bundle</packaging>

    <name>Apache Sling Subsystems Base Installer</name>
    <description>
        Provides support for subsystems-base files to the Apache Sling OSGi installer
    </description>

    <properties>
        <sling.java.version>7</sling.java.version>
    </properties>

    <scm>
        <connection>scm:svn:http://svn.apache.org/repos/asf/sling/trunk/installer/factories/subsystems-base</connection>
        <developerConnection> scm:svn:https://svn.apache.org/repos/asf/sling/trunk/installer/factories/subsystems-base</developerConnection>
        <url>http://svn.apache.org/viewvc/sling/trunk/installer/factories/subsystems-base/</url>
    </scm>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-Activator>
                            org.apache.sling.installer.factories.subsystems.base.impl.Activator
                        </Bundle-Activator>
                        <Private-Package>
                            org.apache.sling.installer.factories.subsystems.base.impl.*
                        </Private-Package>
                    </instructions>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.rat</groupId>
                <artifactId>apache-rat-plugin</artifactId>
                <configuration>
                   <excludes>
                        <exclude>src/test/resources/*-base</exclude>
                   </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.core</artifactId>
            <version>5.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.compendium</artifactId>
            <version>5.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.sling</groupId>
            <artifactId>org.apache.sling.installer.api</artifactId>
            <version>1.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.sling</groupId>
            <artifactId>org.apache.sling.settings</artifactId>
            <version>1.3.6</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

redpajama_set_name: RedPajamaGithub


text:
package org.xbmc.kore.jsonrpc;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.xbmc.kore.jsonrpc.notification.Player;

/**
 * Abstract class, based of all the JSON RPC notifications
 *
 * Each specific notification should be a subclass of this.
 */
public abstract class ApiNotification {
    protected static final String METHOD_NODE = "method";
    protected static final String PARAMS_NODE = "params";

    public final String sender;

    /**
     * Constructor from a notification node (starting on "params" node)
     * @param node node
     */
    public ApiNotification(ObjectNode node) {
        sender = node.get("sender").textValue();
    }

    /**
     * Returns this notification name
     */
    public abstract String getNotificationName();

    /**
     * Returns a specific notification present in the Json Node
     *
     * @param node Json node with notification
     * @return Specific notification object
     */
    public static ApiNotification notificationFromJsonNode(JsonNode node) {
        String method = node.get(METHOD_NODE).asText();
        ObjectNode params = (ObjectNode)node.get(PARAMS_NODE);

        ApiNotification result = null;
        switch (method) {
        case Player.OnPause.NOTIFICATION_NAME:
            result = new Player.OnPause(params);
            break;
        case Player.OnPlay.NOTIFICATION_NAME:
            result = new Player.OnPlay(params);
            break;
        case Player.OnResume.NOTIFICATION_NAME:
            result = new Player.OnResume(params);
            break;
        case Player.OnSeek.NOTIFICATION_NAME:
            result = new Player.OnSeek(params);
            break;
        case Player.OnSpeedChanged.NOTIFICATION_NAME:
            result = new Player.OnSpeedChanged(params);
            break;
        case Player.OnStop.NOTIFICATION_NAME:
            result = new Player.OnStop(params);
            break;
        }

        return result;
    }
}


text:
package BehaviorSubject

import (
	"time"

	_ "github.com/reactivego/rx"
)

func Example_behaviorSubject() {
	subject := NewBehaviorSubjectString("a")
	subject.Timeout(1 * time.Millisecond).Println()
	// Output:
	// a
}

func Example_behaviorSubject2() {
	subject := NewBehaviorSubjectString("a")
	subject.Next("b")
	subject.Timeout(1 * time.Millisecond).Println()
	// Output:
	// b
}

func Example_behaviorSubject3() {
	concurrent := GoroutineScheduler()
	subject := NewBehaviorSubjectString("a")
	subject.Next("b")
	subject.Next("c")
	subject.Next("d")
	subject.Next("c")
	subject.Next("a")
	subject.Next("c")
	subject.Next("d")
	subject.Next("b")
	subject.Timeout(1 * time.Millisecond).SubscribeOn(concurrent).Subscribe(PrintlnString())
	subject.Next("c")
	subject.Next("d")
	concurrent.Wait()
	// Output:
	// b
	// c
	// d
}

func Example_behaviorSubjectCompleted() {
	const ms = time.Millisecond
	subject := NewBehaviorSubjectString("a")
	subject.Next("b")
	subject.Next("c")
	subject.Complete()
	subject.Println()
	// Output:
}


text:
<?php

declare(strict_types=1);

namespace tests\Phpml\Classification;

use Phpml\Classification\MLPClassifier;
use Phpml\NeuralNetwork\Node\Neuron;
use Phpml\ModelManager;
use PHPUnit\Framework\TestCase;

class MLPClassifierTest extends TestCase
{
    public function testMLPClassifierLayersInitialization()
    {
        $mlp = new MLPClassifier(2, [2], [0, 1]);

        $this->assertCount(3, $mlp->getLayers());

        $layers = $mlp->getLayers();

        // input layer
        $this->assertCount(3, $layers[0]->getNodes());
        $this->assertNotContainsOnly(Neuron::class, $layers[0]->getNodes());

        // hidden layer
        $this->assertCount(3, $layers[1]->getNodes());
        $this->assertNotContainsOnly(Neuron::class, $layers[1]->getNodes());

        // output layer
        $this->assertCount(2, $layers[2]->getNodes());
        $this->assertContainsOnly(Neuron::class, $layers[2]->getNodes());
    }

    public function testSynapsesGeneration()
    {
        $mlp = new MLPClassifier(2, [2], [0, 1]);
        $layers = $mlp->getLayers();

        foreach ($layers[1]->getNodes() as $node) {
            if ($node instanceof Neuron) {
                $synapses = $node->getSynapses();
                $this->assertCount(3, $synapses);

                $synapsesNodes = $this->getSynapsesNodes($synapses);
                foreach ($layers[0]->getNodes() as $prevNode) {
                    $this->assertContains($prevNode, $synapsesNodes);
                }
            }
        }
    }

    public function testBackpropagationLearning()
    {
        // Single layer 2 classes.
        $network = new MLPClassifier(2, [2], ['a', 'b']);
        $network->train(
            [[1, 0], [0, 1], [1, 1], [0, 0]],
            ['a', 'b', 'a', 'b']
        );

        $this->assertEquals('a', $network->predict([1, 0]));
        $this->assertEquals('b', $network->predict([0, 1]));
        $this->assertEquals('a', $network->predict([1, 1]));
        $this->assertEquals('b', $network->predict([0, 0]));
    }

    public function testBackpropagationTrainingReset()
    {
        // Single layer 2 classes.
        $network = new MLPClassifier(2, [2], ['a', 'b'], 1000);
        $network->train(
            [[1, 0], [0, 1]],
            ['a', 'b']
        );

        $this->assertEquals('a', $network->predict([1, 0]));
        $this->assertEquals('b', $network->predict([0, 1]));

        $network->train(
            [[1, 0], [0, 1]],
            ['b', 'a']
        );

        $this->assertEquals('b', $network->predict([1, 0]));
        $this->assertEquals('a', $network->predict([0, 1]));
    }

    public function testBackpropagationPartialTraining()
    {
        // Single layer 2 classes.
        $network = new MLPClassifier(2, [2], ['a', 'b'], 1000);
        $network->partialTrain(
            [[1, 0], [0, 1]],
            ['a', 'b']
        );

        $this->assertEquals('a', $network->predict([1, 0]));
        $this->assertEquals('b', $network->predict([0, 1]));

        $network->partialTrain(
            [[1, 1], [0, 0]],
            ['a', 'b']
        );

        $this->assertEquals('a', $network->predict([1, 0]));
        $this->assertEquals('b', $network->predict([0, 1]));
        $this->assertEquals('a', $network->predict([1, 1]));
        $this->assertEquals('b', $network->predict([0, 0]));
    }

    public function testBackpropagationLearningMultilayer()
    {
        // Multi-layer 2 classes.
        $network = new MLPClassifier(5, [3, 2], ['a', 'b']);
        $network->train(
            [[1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]],
            ['a', 'b', 'a', 'b']
        );

        $this->assertEquals('a', $network->predict([1, 0, 0, 0, 0]));
        $this->assertEquals('b', $network->predict([0, 1, 1, 0, 0]));
        $this->assertEquals('a', $network->predict([1, 1, 1, 1, 1]));
        $this->assertEquals('b', $network->predict([0, 0, 0, 0, 0]));
    }

    public function testBackpropagationLearningMulticlass()
    {
        // Multi-layer more than 2 classes.
        $network = new MLPClassifier(5, [3, 2], ['a', 'b', 4]);
        $network->train(
            [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]],
            ['a', 'b', 'a', 'a', 4]
        );

        $this->assertEquals('a', $network->predict([1, 0, 0, 0, 0]));
        $this->assertEquals('b', $network->predict([0, 1, 0, 0, 0]));
        $this->assertEquals('a', $network->predict([0, 0, 1, 1, 0]));
        $this->assertEquals('a', $network->predict([1, 1, 1, 1, 1]));
        $this->assertEquals(4, $network->predict([0, 0, 0, 0, 0]));
    }

    public function testSaveAndRestore()
    {
        // Instantinate new Percetron trained for OR problem
        $samples = [[0, 0], [1, 0], [0, 1], [1, 1]];
        $targets = [0, 1, 1, 1];
        $classifier = new MLPClassifier(2, [2], [0, 1]);
        $classifier->train($samples, $targets);
        $testSamples = [[0, 0], [1, 0], [0, 1], [1, 1]];
        $predicted = $classifier->predict($testSamples);

        $filename = 'perceptron-test-'.rand(100, 999).'-'.uniqid();
        $filepath = tempnam(sys_get_temp_dir(), $filename);
        $modelManager = new ModelManager();
        $modelManager->saveToFile($classifier, $filepath);

        $restoredClassifier = $modelManager->restoreFromFile($filepath);
        $this->assertEquals($classifier, $restoredClassifier);
        $this->assertEquals($predicted, $restoredClassifier->predict($testSamples));
    }

    /**
     * @expectedException \Phpml\Exception\InvalidArgumentException
     */
    public function testThrowExceptionOnInvalidLayersNumber()
    {
        new MLPClassifier(2, [], [0, 1]);
    }

    /**
     * @expectedException \Phpml\Exception\InvalidArgumentException
     */
    public function testThrowExceptionOnInvalidPartialTrainingClasses()
    {
        $classifier = new MLPClassifier(2, [2], [0, 1]);
        $classifier->partialTrain(
            [[0, 1], [1, 0]],
            [0, 2],
            [0, 1, 2]
        );
    }
    /**
     * @expectedException \Phpml\Exception\InvalidArgumentException
     */
    public function testThrowExceptionOnInvalidClassesNumber()
    {
        new MLPClassifier(2, [2], [0]);
    }

    /**
     * @param array $synapses
     *
     * @return array
     */
    private function getSynapsesNodes(array $synapses): array
    {
        $nodes = [];
        foreach ($synapses as $synapse) {
            $nodes[] = $synapse->getNode();
        }

        return $nodes;
    }
}


text:
/**
 * External dependencies
 */
import { __, _x } from '@googleforcreators/i18n';

/**
 * Internal dependencies
 */
import type { MetaData } from '../../types';

export default {
  slug: 'laptop-buying-guide',
  creationDate: '2021-07-29T00:00:00.000Z',
  title: _x('Laptop Buying Guide', 'template name', 'web-stories'),
  tags: [
    _x('Technology', 'template keyword', 'web-stories'),
    _x('Products', 'template keyword', 'web-stories'),
    _x('Laptop', 'template keyword', 'web-stories'),
    _x('Simple', 'template keyword', 'web-stories'),
    _x('Blue', 'template keyword', 'web-stories'),
  ],
  colors: [
    {
      label: _x('Brilliant Blue', 'color', 'web-stories'),
      color: '#0057ff',
      family: _x('Blue', 'color', 'web-stories'),
    },
    {
      label: _x('White', 'color', 'web-stories'),
      color: '#fff',
      family: _x('White', 'color', 'web-stories'),
    },
    {
      label: _x('Gentle Gray', 'color', 'web-stories'),
      color: '#c4c4c4',
      family: _x('Gray', 'color', 'web-stories'),
    },
    {
      label: _x('Mineshaft Black', 'color', 'web-stories'),
      color: '#3d3d3d',
      family: _x('Black', 'color', 'web-stories'),
    },
  ],
  description: __(
    'This template's clean design and structure will let you create uncomplicated long-form product reviews, comparisons and more. Adapt it to your style by changing the colors.',
    'web-stories'
  ),
  vertical: _x('Technology', 'template vertical', 'web-stories'),
} as MetaData;


text:
from setuptools import setup
import os

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()

version = "1.0b3"

setup(
    version=version,
    description="A plugin for ploy providing support for OpenVZ containers.",
    long_description=README + "\n\n",
    name="ploy_openvz",
    author='Florian Schulze',
    author_email='florian.schulze@gmx.net',
    license="BSD 3-Clause License",
    url='http://github.com/ployground/ploy_openvz',
    classifiers=[
        'Environment :: Console',
        'Intended Audience :: System Administrators',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: System :: Installation/Setup',
        'Topic :: System :: Systems Administration'],
    include_package_data=True,
    zip_safe=False,
    packages=['ploy_openvz'],
    install_requires=[
        'setuptools',
        'ploy >= 1.0.0, < 2dev',
        'lazy'],
    entry_points="""
        [ploy.plugins]
        vz = ploy_openvz:plugin
    """)


text:
package properties;

import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import filter.Inhaltsstoff;

/**
 * Project: LIV - Lebensmittelinhaltsstoffverifizierer
 *
 * class Liv Einstellungen stellt alle Methoden zur properties Datei zur Verfügung
 *
 * @author team equal-IT
 * @mail: team@equal-it.de
 * @version 1.0 2016/07/08
 */

public class Einstellungen {

	private static final String EINSTELLUNGEN = "einstellungen.properties";
	private static final String AKTUELLER_FILTER = "aktueller_Filter";

	public Properties properties = null;
	public String dateipfad = EINSTELLUNGEN;

	public void schreibeAktuellenFilter(Set<Inhaltsstoff> inhaltsstoffe) {
		Set<String> anzeigenamen = new HashSet<>();
		for (Inhaltsstoff inhaltsstoff : inhaltsstoffe) {
			anzeigenamen.add(inhaltsstoff.anzeigename());
		}
		String filterwert = String.join(",", anzeigenamen);
		schreibeEinstellung(AKTUELLER_FILTER, filterwert);
	}

	public Set<Inhaltsstoff> leseAktuellenFilter() {
		Set<Inhaltsstoff> aktuellerFilter = new HashSet<>();
		String filterAlsText = leseEinstellung(AKTUELLER_FILTER);
		if (filterAlsText != null && !filterAlsText.isEmpty()) {
			String[] anzeigenamen = filterAlsText.split(",");
			for (String name : anzeigenamen) {
				aktuellerFilter.add(Inhaltsstoff
						.inhaltstoffFuerAnzeigenamen(name));
			}
		}
		return aktuellerFilter;
	}

	String leseEinstellung(final String einstellung) {
		if (properties == null) {
			ladePropertiesDatei();
		}
		return this.properties.getProperty(einstellung);
	}

	void schreibeEinstellung(final String einstellung, final String wert) {
		if (properties == null) {
			ladePropertiesDatei();
		}
		this.properties.put(einstellung, wert);
		schreibePropertiesDatei();
	}

	private void ladePropertiesDatei() {
		Properties properties = new Properties();
		try (FileInputStream inStream = new FileInputStream(dateipfad)) {
			properties.load(inStream);
		} catch (IOException e) {
			//System.err.println("Fehler beim Laden der Datei: " + EINSTELLUNGEN);
		}
		this.properties = properties;
	}

	public void schreibePropertiesDatei() {
		String comment = "Properties aktualisiert am:";
		try (FileOutputStream out = new FileOutputStream(dateipfad)) {
			this.properties.store(out, comment);
		} catch (IOException e) {
			System.err.println("Fehler beim Schreiben der Datei: " + dateipfad);
		}
	}

/*	public static void main(String[] args) {
		// Test
		Einstellungen einstellungen = new Einstellungen();
		einstellungen.dateipfad = "test.properties"; // nur fuer Test umstellen

		einstellungen.ladePropertiesDatei();
		System.out.println(einstellungen.dateipfad + " gefunden.");

		einstellungen.schreibeEinstellung("test", "erfolgreich");
		einstellungen.schreibePropertiesDatei();
		System.out.println(einstellungen.dateipfad + " geschrieben.");

		// aktuellen Filter schreiben
		Set<Inhaltsstoff> inhaltsstoffe = new HashSet<>();
		inhaltsstoffe.add(Inhaltsstoff.NUSS);
		inhaltsstoffe.add(Inhaltsstoff.UNBEKANNT);
		einstellungen.schreibeAktuellenFilter(inhaltsstoffe);

		// aktuellen Filter lesen
		Set<Inhaltsstoff> aktuellerFilter = einstellungen.leseAktuellenFilter();
		aktuellerFilter.contains(Inhaltsstoff.UNBEKANNT);
		aktuellerFilter.contains(Inhaltsstoff.NUSS);

		// aufraeumen
		einstellungen.properties.clear();
		einstellungen.schreibePropertiesDatei();
	}*/
}


text:
'use strict';

rockBandsApp.controller('HomeController',
    function HomeController($scope, $resource, rockBandsData) {
        var NUMBER_OF_ITEMS_TO_TAKE = 3,
            BANDS_FACTORY_NAME = 'bands',
            ALBUMS_FACTORY_NAME = 'albums',
            SONGS_FACTORY_NAME = 'songs';

        getCoverOfItems(BANDS_FACTORY_NAME);
        getCoverOfItems(ALBUMS_FACTORY_NAME);
        getCoverOfItems(SONGS_FACTORY_NAME);

        function getCoverOfItems(factoryName) {
            rockBandsData.getCoverOfItems(factoryName, NUMBER_OF_ITEMS_TO_TAKE)
                .then(function (data) {
                    $scope[factoryName] = data;
                });
        }
    }
);


text:
number=1.times.map{ 1000 +  Random.rand(11) }

template "/opt/novell/idm/Designer//NOVLRSERVB.properties" do
  source "NOVLRSERVB.properties.erb"
  owner "root"
  mode "0644"
end
execute "Create Roles and Resources Driver" do
 user "root"
 command "/bin/sh -c 'ulimit -n 4096; LD_LIBRARY_PATH=/opt/novell/idm/Designer/plugins/com.novell.core.iconeditor_4.0.0.201206110753/os/linux:/opt/novell/idm/Designer/plugins/com.novell.core.jars_4.0.0.201206110753/os/linux/x86:/opt/novell/idm/Designer/plugins/com.novell.core.jars_4.0.0.201206110753/os/linux/gcc3:$LD_LIBRARY_PATH \"/opt/novell/idm/Designer//Designer\" -nosplash -nl en -application com.novell.idm.rcp.DesignerHeadless -command deployDriver -p \"/opt/novell/idm/Designer//packages/eclipse/plugins\":\"/tmp/plugins\" -a \"admin.servers.system\" -w novell123$ -s 127.0.0.1:524 -c \"driverset1.system\" -b NOVLRSERVB -l \"/var/opt/novell/idm/roles_driver.log\" -u IDM4_15_RandR#{number}'"
  action :run
end


text:
'''
Copyright 2011 SRI International

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Created on May 9, 2011

@author: jklo
'''
from gnupg import GPG
from ..sign.Sign import *
from ..errors import *
import types, re, copy, os, sys
import cStringIO

from abc import ABCMeta

class VerifyBase(SignBase):
    __metaclass__ = ABCMeta
    '''
    Base class for verifying signatures
    '''

    def __init__(self, gpgbin="/usr/local/bin/gpg", gnupgHome=os.path.expanduser(os.path.join("~", ".gnupg"))):
        '''
        Constructor
        '''
        self.gnupgHome = gnupgHome
        self.gpgbin = gpgbin
        SignBase.__init__(self, privateKeyID=None, passphrase=None, gnupgHome=self.gnupgHome, gpgbin=self.gpgbin, publicKeyLocations=[])

    def _getSignatureInfo(self, envelope={}):
            sigInfo = None

            if envelope.has_key("digital_signature"):
                sigInfo = envelope["digital_signature"]
                if sigInfo.has_key("signing_method"):
                    if sigInfo["signing_method"] == self.signatureMethod:
                        if not sigInfo.has_key("signature") or sigInfo["signature"] == None or len(sigInfo["signature"]) == 0:
                            raise BadSignatureFormat(MISSING_SIGNATURE)
                        elif not (sigInfo.has_key("key_location") and isinstance(sigInfo["key_location"], types.ListType) and len(sigInfo["key_location"]) > 0 ):
                            raise BadSignatureFormat(MISSING_KEY_LOCATION)
                        elif sigInfo.has_key("key_owner") and not isinstance(sigInfo["key_owner"], types.StringTypes):
                            raise BadSignatureFormat(BAD_KEY_OWNER)
                    else:
                        raise UnsupportedSignatureAlgorithm(sigInfo["signing_method"])
                else:
                    raise UnsupportedSignatureAlgorithm(None)

            return sigInfo

    def _extractHashFromSignature(self, signatureBlock=""):

        def removeHead(mesg=[]):
            status = 0
            mcopy = copy.deepcopy(mesg)
            for line in mesg:
                if re.match("^-----BEGIN PGP (SIGNED ){0,1}MESSAGE-----$", line) != None:
                    status = 1
                elif (status == 1 or status == 2) and re.match("^[^:]+: .+$", line) != None:
                    status = 2
                elif (status == 1 or status == 2) and line == "":
                    status = 3

                mcopy.pop(0)

                if status == 3:
                    break

            return mcopy

        def removeTail(mesg=[]):
            msgOnly = ""
            for line in mesg:
                if re.match("^-----BEGIN PGP SIGNATURE-----$", line):
                    break
                msgOnly += line
            return msgOnly

        if sys.version_info > (2, 7):
            sig = re.split("\r\n|\r|\n", signatureBlock, flags=re.MULTILINE)
        else:
            sig = re.split("\r\n|\r|\n", signatureBlock)

        hash = removeTail(removeHead(sig))

        return hash

    def get_and_verify(self, envelope):
        '''
        Get the OpenPGP validation info and Verify integrity of the provided envelope.

        Returns:
            None if no signature block exists
            gnupg.Verify object if signature & integrity check pass
        Raises:
            BadSignatureFormat if signature & integrity check do not pass
            MissingPublicKey if public key for signed document is missing
        '''

        sigInfo = self._getSignatureInfo(envelope)

        if sigInfo != None:

            verified = self.gpg.verify(sigInfo["signature"])
            if verified.valid == True:
                verifiedHash = self._extractHashFromSignature(sigInfo["signature"])

                if self.get_message(envelope) == verifiedHash:
                    return verified
                else:
                    raise BadSignatureFormat("valid signature, envelope hash bad match.")
            elif verified.valid == False and verified.status == 'no public key':
                raise MissingPublicKey(message=verified.data, keyid=verified.key_id)
            else:
                raise BadSignatureFormat("invalid signature")
        return None

    def verify(self, envelope):
        '''
        Verify integrity of the provided envelope.

        Returns:
            None if no signature block exists
            True if signature & integrity check pass
            False if signature & integrity check do not pass

        Raises:
            MissingPublicKey if public key for signed document is missing
        '''

        sigInfo = self._getSignatureInfo(envelope)

        if sigInfo != None:

            verified = self.gpg.verify(sigInfo["signature"])
            if verified.valid == True:
                verifiedHash = self._extractHashFromSignature(sigInfo["signature"])

                if self.get_message(envelope) == verifiedHash:
                    return True
                else:
                    return False
            elif verified.valid == False and verified.status == 'no public key':
                raise MissingPublicKey(message=verified.data, keyid=verified.key_id)
            else:
                return False
        return None

class Verify_0_21(Sign_0_21, VerifyBase):
    pass

class Verify_0_23(Sign_0_23, VerifyBase):
    pass

class Verify_0_49(Sign_0_49, VerifyBase):
    pass

class Verify_0_51(Sign_0_51, VerifyBase):
    pass

if __name__ == "__main__":
    verify = Verify_0_21()
    pass


text:
package bid.adonis.lau.dubbo;

import bid.adonis.lau.domain.City;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;

/**
 * 城市 Dubbo 服务消费者
 *
 * @author: adonis lau
 * @email: adonis.lau.dev@gmail.com
 * @date: Created in 2018/1/17 22:54
 */
@Component
public class CityDubboConsumerService {

    @Reference(version = "1.0.0")
    CityDubboService cityDubboService;

    /**
     * 输出查询到的城市
     */
    public void printCity() {
        String cityName = "温岭";
        City city = cityDubboService.findCityByName(cityName);
        System.out.println(city.toString());
    }
}


text:
from django.test import TestCase

from .models import Schedule, OneSchedule
from . import solid_data as sd

class ScheduleTests(TestCase):
    """
    Test for method of Schedule model.
    """
    def test_get_month_calendar(self):
        """Test for method get_month_calendar for Schedule object.
        Should return list with info about days of the week for
        every days in month """

        schedule = Schedule(month="czerwiec", year='2016')
        expected_month_calendar_results = [
            (1, 'śr'), (2, 'cz'), (3, 'pt'), (4, 'so'), (5, 'n'),
            (6, 'pn'), (7, 'wt'), (8, 'śr'), (9, 'cz'), (10, 'pt'),
            (11, 'so'), (12, 'n'), (13, 'pn'), (14, 'wt'), (15, 'śr'),
            (16, 'cz'), (17, 'pt'), (18, 'so'), (19, 'n'), (20, 'pn'),
            (21, 'wt'), (22, 'śr'), (23, 'cz'), (24, 'pt'), (25, 'so'),
            (26, 'n'), (27, 'pn'), (28, 'wt'), (29, 'śr'), (30, 'cz')
        ]
        self.assertEqual(
            schedule.get_month_calendar(), expected_month_calendar_results
        )

def create_one_chedule(month_schedule):
    return OneSchedule(one_schedule=month_schedule)

class OneScheduleTests(TestCase):
    """
    Test for method of OneSchedule model.
    """

    def test_get_working_days_number_person(self):
        """Test for method get_working_days_number_person
        for OneSchedule object."""
        one_schedule = create_one_chedule('...DDD...NNN...DDD...NNN...DDD')
        self.assertEqual(one_schedule.get_working_days_number_person(), 15)

    def test_get_number_of_nights(self):
        """Test for method get_number_of_nights for OneSchedule object."""

        one_schedule = create_one_chedule('...DDD...NNN...DDD...NNN...DDD')
        self.assertEqual(one_schedule.get_number_of_nights(), 6)

    def test_get_number_of_days(self):
        """Test for method get_number_of_days for OneSchedule object."""

        one_schedule = create_one_chedule('...DDD...NNN...DDD...NNN...DDD')
        self.assertEqual(one_schedule.get_number_of_days(), 9)

    def test_wheather_day_is_free1(self):
        """Test for method wheather_day_is_free for OneSchedule object.
        - holiday"""
        one_schedule = create_one_chedule('UUUDDD...NNN...DDD...NNN...DDD')
        self.assertFalse(one_schedule.wheather_day_is_free(1))

    def test_wheather_day_is_free2(self):
        """Test for method wheather_day_is_free for OneSchedule object.
        - night"""
        one_schedule = create_one_chedule('UUUDDD...NNN...DDD...NNN...DDD')
        self.assertFalse(one_schedule.wheather_day_is_free(10))

    def test_wheather_day_is_free3(self):
        """Test for method wheather_day_is_free for OneSchedule object.
        - day"""
        one_schedule = create_one_chedule('UUUDDD...NNN...DDD...NNN...DDD')
        self.assertFalse(one_schedule.wheather_day_is_free(4))

    def test_wheather_day_is_free4(self):
        """Test for method wheather_day_is_free for OneSchedule object.
        - free day"""
        one_schedule = create_one_chedule('UUUDDD...NNN...DDD...NNN...DDD')
        self.assertTrue(one_schedule.wheather_day_is_free(7))

    def test_take_work1(self):
        """Test for method take_work for OneSchedule object - NIGHT"""
        one_schedule = create_one_chedule('...DDD...NNN...DDD...NNN...DDD')
        one_schedule.take_work(0, sd.NIGHT)
        self.assertEqual(
            one_schedule.one_schedule, 'N..DDD...NNN...DDD...NNN...DDD'
        )

    def test_take_work2(self):
        """Test for method take_work for OneSchedule object - DAY"""
        one_schedule = create_one_chedule('...DDD...NNN...DDD...NNN...DDD')
        one_schedule.take_work(7, sd.DAY)
        self.assertEqual(
            one_schedule.one_schedule, '...DDD.D.NNN...DDD...NNN...DDD'
        )

    def test_take_work3(self):
        """Test for method take_work for OneSchedule object - holiday"""
        one_schedule = create_one_chedule('...DDD...NNN...DDD...NNN...DDD')
        one_schedule.take_work(13, sd.HOLIDAY)
        self.assertEqual(
            one_schedule.one_schedule, '...DDD...NNN.U.DDD...NNN...DDD'
        )

    def test_filtre_work_days_in_month1(self):
        """Test for method filtre_work_days_in_month for OneSchedule object."""
        one_schedule = create_one_chedule('...DDD...NNN...DDD...NNN...DDD')
        self.assertFalse(one_schedule.filtre_work_days_in_month(14))

    def test_filtre_work_days_in_month2(self):
        """Test for method filtre_work_days_in_month for OneSchedule object."""
        one_schedule = create_one_chedule('...DDD...NNN...DDD...NNN...DDD')
        self.assertTrue(one_schedule.filtre_work_days_in_month(15))

    def test_filtre_double_work1(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('.D............................')
        self.assertFalse(one_schedule.filtre_double_work(0, 'N'))

    def test_filtre_double_work2(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('.D............................')
        self.assertTrue(one_schedule.filtre_double_work(0, 'D'))

    def test_filtre_double_work3(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('.N............................')
        self.assertTrue(one_schedule.filtre_double_work(0, 'N'))

    def test_filtre_double_work4(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('.N............................')
        self.assertTrue(one_schedule.filtre_double_work(0, 'D'))

    def test_filtre_double_work5(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('D.............................')
        self.assertTrue(one_schedule.filtre_double_work(1, 'N'))

    def test_filtre_double_work6(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('D.............................')
        self.assertTrue(one_schedule.filtre_double_work(1, 'D'))

    def test_filtre_double_work7(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('N.............................')
        self.assertTrue(one_schedule.filtre_double_work(1, 'N'))

    def test_filtre_double_work8(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('N.............................')
        self.assertFalse(one_schedule.filtre_double_work(1, 'D'))

    def test_filtre_double_work9(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('............D.................')
        self.assertTrue(one_schedule.filtre_double_work(11, 'D'))

    def test_filtre_double_work10(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('............D.................')
        self.assertFalse(one_schedule.filtre_double_work(11, 'N'))

    def test_filtre_double_work11(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('............N.................')
        self.assertFalse(one_schedule.filtre_double_work(13, 'D'))

    def test_filtre_double_work12(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('............N.................')
        self.assertTrue(one_schedule.filtre_double_work(13, 'N'))

    def test_filtre_double_work13(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('............................D.')
        self.assertTrue(one_schedule.filtre_double_work(29, 'D'))

    def test_filtre_double_work14(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('............................D.')
        self.assertTrue(one_schedule.filtre_double_work(29, 'N'))

    def test_filtre_double_work15(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('............................N.')
        self.assertFalse(one_schedule.filtre_double_work(29, 'D'))

    def test_filtre_double_work16(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('............................N.')
        self.assertTrue(one_schedule.filtre_double_work(29, 'N'))

    def test_filtre_double_work17(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('.............................D')
        self.assertTrue(one_schedule.filtre_double_work(28, 'D'))

    def test_filtre_double_work18(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('.............................D')
        self.assertFalse(one_schedule.filtre_double_work(28, 'N'))

    def test_filtre_double_work19(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('.............................N')
        self.assertTrue(one_schedule.filtre_double_work(28, 'D'))

    def test_filtre_double_work20(self):
        """Test for method filtre_double_work for OneSchedule object."""
        one_schedule = create_one_chedule('.............................N')
        self.assertTrue(one_schedule.filtre_double_work(28, 'N'))

    def test_filtre_work_days_in_week1(self):
        """Test for method filtre_work_days_in_week for OneSchedule object."""
        one_schedule = create_one_chedule('...DDD...NNN...DDD...NNN...DDD')
        self.assertTrue(one_schedule.filtre_work_days_in_week(4, 6))

    def test_filtre_work_days_in_week2(self):
        """Test for method filtre_work_days_in_week for OneSchedule object."""
        one_schedule = create_one_chedule('...DDD...NNN...DDD...NNN...DDD')
        self.assertTrue(one_schedule.filtre_work_days_in_week(4, 9))

    def test_filtre_work_days_in_week3(self):
        """Test for method filtre_work_days_in_week for OneSchedule object."""
        one_schedule = create_one_chedule('.N.DDD.D.NNN...DDD...NNN...DDD')
        self.assertFalse(one_schedule.filtre_work_days_in_week(4, 8))

    def test_filtre_work_days_in_week4(self):
        """Test for method filtre_work_days_in_week for OneSchedule object."""
        one_schedule = create_one_chedule('.N.DDD.D.NNN...DDD...NNN...DDD')
        self.assertFalse(one_schedule.filtre_work_days_in_week(4, 10))


text:
package com.microsoft.reef.examples.nggroup.bgd.parameters;

import javax.inject.Inject;

import com.microsoft.reef.examples.nggroup.bgd.loss.LogisticLossFunction;
import com.microsoft.reef.examples.nggroup.bgd.loss.LossFunction;
import com.microsoft.reef.examples.nggroup.bgd.loss.SquaredErrorLossFunction;
import com.microsoft.reef.examples.nggroup.bgd.loss.WeightedLogisticLossFunction;
import com.microsoft.tang.annotations.Parameter;

/**
 *
 */
public class BGDLossType {

  private final Class<? extends LossFunction> lossFunction;

  @Inject
  public BGDLossType(@Parameter(LossFunctionType.class) final String lossFunctionStr) {
    switch(lossFunctionStr) {
    case "logLoss":
      this.lossFunction = LogisticLossFunction.class;
      break;
    case "weightedLogLoss":
      this.lossFunction = WeightedLogisticLossFunction.class;
      break;
    case "squaredError":
      this.lossFunction = SquaredErrorLossFunction.class;
      break;
    default:
      throw new RuntimeException("Specified loss function type: " + lossFunctionStr
              + " is not yet implemented. Supported types are logLoss|weightedLogLoss|squaredError");
    }
  }

  /**
   * @return the lossFunction
   */
  public Class<? extends LossFunction> getLossFunction() {
    return lossFunction;
  }
}


text:
package com.ttaylorr.uhc.pvp.core;

import com.google.common.base.Function;
import com.ttaylorr.uhc.pvp.CommandListener;
import com.ttaylorr.uhc.pvp.PVPManagerPlugin;
import com.ttaylorr.uhc.pvp.core.gamemodes.AdminGameMode;
import com.ttaylorr.uhc.pvp.core.gamemodes.GameMode;
import com.ttaylorr.uhc.pvp.core.gamemodes.PVPGameMode;
import com.ttaylorr.uhc.pvp.core.gamemodes.SpectatorGameMode;
import com.ttaylorr.uhc.pvp.util.Checker;
import com.ttaylorr.uhc.pvp.util.Continuation;
import com.ttaylorr.uhc.pvp.util.Message;
import com.ttaylorr.uhc.pvp.util.PVPManagerCommand;
import net.milkbowl.vault.permission.Permission;
import nl.dykam.dev.reutil.data.ComponentHandle;
import nl.dykam.dev.reutil.data.ComponentManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.Arrays;

public class UserManager implements CommandListener {
    private final ComponentHandle<Player, UserData> dataHandle;
    private final Command[] commands;
    private PVPManagerPlugin plugin;
    private Function<Player, GameMode> defaultGameMode;
    private GameModeCollection gameModes;

    public UserManager(PVPManagerPlugin plugin, Function<Player, GameMode> defaultGameMode, GameMode... gameModes) {
        this.plugin = plugin;
        this.defaultGameMode = defaultGameMode;
        this.gameModes = new GameModeCollection(this, defaultGameMode);
        this.gameModes.add(Arrays.asList(gameModes));
        dataHandle = ComponentManager.get(plugin).get(UserData.class);
        commands = new Command[] {
            new PVPManagerCommand(new CommandExecutor() {
                @Override
                public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) {
                    if(!Checker.isPlayer(commandSender))
                        return true;
                    final Player player = (Player) commandSender;
                    final UserData userData = getUserData(player);
                    if(!userData.isSubscribed()) {
                        Message.warn(player, "You are not in a gamemode. Please relog");
                    } else {
                        if (userData.gameMode instanceof PVPGameMode)
                            Message.message(player, "You are in PVP, to leave: " + ChatColor.UNDERLINE + "/pvp quit");
                        else if(userData.gameMode instanceof SpectatorGameMode)
                            Message.message(player, "You are in spectator mode, to leave: " + ChatColor.UNDERLINE + "/pvp quit");
                        else if(userData.gameMode instanceof AdminGameMode)
                            Message.message(player, "You are in admin mode, to leave: " + ChatColor.UNDERLINE + "/pvp quit");
                        else
                            Message.message(player, "You are in the lobby, to join: " + ChatColor.UNDERLINE + "/pvp join");
                    }
                    return true;
                }
            }, ""),
        };

        for(Player player : Bukkit.getOnlinePlayers())
            subscribe(player);
    }

    public void switchGameMode(final Player player, final GameMode to) {
        final UserData userData = getUserData(player);
        if(userData.transitioning) {
            userData.transition.failure();
        }
        userData.transitioning = true;
        try {
            userData.transition = userData.gameMode.exit(player, new Continuation() {
                @Override
                public void success() {
                    userData.transitioning = false;
                    to.enter(player);
                    userData.gameMode = to;
                }

                @Override
                public void failure() {
                    userData.transitioning = false;
                }
            });
        } catch (Throwable ex) {
            try {
            unsubscribe(player);
            } catch (Throwable unex) {
                unex.printStackTrace();
            }
            subscribe(player);
            Message.warn(player, "An error occured, you have forced to rejoin");
            throw ex;
        }
    }

    public void subscribe(Player player) {
        Permission permission = plugin.getPermission();
        if(permission != null) {
            for (GameMode gameMode : gameModes.getGameModes()) {
                if(permission.playerInGroup(player, gameMode.getPermissionGroup()))
                    permission.playerRemoveGroup(player, gameMode.getPermissionGroup());
            }
        }
        gameModes.getDefaultGameMode(player).enter(player);
    }

    public void unsubscribe(Player player) {
        UserData userData = getUserData(player);
        if(userData == null || userData.gameMode == null)
            return;
        userData.gameMode.getSpector().unAssignTo(player);
        userData.gameMode.immediateExit(player);
    }

    public void unsubscribeAll() {
        for (Player player : Bukkit.getOnlinePlayers()) {
            unsubscribe(player);
        }
    }

    public UserData getUserData(Player player) {
        return dataHandle.get(player);
    }

    @Override
    public Command[] getCommands() {
        return commands;
    }

    public PVPManagerPlugin getPlugin() {
        return plugin;
    }

    public GameModeCollection getGameModes() {
        return gameModes;
    }

}


text:
/* Auto-generated by genmsg_cpp from file /home/notroot/IAI/ARES/px4/Firmware/msg/fence_vertex.msg */

#pragma once

#include <stdint.h>
#include <uORB/uORB.h>

#ifndef __cplusplus

#endif

/**
 * @addtogroup topics
 * @{
 */

#ifdef __cplusplus
struct __EXPORT fence_vertex_s {
#else
struct fence_vertex_s {
#endif
	float lat;
	float lon;
#ifdef __cplusplus

#endif
};

/**
 * @}
 */

/* register this as object request broker structure */
ORB_DECLARE(fence_vertex);


text:
namespace ray {
namespace gcs {

class MockGcsClientOptions : public GcsClientOptions {
 public:
};

}  // namespace gcs
}  // namespace ray

namespace ray {
namespace gcs {

class MockGcsClient : public GcsClient {
 public:
  MOCK_METHOD(Status, Connect, (instrumented_io_context & io_service), (override));
  MOCK_METHOD(void, Disconnect, (), (override));
  MOCK_METHOD((std::pair<std::string, int>), GetGcsServerAddress, (), (const, override));
  MOCK_METHOD(std::string, DebugString, (), (const, override));

  MockGcsClient() {
    mock_job_accessor = new MockJobInfoAccessor();
    mock_actor_accessor = new MockActorInfoAccessor();
    mock_node_accessor = new MockNodeInfoAccessor();
    mock_node_resource_accessor = new MockNodeResourceInfoAccessor();
    mock_error_accessor = new MockErrorInfoAccessor();
    mock_stats_accessor = new MockStatsInfoAccessor();
    mock_worker_accessor = new MockWorkerInfoAccessor();
    mock_placement_group_accessor = new MockPlacementGroupInfoAccessor();
    mock_internal_kv_accessor = new MockInternalKVAccessor();

    GcsClient::job_accessor_.reset(mock_job_accessor);
    GcsClient::actor_accessor_.reset(mock_actor_accessor);
    GcsClient::node_accessor_.reset(mock_node_accessor);
    GcsClient::node_resource_accessor_.reset(mock_node_resource_accessor);
    GcsClient::stats_accessor_.reset(mock_stats_accessor);
    GcsClient::error_accessor_.reset(mock_error_accessor);
    GcsClient::worker_accessor_.reset(mock_worker_accessor);
    GcsClient::placement_group_accessor_.reset(mock_placement_group_accessor);
  }
  MockActorInfoAccessor *mock_actor_accessor;
  MockJobInfoAccessor *mock_job_accessor;
  MockNodeInfoAccessor *mock_node_accessor;
  MockNodeResourceInfoAccessor *mock_node_resource_accessor;
  MockErrorInfoAccessor *mock_error_accessor;
  MockStatsInfoAccessor *mock_stats_accessor;
  MockWorkerInfoAccessor *mock_worker_accessor;
  MockPlacementGroupInfoAccessor *mock_placement_group_accessor;
  MockInternalKVAccessor *mock_internal_kv_accessor;
};

}  // namespace gcs
}  // namespace ray


text:
package io.spotnext.infrastructure.type;

public enum ListModification {
	REMOVE, ADD, CLEAR, SET
}


text:
module.exports = {};
var fs = require('fs');
var controllers = fs.readdirSync('./server/controllers');
for (var i = 0; i < controllers.length; i++) {
    if(controllers[i] === 'index.js'){
        continue;
    }

    var current = require('./' + controllers[i]);
    module.exports[current.name] = current.data;
}


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>Stackable Javascript</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

Hello, world!


text:
package springStarterProject.dao;

import java.util.List;

import springStarterProject.model.Student;

public interface StudentDAO {
    public long createStudent(Student student);
    public Student updateStudent(Student student);
    public void deleteStudent(long id);
    public List<Student> getAllStudents();
    public Student getStudent(long id);
}


text:
class AddWordIdToContexts < ActiveRecord::Migration
  def self.up
    add_column :contexts, :word_id, :integer
  end

  def self.down
    remove_column :contexts, :word_id
  end
end


text:
from flask import Blueprint

economy = Blueprint('economy',
	             __name__,
	             template_folder='templates',
	             static_folder='static',
				 static_url_path='/economy/static'
)

from . import views


text:
var exec = require('cordova/exec');
var platformId = require('cordova/platform').id;

module.exports = {

    /**
     * Call the native dialer
     *
     * @param {String, Function}      The phone number to call, The callback error function
     */
    dial: function(phnum, errorCallback, successCallback) {
        if (phnum == null) errorCallback("empty");
        if (platformId == 'ios' || platformId == 'android') {
            exec(
                successCallback,
                errorCallback,
                "PhoneDialer",
                "dial",
                [phnum]
            );
        } else {
            document.location.href = "tel:" + phnum;
            if (successCallback) successCallback();
        }
    },
};


text:
import Ember from 'ember';

export default Ember.Mixin.create({
  boundResize: null,
  throttleTimer: null,
  resizeInterval: 200,

  didInsertElement: function() {
    this._super();

    this.set('boundResize', this.triggerResize.bind(this));
    $(window).on('resize', this.get('boundResize'));
    $(window).on('focus', this.get('boundResize'));
    Ember.run.next(this,'onResize');
  },

  triggerResize: function() {
    var timer = Ember.run.throttle(this, 'onResize', this.get('resizeInterval'), false);
    this.set('throttleTimer', timer);
  },

  onResize: function() {
    // Override me with resize logic
  },

  willDestroyElement: function() {
    Ember.run.cancel(this.get('throttleTimer'));
    $(window).off('resize', this.get('boundResize'));
    $(window).off('focus', this.get('boundResize'));
  },
});


text:
function main() {
    local quiet=0

    for arg in "$@"
    do
        case $arg in
            "-q"|"--quiet" )
               quiet=1
               ;;

            "-h"|"--help" )
               echo "venv-activate.sh:  Enter the Mycroft virtual environment"
               echo "Usage:"
               echo "   source venv-activate.sh"
               echo "or"
               echo "   . venv-activate.sh"
               echo ""
               echo "Options:"
               echo "   -q | --quiet    Don't show instructions."
               echo "   -h | --help    Show help."
               return 0
               ;;

            *)
               echo "ERROR:  Unrecognized option: $@"
               return 1
               ;;
       esac
    done

    if [ "$0" == "$BASH_SOURCE" ] ; then
        # Prevent running in script then exiting immediately
        echo "ERROR: Invoke with 'source venv-activate.sh' or '. venv-activate.sh'"
    else
        local SRC_DIR="$( builtin cd "$( dirname "${BASH_SOURCE}" )" ; pwd -P )"
        source ${SRC_DIR}/.venv/bin/activate

        # Provide an easier to find "mycroft-" prefixed command.
        unalias mycroft-venv-activate 2>/dev/null
        alias mycroft-venv-deactivate="deactivate && unalias mycroft-venv-deactivate 2>/dev/null && alias mycroft-venv-activate=\"source '${SRC_DIR}/venv-activate.sh'\""
        if [ $quiet -eq 0 ] ; then
            echo "Entering Mycroft virtual environment.  Run 'mycroft-venv-deactivate' to exit"
        fi
    fi
}

main $@