text:
This document details how to setup environments for some languages.

## Native: C & C++

The default setup and packages include native support, check [this document](../generic/general.md).

## Python

Virtualenv per project, the deployment system for each project, which is capistrano, will setup the virtualenv for the project.

Python and python3 themselves are provided by the system and are installed as part of the default devops package on any server check [this document](../generic/general.md).

Virtualenv must be install system wide in order to be available for developers running their capistrano scripts.

To do so run `dnf install virtualenv`.

### How to create a python2 virtual env?

`virtualenv -p python2 <env-foldername>`

### How to create a python 3 virtual env?

`virtualenv -p python3 <env-foldername>`

## Node

Nvm is used to manage node version installing system node before nvm is prudent.

Simply run the install script from [nvm readme](https://github.com/creationix/nvm)

`curl -o- https://raw.githubusercontent.com/creationix/nvm/<nvm version>/install.sh | bash`

This must be done for each user that wants node on the server.
bash must reload before there is any effect after installing nvm

`nvm install v7.7.3`
`nvm alias default v7.7.3`

Either use v7.7.1 or latest, configuration of other versions if required is done through capistrano script and `.nvmrc` file.

`nvm ls-remote` lists available versions, latest is last one printed.

## Ruby

rbenv is used to manage ruby versions, installing system ruby before rbenv is prudent.

DO NOT USE RVM.

### Rbenv installation

```bash
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
cd ~/.rbenv && src/configure && make -C src
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
```
This must be done for each user that wants ruby on the server.
bash must reload before there is any effect after installing rbenv.

List ruby versions via `rbenv install -l`

Ignore all except those of the format `2.3.1`

Install `2.3.1` or latest. `rbenv install 2.3.1`. Make the version you installed defualt `rbenv global 2.3.1`

Rehash (after installing new ruby version or gems with executables) `rbenv rehash`

Install default gems `gem install bundler pry` and rehash again.

Installing a specific version is to be handled by project maintainers via capistrano and `.ruby-version` or `RUBY_VERSION` env var.

Additional documentation [here](https://github.com/rbenv/rbenv)


text:
package utils

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/onsi/ginkgo"
	k8sv1 "k8s.io/api/core/v1"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	k8serrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/client-go/kubernetes"
)

const (
	// PodWaitForTime is the time to wait for Pod operations to complete
	PodWaitForTime = defaultPollPeriod
	// PodWaitForTimeFast is the fast time to wait for Pod operations to complete (30 sec)
	PodWaitForTimeFast = defaultPollPeriodFast
	// PodWaitIntervalFast is the fast polling interval (250ms)
	PodWaitIntervalFast = 250 * time.Millisecond

	podCreateTime = defaultPollPeriod
	podDeleteTime = defaultPollPeriod

	//VerifierPodName is the name of the verifier pod.
	VerifierPodName = "verifier"
)

// DeleteVerifierPod deletes the verifier pod
func DeleteVerifierPod(clientSet *kubernetes.Clientset, namespace string) error {
	return DeletePodByName(clientSet, VerifierPodName, namespace, nil)
}

// CreatePod calls the Kubernetes API to create a Pod
func CreatePod(clientSet *kubernetes.Clientset, namespace string, podDef *k8sv1.Pod) (*k8sv1.Pod, error) {
	err := wait.PollImmediate(2*time.Second, podCreateTime, func() (bool, error) {
		var err error
		_, err = clientSet.CoreV1().Pods(namespace).Create(context.TODO(), podDef, metav1.CreateOptions{})
		if err != nil {
			return false, err
		}
		return true, nil
	})
	return podDef, err
}

// DeletePodByName deletes the pod based on the passed in name from the passed in Namespace
func DeletePodByName(clientSet *kubernetes.Clientset, podName, namespace string, gracePeriod *int64) error {
	_ = clientSet.CoreV1().Pods(namespace).Delete(context.TODO(), podName, metav1.DeleteOptions{
		GracePeriodSeconds: gracePeriod,
	})
	return wait.PollImmediate(2*time.Second, podDeleteTime, func() (bool, error) {
		_, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{})
		if errors.IsNotFound(err) {
			return true, nil
		}
		return false, err
	})
}

// DeletePodNoGrace deletes the passed in Pod from the passed in Namespace
func DeletePodNoGrace(clientSet *kubernetes.Clientset, pod *k8sv1.Pod, namespace string) error {
	zero := int64(0)
	return DeletePodByName(clientSet, pod.Name, namespace, &zero)
}

// DeletePod deletes the passed in Pod from the passed in Namespace
func DeletePod(clientSet *kubernetes.Clientset, pod *k8sv1.Pod, namespace string) error {
	return DeletePodByName(clientSet, pod.Name, namespace, nil)
}

// FindPodBySuffix finds the first pod which has the passed in suffix. Returns error if multiple pods with the same suffix are found.
func FindPodBySuffix(clientSet *kubernetes.Clientset, namespace, suffix, labelSelector string) (*k8sv1.Pod, error) {
	return findPodByCompFunc(clientSet, namespace, suffix, labelSelector, strings.HasSuffix)
}

// FindPodByPrefix finds the first pod which has the passed in prefix. Returns error if multiple pods with the same prefix are found.
func FindPodByPrefix(clientSet *kubernetes.Clientset, namespace, prefix, labelSelector string) (*k8sv1.Pod, error) {
	return findPodByCompFunc(clientSet, namespace, prefix, labelSelector, strings.HasPrefix)
}

// FindPodBySuffixOnce finds once (no polling) the first pod which has the passed in suffix. Returns error if multiple pods with the same suffix are found.
func FindPodBySuffixOnce(clientSet *kubernetes.Clientset, namespace, suffix, labelSelector string) (*k8sv1.Pod, error) {
	return findPodByCompFuncOnce(clientSet, namespace, suffix, labelSelector, strings.HasSuffix)
}

// FindPodByPrefixOnce finds once (no polling) the first pod which has the passed in prefix. Returns error if multiple pods with the same prefix are found.
func FindPodByPrefixOnce(clientSet *kubernetes.Clientset, namespace, prefix, labelSelector string) (*k8sv1.Pod, error) {
	return findPodByCompFuncOnce(clientSet, namespace, prefix, labelSelector, strings.HasPrefix)
}

func findPodByCompFunc(clientSet *kubernetes.Clientset, namespace, prefix, labelSelector string, compFunc func(string, string) bool) (*k8sv1.Pod, error) {
	var result *k8sv1.Pod
	var err error
	wait.PollImmediate(2*time.Second, podCreateTime, func() (bool, error) {
		result, err = findPodByCompFuncOnce(clientSet, namespace, prefix, labelSelector, compFunc)
		if result != nil {
			return true, err
		}
		// If no result yet, continue polling even if there is an error
		return false, nil
	})
	return result, err
}

func findPodByCompFuncOnce(clientSet *kubernetes.Clientset, namespace, prefix, labelSelector string, compFunc func(string, string) bool) (*k8sv1.Pod, error) {
	var result *k8sv1.Pod
	podList, err := clientSet.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{
		LabelSelector: labelSelector,
	})
	if err != nil {
		return nil, err
	}
	for _, pod := range podList.Items {
		if compFunc(pod.Name, prefix) {
			if result == nil {
				result = pod.DeepCopy()
			} else {
				fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: First pod name %s in namespace %s\n", result.Name, result.Namespace)
				fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: Second pod name %s in namespace %s\n", pod.Name, pod.Namespace)
				return result, fmt.Errorf("Multiple pods starting with prefix %q in namespace %q", prefix, namespace)
			}
		}
	}
	if result == nil {
		return nil, errors.NewNotFound(v1.Resource("pod"), prefix)
	}
	return result, nil
}

// WaitTimeoutForPodReady waits for the given pod to be created and ready
func WaitTimeoutForPodReady(clientSet *kubernetes.Clientset, podName, namespace string, timeout time.Duration) error {
	return WaitTimeoutForPodCondition(clientSet, podName, namespace, k8sv1.PodReady, 2*time.Second, timeout)
}

// WaitTimeoutForPodReadyPollPeriod waits for the given pod to be created and ready using the passed in poll period
func WaitTimeoutForPodReadyPollPeriod(clientSet *kubernetes.Clientset, podName, namespace string, pollperiod, timeout time.Duration) error {
	return WaitTimeoutForPodCondition(clientSet, podName, namespace, k8sv1.PodReady, pollperiod, timeout)
}

// WaitTimeoutForPodSucceeded waits for pod to succeed
func WaitTimeoutForPodSucceeded(clientSet *kubernetes.Clientset, podName, namespace string, timeout time.Duration) error {
	return WaitTimeoutForPodStatus(clientSet, podName, namespace, k8sv1.PodSucceeded, timeout)
}

// WaitTimeoutForPodFailed waits for pod to fail
func WaitTimeoutForPodFailed(clientSet *kubernetes.Clientset, podName, namespace string, timeout time.Duration) error {
	return WaitTimeoutForPodStatus(clientSet, podName, namespace, k8sv1.PodFailed, timeout)
}

// WaitTimeoutForPodStatus waits for the given pod to be created and have a expected status
func WaitTimeoutForPodStatus(clientSet *kubernetes.Clientset, podName, namespace string, status k8sv1.PodPhase, timeout time.Duration) error {
	return wait.PollImmediate(2*time.Second, timeout, podStatus(clientSet, podName, namespace, status))
}

// WaitTimeoutForPodCondition waits for the given pod to be created and have an expected condition
func WaitTimeoutForPodCondition(clientSet *kubernetes.Clientset, podName, namespace string, conditionType k8sv1.PodConditionType, pollperiod, timeout time.Duration) error {
	return wait.PollImmediate(pollperiod, timeout, podCondition(clientSet, podName, namespace, conditionType))
}

func podStatus(clientSet *kubernetes.Clientset, podName, namespace string, status k8sv1.PodPhase) wait.ConditionFunc {
	return func() (bool, error) {
		pod, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{})
		if err != nil {
			if k8serrors.IsNotFound(err) {
				return false, nil
			}
			return false, err
		}
		fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: Checking POD %s phase: %s\n", podName, string(pod.Status.Phase))
		switch pod.Status.Phase {
		case status:
			return true, nil
		}
		return false, nil
	}
}

func podCondition(clientSet *kubernetes.Clientset, podName, namespace string, conditionType k8sv1.PodConditionType) wait.ConditionFunc {
	return func() (bool, error) {
		pod, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{})
		if err != nil {
			if k8serrors.IsNotFound(err) {
				return false, nil
			}
			return false, err
		}
		for _, cond := range pod.Status.Conditions {
			if cond.Type == conditionType {
				fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: Checking POD %s condition: %s=%s\n", podName, string(cond.Type), string(cond.Status))
				if cond.Status == k8sv1.ConditionTrue {
					return true, nil
				}
			}
		}
		return false, nil
	}
}

// PodGetNode returns the node on which a given pod is executing
func PodGetNode(clientSet *kubernetes.Clientset, podName, namespace string) (string, error) {
	pod, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{})
	if err != nil {
		return "", err
	}
	return pod.Spec.NodeName, nil
}

// WaitPodDeleted waits fo a pod to no longer exist
// returns whether the pod is deleted along with any error
func WaitPodDeleted(clientSet *kubernetes.Clientset, podName, namespace string, timeout time.Duration) (bool, error) {
	var result bool
	err := wait.PollImmediate(2*time.Second, timeout, func() (bool, error) {
		_, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{})
		if err != nil {
			if k8serrors.IsNotFound(err) {
				result = true
				return true, nil
			}
			return false, err
		}
		return false, nil
	})
	return result, err
}

// IsExpectedNode waits to check if the specified pod is schedule on the specified node
func IsExpectedNode(clientSet *kubernetes.Clientset, nodeName, podName, namespace string, timeout time.Duration) error {
	return wait.PollImmediate(2*time.Second, timeout, isExpectedNode(clientSet, nodeName, podName, namespace))
}

// returns true is the specified pod running on the specified nodeName. Otherwise returns false
func isExpectedNode(clientSet *kubernetes.Clientset, nodeName, podName, namespace string) wait.ConditionFunc {
	return func() (bool, error) {
		pod, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{})
		if err != nil {
			if k8serrors.IsNotFound(err) {
				return false, nil
			}
			return false, err
		}
		fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: Checking Node name: %s\n", string(pod.Spec.NodeName))
		if pod.Spec.NodeName == nodeName {
			return true, nil
		}
		return false, nil
	}
}

// GetSchedulableNode return a schedulable node from a nodes list
func GetSchedulableNode(nodes *v1.NodeList) *string {
	for _, node := range nodes.Items {
		if node.Spec.Taints == nil {
			return &node.Name
		}
		schedulableNode := true
		for _, taint := range node.Spec.Taints {
			if taint.Effect == "NoSchedule" {
				schedulableNode = false
				break
			}
		}
		if schedulableNode {
			return &node.Name
		}
	}
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
package com.ivyis.di.trans.steps.git.command.impl;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.Logger;
import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.NoFilepatternException;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.i18n.BaseMessages;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.ivyis.di.trans.steps.git.GitCommandType;
import com.ivyis.di.trans.steps.git.command.GitCommand;
import com.ivyis.di.trans.steps.git.command.GitOperationsCommand;
import com.ivyis.di.trans.steps.git.operations.GitOperationsStep;

/**
 * Add Git command implementation.
 *
 * @author Joel Latino
 * @since 1.0.0
 */
public class AddGitCommand implements GitOperationsCommand {
  private static final Class<?> PKG = AddGitCommand.class; // for i18n
  private static final Logger LOGGER = Logger.getLogger(PKG);

  private String filepattern;
  private boolean update;

  public AddGitCommand() {}

  public AddGitCommand(String description) {
    if ("".equals(description)) {
      throw new IllegalArgumentException("Unkomnown config fields.");
    }
    final String[] stringProps = description.split(" / ");
    for (String stringProp : stringProps) {
      if (BaseMessages.getString(PKG, "Git.FilePattern.Label").equals(
          stringProp.split(":")[0].trim())) {
        this.filepattern = stringProp.split(":")[1].trim();
      } else if (BaseMessages.getString(PKG, "Git.Update.Label").equals(
          stringProp.split(":")[0].trim())) {
        this.update = Boolean.parseBoolean(stringProp.split(":")[1]
            .trim());
      }
    }
  }

  public AddGitCommand(Node xml, String stepName) throws KettleException {
    try {
      final XPathFactory xPathFactory = XPathFactory.newInstance();
      final XPath xpath = xPathFactory.newXPath();
      XPathExpression xPathExpr = xpath.compile("//step[name='"
          + stepName + "']/gitCommands//" + GitCommand.MAIN_NODE
          + "/filepattern/text()");
      this.filepattern = (String) xPathExpr.evaluate(xml,
          XPathConstants.STRING);

      xPathExpr = xpath.compile("//step[name='" + stepName
          + "']/gitCommands//" + GitCommand.MAIN_NODE
          + "/update/text()");
      this.update = Boolean.parseBoolean((String) xPathExpr.evaluate(xml,
          XPathConstants.STRING));

    } catch (XPathExpressionException e) {
      throw new KettleException(e);
    }
  }

  public String getDescription() {
    return BaseMessages.getString(PKG, "Git.FilePattern.Label") + ": "
        + (filepattern == null ? "" : filepattern) + " / "
        + BaseMessages.getString(PKG, "Git.Update.Label") + ": "
        + update;
  }

  public GitCommandType getCommandType() {
    return GitCommandType.ADD;
  }

  public String getXML() {
    try {
      final DocumentBuilderFactory dFact = DocumentBuilderFactory
          .newInstance();
      final DocumentBuilder build = dFact.newDocumentBuilder();
      final Document doc = build.newDocument();
      final Element root = doc.createElement(MAIN_NODE);
      doc.appendChild(root);
      final Element commandName = doc.createElement(COMMAND_NAME_NODE);
      commandName.appendChild(doc.createTextNode(GitCommandType.ADD
          .getOperationName()));
      root.appendChild(commandName);

      final Element filepatternNode = doc.createElement("filepattern");
      filepatternNode.appendChild(doc.createTextNode(filepattern));
      root.appendChild(filepatternNode);

      final Element updateNode = doc.createElement("update");
      updateNode.appendChild(doc.createTextNode(String.valueOf(update)));
      root.appendChild(updateNode);

      final Transformer tf = TransformerFactory.newInstance()
          .newTransformer();
      tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      tf.setOutputProperty(OutputKeys.INDENT, "yes");
      tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      final Writer out = new StringWriter();
      tf.transform(new DOMSource(doc), new StreamResult(out));
      return out.toString();

    } catch (ParserConfigurationException pce) {
      LOGGER.error(pce.getMessage(), pce);
      return "";
    } catch (TransformerException e) {
      LOGGER.error(e.getMessage(), e);
      return "";
    }
  }

  public Git call(final GitOperationsStep gitOperationsStep, Git git,
      CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder)
      throws IllegalArgumentException, IOException,
      NoFilepatternException, GitAPIException {

    AddCommand ac = git.add();

    if (!Const.isEmpty(this.filepattern)) {
      ac = ac.addFilepattern(gitOperationsStep
          .environmentSubstitute(this.filepattern));
    }

    ac.setUpdate(update).call();
    return git;
  }

  public String getFilepattern() {
    return filepattern;
  }

  public void setFilepattern(String filepattern) {
    this.filepattern = filepattern;
  }

  public boolean isUpdate() {
    return update;
  }

  public void setUpdate(boolean update) {
    this.update = update;
  }

}


text:
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee180ecbc5e">
<name type="corporate">
 <namePart>United States Government Printing Office</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">printer</roleTerm>
  <roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
 <role>
  <roleTerm type="text" authority="marcrelator">distributor</roleTerm>
  <roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
 <namePart>United States</namePart>
 <namePart>United States District Court District of Kansas</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">author</roleTerm>
  <roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
 <description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
 <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
 <collectionCode>USCOURTS</collectionCode>
 <category>Judicial Publications</category>
 <branch>judicial</branch>
 <dateIngested>2011-11-01</dateIngested>
</extension>
<originInfo>
 <publisher>Administrative Office of the United States Courts</publisher>
 <dateIssued encoding="w3cdtf">2006-01-20</dateIssued>
 <issuance>monographic</issuance>
</originInfo>
<physicalDescription>
 <note type="source content type">deposited</note>
 <digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-2_05-cv-02406</identifier>
<identifier type="local">P0b002ee180ecbc5e</identifier>
<recordInfo>
 <recordContentSource authority="marcorg">DGPO</recordContentSource>
 <recordCreationDate encoding="w3cdtf">2011-11-01</recordCreationDate>
 <recordChangeDate encoding="w3cdtf">2011-11-01</recordChangeDate>
 <recordIdentifier source="DGPO">USCOURTS-ksd-2_05-cv-02406</recordIdentifier>
 <recordOrigin>machine generated</recordOrigin>
 <languageOfCataloging>
  <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ksd-2_05-cv-02406</accessId>
 <courtType>District</courtType>
 <courtCode>ksd</courtCode>
 <courtCircuit>10th</courtCircuit>
 <courtState>Kansas</courtState>
 <courtSortOrder>2190</courtSortOrder>
 <caseNumber>2:05-cv-02406</caseNumber>
 <caseOffice>Kansas City</caseOffice>
 <caseType>civil</caseType>
 <natureSuitCode>442</natureSuitCode>
 <natureSuit>Civil Rights Employment</natureSuit>
 <party fullName="O'Donnell&Sons Construction Co" lastName="O'Donnell&Sons Construction Co" role="Defendant"></party>
 <party firstName="Phyllis" fullName="Phyllis Marie Strozier" lastName="Strozier" middleName="Marie" role="Plaintiff"></party>
</extension>
<titleInfo>
 <title>Strozier v. O'Donnell&Sons Construction Co</title>
 <partNumber>2:05-cv-02406</partNumber>
</titleInfo>
<location>
 <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-2_05-cv-02406/content-detail.html</url>
</location>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="preferred citation">2:05-cv-02406;05-2406</identifier>
<name type="corporate">
 <namePart>United States District Court District of Kansas</namePart>
 <namePart>10th Circuit</namePart>
 <namePart>Kansas City</namePart>
 <affiliation>U.S. Courts</affiliation>
 <role>
  <roleTerm authority="marcrelator" type="text">author</roleTerm>
  <roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
 <displayForm>O'Donnell&Sons Construction Co</displayForm>
 <namePart type="family">O'Donnell&Sons Construction Co</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Defendant</description>
</name>
<name type="personal">
 <displayForm>Phyllis Marie Strozier</displayForm>
 <namePart type="family">Strozier</namePart>
 <namePart type="given">Phyllis</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ksd-2_05-cv-02406</accessId>
 <courtType>District</courtType>
 <courtCode>ksd</courtCode>
 <courtCircuit>10th</courtCircuit>
 <courtState>Kansas</courtState>
 <courtSortOrder>2190</courtSortOrder>
 <caseNumber>2:05-cv-02406</caseNumber>
 <caseOffice>Kansas City</caseOffice>
 <caseType>civil</caseType>
 <natureSuitCode>442</natureSuitCode>
 <natureSuit>Civil Rights Employment</natureSuit>
 <party fullName="O'Donnell&Sons Construction Co" lastName="O'Donnell&Sons Construction Co" role="Defendant"></party>
 <party firstName="Phyllis" fullName="Phyllis Marie Strozier" lastName="Strozier" middleName="Marie" role="Plaintiff"></party>
 <state>Kansas</state>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-ksd-2_05-cv-02406-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-2_05-cv-02406/USCOURTS-ksd-2_05-cv-02406-0/mods.xml">
 <titleInfo>
  <title>Strozier v. O'Donnell&Sons Construction Co</title>
  <subTitle>ORDER sustaining 13 Motion to Dismiss. Plaintiff's claims are dismissed without prejudice. Signed by Judge Kathryn H. Vratil on 1/20/06. (ls)</subTitle>
  <partNumber>0</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2006-01-20</dateIssued>
</originInfo>
 <relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-ksd-2_05-cv-02406-0.pdf" type="otherFormat">
  <identifier type="FDsys Unique ID">D09002ee180ecc883</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-2_05-cv-02406/USCOURTS-ksd-2_05-cv-02406-0</identifier>
 <identifier type="former granule identifier">ksd-2_05-cv-02406_0.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-2_05-cv-02406/USCOURTS-ksd-2_05-cv-02406-0/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-2_05-cv-02406/pdf/USCOURTS-ksd-2_05-cv-02406-0.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 2:05-cv-02406; Strozier v. O'Donnell&Sons Construction Co; </searchTitle>
  <courtName>United States District Court District of Kansas</courtName>
  <state>Kansas</state>
  <accessId>USCOURTS-ksd-2_05-cv-02406-0</accessId>
  <sequenceNumber>0</sequenceNumber>
  <dateIssued>2006-01-20</dateIssued>
  <docketText>ORDER sustaining 13 Motion to Dismiss. Plaintiff's claims are dismissed without prejudice. Signed by Judge Kathryn H. Vratil on 1/20/06. (ls)</docketText>
</extension>
</relatedItem>
</mods>


text:
<?xml version="1.0"?>
<tool_dependency>
    <package name="hisat" version="2.0">
        <repository name="package_hisat_2_0" owner="iuc" />
    </package>
</tool_dependency>


text:
<?php

namespace App\Admin;

use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Admin\{
    AbstractAdmin,
    AdminInterface
};
use Knp\Menu\ItemInterface as MenuItemInterface;
use Sonata\AdminBundle\Datagrid\{
    ListMapper,
    DatagridMapper
};
use Symfony\Component\Form\Extension\Core\Type\{
    FileType,
    HiddenType,
    ChoiceType,
    TextareaType
};
use App\Entity\{
    Company,
    Category,
    User
};
use App\Service\FileUploader;
use App\Form\Type\KeyValueType;
use Sonata\AdminBundle\Form\Type\ModelType;

class CompanyAdmin extends AbstractAdmin {

    protected $datagridValues = [
        '_sort_by' => 'title',
    ];

    protected function configureFormFields(FormMapper $formMapper) {
        $companyObj = $this->getSubject();

        $fileFieldOptions = ['required' => false];
        if ($companyObj && ($image = $companyObj->getLogo())) {
            $imgPath = $this->getConfigurationPool()->getContainer()->getParameter('company_images');
            $imgPath = substr($imgPath, strpos($imgPath, '/uploads'));
            $imageSrc = $this->getRequest()->getUriForPath($imgPath . $image);

            $fileFieldOptions['help'] = '<img src="' . $imageSrc . '" height="100px" width="auto"/>';

            $fileFieldOptions['data_class'] = null;
        }

        $formMapper
                ->tab('Content')
                ->add('logo', FileType::class, $fileFieldOptions)
                ->add('title')
                ->add('description', TextareaType::class, ['required' => false])
                ->add('categories', ModelType::class, [
                    'class' => Category::class,
                    'multiple' => true
                ])
                ->add('aliases', null, ['required' => false])
                ->end()->end()
                ->tab('Metadata')
                ->add('metadata', KeyValueType::class, [
                    'required' => false,
                    'allowed_keys' => [
                        Company::METADATA
                    ]
                ])
                ->end()->end()
                ->tab('Owner')
                ->add('featured', null, ['required' => false])
                ->add('agent', ModelType::class, [
                    'class' => User::class,
                    'required' => false
                ])
                ->end()->end()
                ->tab('SEO')
                ->add('metaTitle')
                ->add('metaDescription')
                ->end()
        ;

        if ($companyObj && ($image = $companyObj->getLogo())) {
            $formMapper->add('default_image', HiddenType::class, [
                'mapped' => null,
                'data' => $companyObj->getLogo()
            ]);
        }
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper) {
        $datagridMapper
                ->add('title')
                ->add('categories')
        ;
    }

    protected function configureListFields(ListMapper $listMapper) {
        $listMapper
                ->addIdentifier('title')
                ->add('featured', 'boolean', ['editable' => true])
                ->addIdentifier('categories')
        ;
    }

    protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null) {
        if (!$childAdmin && !in_array($action, ['edit', 'show'])) {
            return;
        }

        $admin = $this->isChild() ? $this->getParent() : $this;
        $id = $admin->getRequest()->get('id');

        if ($this->isGranted('EDIT')) {
            $menu->addChild('Edit Company', ['uri' => $admin->generateUrl('edit', ['id' => $id])]);
        }

        //$menu->addChild('View', ['uri' => $admin->generateUrl('show', ['id' => $id])]);

        if ($this->isGranted('LIST')) {
            $menu->addChild('Manage Gallery', [
                'uri' => $admin->generateUrl('admin.company.gallery.list', ['id' => $id])
            ]);
        }
        if ($this->isGranted('LIST')) {
            $menu->addChild('Manage Branches', [
                'uri' => $admin->generateUrl('admin.company.address.list', ['id' => $id])
            ]);
        }
    }

    public function toString($object) {
        return $object instanceof Company ? $object->getTitle() : 'Company';
    }

    public function prePersist($company) {
        $file = $company->getLogo();

        if (!is_null($file)) {
            $imgPath = $this->getConfigurationPool()->getContainer()->getParameter('company_images');
            $fileName = $this->getConfigurationPool()->getContainer()->get(FileUploader::class)->upload($file, $imgPath);
            $company->setLogo($fileName);
        }
    }

    public function preUpdate($company) {
        $file = $company->getLogo();
        $id = $this->getUniqid();
        $request = $this->getRequest()->get($id);
        if (!is_null($file) && !empty($file)) {
            $imgPath = $this->getConfigurationPool()->getContainer()->getParameter('company_images');
            $fileName = $this->getConfigurationPool()->getContainer()->get(FileUploader::class)->upload($file, $imgPath);
            $company->setLogo($fileName);
        } elseif (isset($request['default_image'])) {
            $company->setLogo($request['default_image']);
        }
    }

}


text:
<template name="orionAttributesSummernote">

    {{# if isUploading }}

    {{/ if }}

</template>

<template name="orionAttributesSummernoteColumn">
  {{ preview }}
</template>


text:
<?php
	// These are the email addresses for all major US sms gateways
	// Send a text by emailing "<10 digit number><carrier specific gateway from array>"

	$text2email = array(
		'3 River Wireless' => '@sms.3rivers.net',
		'ACS Wireless' => '@paging.acswireless.com',
		'Alltel' => '@message.alltel.com',
		'AT&T' => '@txt.att.net ',
		'Bell Canada' => '@bellmobility.ca',
		'Bell Mobility (Canada)' => '@txt.bell.ca',
		'Bell Mobility' => '@txt.bellmobility.ca',
		'Blue Sky Frog' => '@blueskyfrog.com',
		'Bluegrass Cellular' => '@sms.bluecell.com',
		'Boost Mobile' => '@myboostmobile.com',
		'BPL Mobile' => '@bplmobile.com',
		'Carolina West Wireless' => '@cwwsms.com',
		'Cellular One' => '@mobile.celloneusa.com',
		'Cellular South' => '@csouth1.com',
		'Centennial Wireless' => '@cwemail.com',
		'CenturyTel' => '@messaging.centurytel.net',
		'Cingular (Now AT&T)' => '@txt.att.net ',
		'Clearnet' => '@msg.clearnet.com',
		'Comcast' => '@comcastpcs.textmsg.com',
		'Corr Wireless Communications' => '@corrwireless.net',
		'Dobson' => '@mobile.dobson.net',
		'Edge Wireless' => '@sms.edgewireless.com',
		'Fido' => '@fido.ca',
		'Golden Telecom' => '@sms.goldentele.com',
		'Helio' => '@messaging.sprintpcs.com',
		'Houston Cellular' => '@text.houstoncellular.net',
		'Idea Cellular' => '@ideacellular.net',
		'Illinois Valley Cellular' => '@ivctext.com',
		'Inland Cellular Telephone' => '@inlandlink.com',
		'MCI' => '@pagemci.com',
		'Metrocall' => '@page.metrocall.com',
		'Metrocall 2-way' => '@my2way.com',
		'Metro PCS' => '@mymetropcs.com',
		'Microcell' => '@fido.ca',
		'Midwest Wireless' => '@clearlydigital.com',
		'Mobilcomm' => '@mobilecomm.net',
		'MTS' => '@text.mtsmobility.com',
		'Nextel' => '@messaging.nextel.com',
		'OnlineBeep' => '@onlinebeep.net',
		'PCS One' => '@pcsone.net',
		'President\'s Choice' => '@txt.bell.ca',
		'Public Service Cellular' => '@sms.pscel.com',
		'Qwest' => '@qwestmp.com',
		'Rogers AT&T Wireless' => '@pcs.rogers.com',
		'Rogers Canada' => '@pcs.rogers.com',
		'Satellink' => '.pageme@satellink.net',
		'Southwestern Bell' => '@email.swbw.com',
		'Sprint' => '@messaging.sprintpcs.com',
		'Sumcom' => '@tms.suncom.com',
		'Surewest Communicaitons' => '@mobile.surewest.com',
		'T-Mobile' => '@tmomail.net',
		'Telus' => '@msg.telus.com',
		'Tracfone' => '@txt.att.net',
		'Triton' => '@tms.suncom.com',
		'Unicel' => '@utext.com',
		'US Cellular' => '@email.uscc.net ',
		'Solo Mobile' => '@txt.bell.ca',
		'US West' => '@uswestdatamail.com',
		'Verizon' => '@vtext.com',
		'Virgin Mobile' => '@vmobl.com',
		'Virgin Mobile Canada' => '@vmobile.ca',
		'West Central Wireless' => '@sms.wcc.net',
		'Western Wireless' => '@cellularonewest.com',
	);
?>


text:
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';

export interface ISpinnerState {
  show: boolean
}

@Injectable()
export class SpinnerService {
  private _spinnerSubject = new Subject();

  spinnerState = <Observable<ISpinnerState>>this._spinnerSubject.asObservable();

  show() {
    this._spinnerSubject.next(<ISpinnerState>{ show: true });
  }

  hide() {
    this._spinnerSubject.next(<ISpinnerState>{ show: false });
  }
}


text:
<?xml version="1.0" ?>
<tei>
	<teiHeader>
		<fileDesc xml:id="55001774"/>
	</teiHeader>
	<text xml:lang="en">
		<front>
<lb/>
	<idno type="DOI">doi:10.1152/ajpregu.00699.2001<lb/> </idno>

	<reference>283:R487-R495
	, 2002. First published 11 April 2002;<lb/>
	Am J Physiol Regul Integr Comp Physiol<lb/>
	</reference>

	<byline>
	<docAuthor>Tetsu Akimoto, Helen Liapis and Marc R. Hammerman<lb/></docAuthor>
	</byline>

	<docTitle>
	<titlePart>explants is oxygen and VEGF dependent<lb/> Microvessel formation from mouse embryonic aortic<lb/></titlePart>
	</docTitle>

	<note type="other">You might find this additional info useful...<lb/> 27 articles, 11 of which can be accessed free at:<lb/> This article cites<lb/></note>

	<ptr type="web">http://ajpregu.physiology.org/content/283/2/R487.full.html#ref-list-1<lb/></ptr>

 1 other HighWire hosted articles<lb/> This article has been cited by<lb/> [PDF]<lb/> [Full Text]<lb/> [Abstract]<lb/> , June 1, 2003; 284 (6): C1625-C1632.<lb/> Am J Physiol Cell Physiol<lb/> Tetsu Akimoto and Marc R. Hammerman<lb/> extracts from metanephroi<lb/> Microvessel formation from mouse aorta is stimulated in vitro by secreted VEGF and<lb/> including high resolution figures, can be found at:<lb/> Updated information and services<lb/> http://ajpregu.physiology.org/content/283/2/R487.full.html<lb/> can be found at:<lb/> and Comparative Physiology<lb/> American Journal of Physiology -Regulatory, Integrative<lb/> about Additional material and information<lb/>

	<note type="other">http://www.the-aps.org/publications/ajpregu<lb/>

	This infomation is current as of June 30, 2011.<lb/> </note>

	<idno type="ISSN">ISSN: 0363-6119, ESSN: 1522-1490. </idno>

	<note type="other">Visit our website at http://www.the-aps.org/.<lb/>

	Physiological Society, 9650 Rockville Pike, Bethesda MD 20814-3991.</note>

	<note type="copyright">Copyright © 2002 by the American Physiological Society</note>

	<note type="other">.<lb/> ranging from molecules to humans, including clinical investigations. It is published 12 times a year (monthly) by the American<lb/> illuminate normal or abnormal regulation and integration of physiological mechanisms at all levels of biological organization,<lb/> publishes original investigations that<lb/></note>

	<reference>American Journal of Physiology -Regulatory, Integrative and Comparative Physiology<lb/> on June 30, 2011<lb/> ajpregu.physiology.org<lb/> </reference>

	<note type="other">Downloaded from</note>

		</front>
	</text>
</tei>


text:
package appnet

import (
	"context"
	"fmt"
	"net"
	"net/http"
)

type appnetClientCtxKey int

type client struct {
	udsHttpClient http.Client
}

const (
	udsAddressKey   appnetClientCtxKey = iota
	unixNetworkName                    = "unix"
)

// Client retrieves the singleton Appnet client
func Client() *client {
	return &client{
		udsHttpClient: http.Client{
			Transport: &http.Transport{
				DialContext: udsDialContext,
			},
		},
	}
}

func udsDialContext(ctx context.Context, _, _ string) (net.Conn, error) {
	udsPath, ok := ctx.Value(udsAddressKey).(string)
	if !ok {
		return nil, fmt.Errorf("appnet client: Path to appnet admin socket was not a string")
	}
	if udsPath == "" {
		return nil, fmt.Errorf("appnet client: Path to appnet admin socket was blank")
	}
	return net.Dial(unixNetworkName, udsPath)
}


text:
import os

import pytest

from molecule import config
from molecule.driver import lxd

@pytest.fixture
def molecule_driver_section_data():
    return {'driver': {'name': 'lxd', 'options': {}}}

@pytest.fixture
def lxd_instance(molecule_driver_section_data, config_instance):
    config_instance.merge_dicts(config_instance.config,
                                molecule_driver_section_data)

    return lxd.Lxd(config_instance)

def test_config_private_member(lxd_instance):
    assert isinstance(lxd_instance._config, config.Config)

def test_testinfra_options_property(lxd_instance):
    assert {
        'connection': 'ansible',
        'ansible-inventory': lxd_instance._config.provisioner.inventory_file
    } == lxd_instance.testinfra_options

def test_name_property(lxd_instance):
    assert 'lxd' == lxd_instance.name

def test_options_property(lxd_instance):
    assert {} == lxd_instance.options

def test_login_cmd_template_property(lxd_instance):
    assert 'lxc exec {instance} bash' == lxd_instance.login_cmd_template

def test_safe_files(lxd_instance):
    assert [] == lxd_instance.safe_files

def test_login_options(lxd_instance):
    assert {'instance': 'foo'} == lxd_instance.login_options('foo')

def test_ansible_connection_options(lxd_instance):
    x = {'ansible_connection': 'lxd'}

    assert x == lxd_instance.ansible_connection_options('foo')

def test_instance_config_property(lxd_instance):
    x = os.path.join(lxd_instance._config.ephemeral_directory,
                     'instance_config.yml')

    assert x == lxd_instance.instance_config

def test_status(mocker, lxd_instance):
    result = lxd_instance.status()

    assert 2 == len(result)

    assert result[0].instance_name == 'instance-1-default'
    assert result[0].driver_name == 'Lxd'
    assert result[0].provisioner_name == 'Ansible'
    assert result[0].scenario_name == 'default'
    assert result[0].created == 'False'
    assert result[0].converged == 'False'

    assert result[1].instance_name == 'instance-2-default'
    assert result[1].driver_name == 'Lxd'
    assert result[1].provisioner_name == 'Ansible'
    assert result[1].scenario_name == 'default'
    assert result[1].created == 'False'
    assert result[1].converged == 'False'


text:
<?php
  $this->load->view('layout/header');
  $this->load->view('layout/container');
$flag = 0;
$pp1 = '';
$pl1 = '';
$ps1 = '';
$pi1 = '';
$id1 = '';
$orderNumber = '0';
if(isset($_REQUEST['edit-id']))
{
  if($_REQUEST['edit-id'] != '')
  {
	  $id1 = $_REQUEST['edit-id'];
			$sqlQuery = "select
    t.inParentId,
    t.Label,
    t.varPageSlug,
    t.varIcon,
    t.order_number,
    (select s.Label from access_control as s where s.intID = t.inParentId) as ParentName
from access_control as t where t.intID = $id1";
			$result = $this->db->query($sqlQuery);

			if($result->num_rows()>0) {
				foreach($result->result() AS $result11)
				{
				// print_r($result11);
						$flag = 1;
						$pp1 = '<option value="'.$result11->inParentId.'"> '.$result11->ParentName.' </option>';
						$pl1 = $result11->Label;
						$ps1 = $result11->varPageSlug;
						$pi1 = '<option value="'.$result11->varIcon.'">'.$result11->varIcon.'</option>';
						$orderNumber = $result11->order_number;
                 }
            }
  }
}

?>

					   <form action="<?=CTRL?>pages" method="POST" autocomplete="off">

		                    Parent Page
		                    <select class="form-control" name='parent_page'>
<?php
				echo $pp1.'<option value="0"> -- </option>';

			$sqlQuery = " SELECT "
			                ." intID AS id, "
			                ." Label AS label"
			        ." FROM access_control";
			$result = $this->db->query($sqlQuery);

			if($result->num_rows()>0) {
				foreach($result->result() AS $result11)
				{
				echo '<option value="'.$result11->id.'">'.$result11->label.'</option>';
				}
            }

?>
                                                   </select>

		                    Label
		                    <input class="form-control spinner" type='text' name='page_label' required size='35' value="<?php echo $pl1; ?>">

		                    Page slug
		                    <input class="form-control spinner" type='text' name='page_add' required size='35' value="<?php echo $ps1; ?>">

		                    Icon
		                    <select class="form-control" name='page_icon'>
                            <?php echo $pi1.'<option value=""> Select Icon </option>'; ?>
                                      <option value="icon-home">icon-home</option>
                                      <option value="icon-diamond">icon-diamond</option>
                                      <option value="icon-puzzle">icon-puzzle</option>
                                      <option value="icon-settings">icon-settings</option>
                                      <option value="icon-bulb">icon-bulb</option>
                                      <option value="icon-briefcase">icon-briefcase</option>
                                      <option value="icon-wallet">icon-wallet</option>
                                      <option value="icon-bar-chart">icon-bar-chart</option>
                                      <option value="icon-pointer">icon-pointer</option>
                                      <option value="icon-layers">icon-layers</option>
                                      <option value="icon-basket">icon-basket</option>
                                      <option value="icon-docs">icon-docs</option>
                                      <option value="icon-user">icon-user</option>
                                      <option value="icon-social-dribbble">icon-social-dribbble</option>
                                      <option value="icon-folder">icon-folder</option>
                         </select>

                                   Menu Order
                                   <input class="form-control spinner" type='text' name='orderNumber' required size='35' value="<?php echo $orderNumber; ?>">

                            <?php
                            if($flag == 1)
							{

								echo '<input type="hidden" value="'.$id1.'" id="" name="update_page" />'."<input type='submit' name='action-update-page' value='Update Page' class='btn green'>";
							}
							else
							{
								echo ' <input type="hidden" value="update" id="" name="add_new_page" />'."<input type='submit' name='action-add-page' value='Add Page' class='btn green'>";
							}
							?>

						</form>


text:
namespace http2 {
namespace test {

void Randomize(Http2FrameHeader* out, Http2Random* rng) {
  out->payload_length = rng->Rand32() & 0xffffff;
  out->type = static_cast<Http2FrameType>(rng->Rand8());
  out->flags = static_cast<Http2FrameFlag>(rng->Rand8());
  out->stream_id = rng->Rand32() & StreamIdMask();
}
void Randomize(Http2PriorityFields* out, Http2Random* rng) {
  out->stream_dependency = rng->Rand32() & StreamIdMask();
  out->weight = rng->Rand8() + 1;
  out->is_exclusive = rng->OneIn(2);
}
void Randomize(Http2RstStreamFields* out, Http2Random* rng) {
  out->error_code = static_cast<Http2ErrorCode>(rng->Rand32());
}
void Randomize(Http2SettingFields* out, Http2Random* rng) {
  out->parameter = static_cast<Http2SettingsParameter>(rng->Rand16());
  out->value = rng->Rand32();
}
void Randomize(Http2PushPromiseFields* out, Http2Random* rng) {
  out->promised_stream_id = rng->Rand32() & StreamIdMask();
}
void Randomize(Http2PingFields* out, Http2Random* rng) {
  for (int ndx = 0; ndx < 8; ++ndx) {
    out->opaque_bytes[ndx] = rng->Rand8();
  }
}
void Randomize(Http2GoAwayFields* out, Http2Random* rng) {
  out->last_stream_id = rng->Rand32() & StreamIdMask();
  out->error_code = static_cast<Http2ErrorCode>(rng->Rand32());
}
void Randomize(Http2WindowUpdateFields* out, Http2Random* rng) {
  out->window_size_increment = rng->Rand32() & 0x7fffffff;
}
void Randomize(Http2AltSvcFields* out, Http2Random* rng) {
  out->origin_length = rng->Rand16();
}
void Randomize(Http2PriorityUpdateFields* out, Http2Random* rng) {
  out->prioritized_stream_id = rng->Rand32() & StreamIdMask();
}

void ScrubFlagsOfHeader(Http2FrameHeader* header) {
  uint8_t invalid_mask = InvalidFlagMaskForFrameType(header->type);
  uint8_t keep_mask = ~invalid_mask;
  header->RetainFlags(keep_mask);
}

bool FrameIsPadded(const Http2FrameHeader& header) {
  switch (header.type) {
    case Http2FrameType::DATA:
    case Http2FrameType::HEADERS:
    case Http2FrameType::PUSH_PROMISE:
      return header.IsPadded();
    default:
      return false;
  }
}

bool FrameHasPriority(const Http2FrameHeader& header) {
  switch (header.type) {
    case Http2FrameType::HEADERS:
      return header.HasPriority();
    case Http2FrameType::PRIORITY:
      return true;
    default:
      return false;
  }
}

bool FrameCanHavePayload(const Http2FrameHeader& header) {
  switch (header.type) {
    case Http2FrameType::DATA:
    case Http2FrameType::HEADERS:
    case Http2FrameType::PUSH_PROMISE:
    case Http2FrameType::CONTINUATION:
    case Http2FrameType::PING:
    case Http2FrameType::GOAWAY:
    case Http2FrameType::ALTSVC:
      return true;
    default:
      return false;
  }
}

bool FrameCanHaveHpackPayload(const Http2FrameHeader& header) {
  switch (header.type) {
    case Http2FrameType::HEADERS:
    case Http2FrameType::PUSH_PROMISE:
    case Http2FrameType::CONTINUATION:
      return true;
    default:
      return false;
  }
}

}  // namespace test
}  // namespace http2


text:
// @formatter:off

package com.microsoft.alm.teamfoundation.chat.webapi;

/**
 */
public class UserData {

    private String userId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(final String userId) {
        this.userId = userId;
    }
}


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

namespace Sample.Tests.TestInfrastructure
{
    public static class GenericEquals
    {
        private static String[] propertyBlackList = new [] { "Originator" };

        public static Boolean Equals(Object a, Object b)
        {
            if (a == null || b == null)
            {
                return b == null && a == null;
            }

            if (a.GetType() != b.GetType()) return false;
            var propA = a.GetType().GetProperties();
            var propB = b.GetType().GetProperties();

            if (propA.Length != propB.Length) return false;

            return propA.All(p => {

                if (propertyBlackList.Contains(p.Name)) return true;

                var pinfo = propB.SingleOrDefault(pb => pb.Name == p.Name);
                if (pinfo == null) return false;

                var bvalue = pinfo.GetValue(b, null);
                var avalue = p.GetValue(a, null);
                return Object.Equals(avalue, bvalue);
            });
        }
    }
}


text:
<?php

class Amazon_Payments_Model_System_Config_Backend_Enabled extends Mage_Core_Model_Config_Data
{
    /**
     * Validate data
     */
    public function save()
    {

        $data = $this->_getCredentials();
        $isEnabled = $this->getValue();

        if ($isEnabled) {
            if ($data['seller_id']['value'] && !ctype_alnum($data['seller_id']['value'])) {
                Mage::getSingleton('core/session')->addError(Mage::helper('adminhtml')->__('Error: Please verify your Seller ID (alphanumeric characters only).'));
            }

            if (extension_loaded('suhosin')) {
                Mage::getSingleton('core/session')->addError(Mage::helper('adminhtml')->__('Login and Pay with Amazon is not compatible with the suhosin extension and may return missing field errors when placing orders.'));
            }

        }
        return parent::save();
    }

    /**
     * Return dynamic help/comment text
     */
    public function getCommentText(Mage_Core_Model_Config_Element $element, $currentValue)
    {
        $version = Mage::getConfig()->getModuleConfig("Amazon_Payments")->version;

        // @see Amazon_Payments_Model_SimplePath->saveToConfig()
        $enabledMessage = Mage::getSingleton('adminhtml/session')->getEnableMessage();
        if ($enabledMessage) {
            $enabledMessage = '
' . $enabledMessage . '
';
            Mage::getSingleton('adminhtml/session')->unsEnableMessage();
        }

        // SimplePath
        return "v$version

        $enabledMessage

        ";
    }

    /**
     * Return credentials
     */
    private function _getCredentials()
    {
        $config = Mage::getSingleton('amazon_payments/config');

        $groups = $this->getData('groups');
        $fields = $groups['ap_credentials']['fields'];

        // Load value from parent scope if field set as inherited
        foreach ($fields as $fieldName => $fieldValue) {
            if (!isset($fieldValue['value']) && !empty($fieldValue['inherit'])) {
                $fields[$fieldName]['value'] = Mage::getStoreConfig('payment/amazon_payments/' . $fieldName, $this->getStoreCode());
            }
        }

        return $fields;
    }

    /**
     * Return Widgets.js URL
     */
    public function getMwsSellerApiUrl()
    {
        switch (Mage::getStoreConfig('amazon_login/settings/region')) {
          case 'uk':
              $tld = 'co.uk';
              break;

          case 'de':
              $tld = 'de';
              break;

          // US
          default:
              $tld = 'com';
              break;
        }

        return "https://mws.amazonservices.".$tld."/Sellers/2011-07-01";
    }

}


text:
describe("6-create-vm", function() {
    var addDom = function(dom) {
        $(dom).appendTo("#testArea");
        return $("#testArea").children().last();
    },
        getOpitons = function(i) {
            i = (i) ? i : 0;
            return $($("#testArea").children()[i]).data("options");
        },
        getDataBind = function(i) {
            i = (i) ? i : 0;
            return $($("#testArea").children()[i]).attr("data-bind");
        };

    afterEach(function() {
        $("#testArea").html("");
    });
    it("createVm -
 - vm = {myId = ko.observable('boo')}", function () {
        // Arrange
        var result, elms;
        addDom("
");
        elms = pd.parseDom();
        // Act
        result = pd.createVm(elms);

        // Assert
        expect(result.myId()).toBe("boo");
    });

    it("createVm -
 - vm = {foo = ko.observable('boo')}", function () {
        // Arrange
        var result, elms;
        addDom("
");
        elms = pd.parseDom();
        // Act
        result = pd.createVm(elms);

        // Assert
        expect(result.foo()).toBe("boo");
    });
    describe("pd.getVmItem", function () {
        it("getVmItem -
 => ko.observable('boo')", function () {
            // Arrange
            var observable = ko.observable(),
                result,
                elm =addDom("
");
            pd.parseDom();

            // Act
            result = pd.getVmItem(getOpitons());

            // Assert
            expect(result()).toBe("boo");
            expect(result.toString()).toEqual(observable.toString());
        });

        it("getVmItem -
 => ko.observable('box')", function () {
            // Arrange
            var observable = ko.observable(),
                result,
                elm = addDom("
");
            pd.parseDom();

            // Act
            result = pd.getVmItem(getOpitons());

            // Assert
            expect(result()).toBe("box");
            expect(result.toString()).toEqual(observable.toString());
        });

        it("getVmItem -
 => ko.observableArray([])", function () {
            // Arrange
            var pop = ko.observableArray([]),
                x = ko.observable(),
                result;
            addDom("
");
            pd.parseDom();

            // Act
            result = pd.getVmItem(getOpitons());

            // Assert
            expect(result()).toEqual([]);
            expect(result.pop).toBeTruthy();
        });
    });
    describe("pd.transposeInitialValue", function () {
        it("transposeInitialValue - 'boo' => string boo", function () {
            // Arrange
            var result;
            // Act
            result = pd.transposeInitialValue('"boo"');

            // Assert
            expect(result).toBe("boo");
        });
        it("transposeInitialValue - 'boo' => string boo", function () {
            // Arrange
            var result;
            // Act
            result = pd.transposeInitialValue("'box'");

            // Assert
            expect(result).toBe("box");
        });

        it("transposeInitialValue - 'boo' => string boo", function () {
            // Arrange
            var result;
            // Act
            result = pd.transposeInitialValue("foo");

            // Assert
            expect(result).toBe("foo");
        });

        it("transposeInitialValue - '-true' => bool true", function () {
            // Arrange
            var result;
            // Act
            result = pd.transposeInitialValue("-true");

            // Assert
            expect(result).toBe(true);
        });

        it("transposeInitialValue - '-f' => bool false", function () {
            // Arrange
            var result;
            // Act
            result = pd.transposeInitialValue("-f");

            // Assert
            expect(result).toBe(false);
        });

        it("transposeInitialValue - '+5' => number 5", function () {
            // Arrange
            var result;
            // Act
            result = pd.transposeInitialValue("+5");

            //Assert
            expect(result).toBe(5);
        });

        it("transposeInitialValue - '+-3.4' => number -3.4", function () {
            // Arrange
            var result;
            // Act
            result = pd.transposeInitialValue("+-3.4");

            // Assert
            expect(result).toBe(-3.4);
        });
    });
});


text:
<?php

namespace SlmQueueTest;

use PHPUnit\Framework\TestCase;
use SlmQueue\ConfigProvider;
use SlmQueue\Module;

class ConfigProviderTest extends TestCase
{
    public function testConfigProviderGetConfig(): void
    {
        $configProvider = new ConfigProvider();
        $config = $configProvider();

        static::assertNotEmpty($config);
    }

    public function testConfigEqualsToModuleConfig(): void
    {
        $module = new Module();
        $moduleConfig = $module->getConfig();
        $configProvider = new ConfigProvider();
        $config = $configProvider();

        static::assertEquals($moduleConfig['service_manager'], $config['dependencies']);
        static::assertEquals($moduleConfig['slm_queue'], $config['slm_queue']);
    }
}


text:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using GgpGrpc.Models;
using Metrics.Shared;
using YetiVSI.ProjectSystem.Abstractions;

namespace YetiVSI.Metrics
{
    public interface IProjectPropertiesMetricsParser
    {
        Task<VSIProjectProperties> GetStadiaProjectPropertiesAsync(IAsyncProject project);
    }

    public class ProjectPropertiesMetricsParser : IProjectPropertiesMetricsParser
    {
        public async Task<VSIProjectProperties> GetStadiaProjectPropertiesAsync(
            IAsyncProject project) =>
            new VSIProjectProperties
            {
                Debugging = new VSIProjectProperties.Types.Debugging
                {
                    DeployExecutableOnLaunch = await GetDeployExecutableOnLaunchAsync(project),
                    SurfaceEnforcementMode = await GetSurfaceEnforcementModeAsync(project),
                    LaunchWithRenderDoc = await GetLaunchWithRenderDocAsync(project),
                    LaunchWithRgp = await GetLaunchWithRgpAsync(project),
                    VulkanDriverVariant = await GetVulkanDriverVariantAsync(project),
                    StadiaEndpoint = await  GetStadiaEndpointAsync(project)
                }
            };

        async Task<VSIProjectProperties.Types.BoolValue> GetLaunchWithRenderDocAsync(
            IAsyncProject project)
        {
            try
            {
                return GetBoolValue(await project.GetLaunchWithRenderDocRawAsync());
            }
            catch (Exception e)
            {
                Trace.TraceError("Could not get 'Launch with RenderDoc' value.\r\n" +
                                 $"Message: {e.Message}.\r\nStack trace: {e.StackTrace}");
                return null;
            }
        }

        async Task<VSIProjectProperties.Types.BoolValue> GetLaunchWithRgpAsync(
            IAsyncProject project)
        {
            try
            {
                return GetBoolValue(await project.GetLaunchWithRgpRawAsync());
            }
            catch (Exception e)
            {
                Trace.TraceError("Could not get 'Launch with RGP' value.\r\n" +
                                 $"Message: {e.Message}.\r\nStack trace: {e.StackTrace}");
                return null;
            }
        }

        VSIProjectProperties.Types.BoolValue GetBoolValue(string rawValue)
        {
            if (string.IsNullOrWhiteSpace(rawValue))
            {
                return new VSIProjectProperties.Types.BoolValue
                {
                    IsDefault = true,
                    Value = VSIProjectProperties.Types.BoolValue.Types.Value.BoolNo
                };
            }

            if (!bool.TryParse(rawValue, out bool projectPropertyValue))
            {
                return new VSIProjectProperties.Types.BoolValue
                {
                    IsDefault = false,
                    Value = VSIProjectProperties.Types.BoolValue.Types.Value.BoolOther
                };
            }

            return new VSIProjectProperties.Types.BoolValue
            {
                IsDefault = false,
                Value = projectPropertyValue
                    ? VSIProjectProperties.Types.BoolValue.Types.Value.BoolYes
                    : VSIProjectProperties.Types.BoolValue.Types.Value.BoolNo
            };
        }

        async Task<VSIProjectProperties.Types.Debugging.Types.DeployExecutableOnLaunch?>
            GetDeployExecutableOnLaunchAsync(IAsyncProject project)
        {
            try
            {
                string rawValue = await project.GetDeployExecutableOnLaunchRawAsync();
                if (!Enum.TryParse(rawValue, true, out DeployOnLaunchSetting deployOnLaunch))
                {
                    return string.IsNullOrWhiteSpace(rawValue)
                        ? VSIProjectProperties.Types.Debugging.Types.DeployExecutableOnLaunch
                            .DeployDefault
                        : VSIProjectProperties.Types.Debugging.Types.DeployExecutableOnLaunch
                            .DeployOther;
                }

                switch (deployOnLaunch)
                {
                    case DeployOnLaunchSetting.ALWAYS:
                        return VSIProjectProperties.Types.Debugging.Types.DeployExecutableOnLaunch
                            .YesAlways;
                    case DeployOnLaunchSetting.DELTA:
                        return VSIProjectProperties.Types.Debugging.Types.DeployExecutableOnLaunch
                            .YesBinaryDiff;
                    case DeployOnLaunchSetting.FALSE:
                        return VSIProjectProperties.Types.Debugging.Types.DeployExecutableOnLaunch
                            .DeployNo;
                    default:
                        return VSIProjectProperties.Types.Debugging.Types.DeployExecutableOnLaunch
                            .DeployOther;
                }
            }
            catch (Exception e)
            {
                Trace.TraceError("Could not get 'Deploy executable on launch' value.\r\n" +
                                 $"Message: {e.Message}.\r\nStack trace: {e.StackTrace}");
                return null;
            }
        }

        async Task<VSIProjectProperties.Types.Debugging.Types.SurfaceEnforcement?>
            GetSurfaceEnforcementModeAsync(IAsyncProject project)
        {
            try
            {
                string rawValue = await project.GetSurfaceEnforcementModeRawAsync();
                if (!Enum.TryParse(rawValue, true,
                                   out SurfaceEnforcementSetting surfaceEnforcement))
                {
                    return string.IsNullOrWhiteSpace(rawValue)
                        ? VSIProjectProperties.Types.Debugging.Types.SurfaceEnforcement
                            .SurfaceDefault
                        : VSIProjectProperties.Types.Debugging.Types.SurfaceEnforcement
                            .SurfaceOther;
                }

                switch (surfaceEnforcement)
                {
                    case SurfaceEnforcementSetting.Block:
                        return VSIProjectProperties.Types.Debugging.Types.SurfaceEnforcement
                            .SurfaceBlock;
                    case SurfaceEnforcementSetting.Off:
                        return VSIProjectProperties.Types.Debugging.Types.SurfaceEnforcement
                            .SurfaceOff;
                    case SurfaceEnforcementSetting.Warn:
                        return VSIProjectProperties.Types.Debugging.Types.SurfaceEnforcement
                            .SurfaceWarn;
                    default:
                        return VSIProjectProperties.Types.Debugging.Types.SurfaceEnforcement
                            .SurfaceOther;
                }
            }
            catch (Exception e)
            {
                Trace.TraceError("Could not get 'Stadia instance surface enforcement' value.\r\n" +
                                 $"Message: {e.Message}.\r\nStack trace: {e.StackTrace}");
                return null;
            }
        }

        async Task<VSIProjectProperties.Types.Debugging.Types.VulkanDriverVariant?>
            GetVulkanDriverVariantAsync(IAsyncProject project)
        {
            try
            {
                string rawValue = await project.GetVulkanDriverVariantRawAsync();
                if (string.IsNullOrWhiteSpace(rawValue))
                {
                    return VSIProjectProperties.Types.Debugging.Types.VulkanDriverVariant
                        .VulkanDefault;
                }

                if (rawValue == "opt")
                {
                    return VSIProjectProperties.Types.Debugging.Types.VulkanDriverVariant.Optimized;
                }

                if (rawValue == "optprintasserts")
                {
                    return VSIProjectProperties.Types.Debugging.Types.VulkanDriverVariant
                        .PrintingAssertions;
                }

                if (rawValue == "dbgtrapasserts")
                {
                    return VSIProjectProperties.Types.Debugging.Types.VulkanDriverVariant
                        .TrappingAssertions;
                }

                return VSIProjectProperties.Types.Debugging.Types.VulkanDriverVariant.VulkanOther;
            }
            catch (Exception e)
            {
                Trace.TraceError("Could not get 'Vulkan driver variant' value.\r\n" +
                                 $"Message: {e.Message}.\r\nStack trace: {e.StackTrace}");
                return null;
            }
        }

        async Task<VSIProjectProperties.Types.Debugging.Types.StadiaEndpoint?>
            GetStadiaEndpointAsync(IAsyncProject project)
        {
            try
            {
                string rawValue = await project.GetStadiaEndpointRawAsync();
                if (!Enum.TryParse(rawValue, true, out StadiaEndpoint endpoint))
                {
                    return string.IsNullOrWhiteSpace(rawValue)
                        ? VSIProjectProperties.Types.Debugging.Types.StadiaEndpoint.EndpointDefault
                        : VSIProjectProperties.Types.Debugging.Types.StadiaEndpoint.EndpointOther;
                }

                switch (endpoint)
                {
                    case StadiaEndpoint.AnyEndpoint:
                        return VSIProjectProperties.Types.Debugging.Types.StadiaEndpoint
                            .AnyEndpoint;
                    case StadiaEndpoint.PlayerEndpoint:
                        return VSIProjectProperties.Types.Debugging.Types.StadiaEndpoint
                            .PlayerWebEndpoint;
                    case StadiaEndpoint.TestClient:
                        return VSIProjectProperties.Types.Debugging.Types.StadiaEndpoint.TestClient;
                    default:
                        return VSIProjectProperties.Types.Debugging.Types.StadiaEndpoint
                            .EndpointOther;
                }
            }
            catch (Exception e)
            {
                Trace.TraceError("Could not get 'Stadia Endpoint' value.\r\n" +
                                 $"Message: {e.Message}.\r\nStack trace: {e.StackTrace}");
                return null;
            }
        }
    }
}


text:
import buildKnex from 'knex';
import Repository from '../repositories/Repository';
import UserRepository from '../repositories/UserRepository';
import {buildMassive} from '../helpers/massiveHelper';
import _ from 'underscore';

export default class DataContext {

    /**
     *
     * @param appConfig
     * @param knex
     * @param massiveInstance
     */
    constructor(appConfig, massiveInstance) {
        if (!appConfig) throw Error('\'appConfig\' should be truthy');
        this.appConfig = appConfig;

        this.db = massiveInstance || buildMassive(this.appConfig.connectionString, _.map(appConfig.entities, e => e.name).concat('user'));

        // create bookshelf models and services
        this.models = {};
        this.services = {};

        // custom models
        if (appConfig.entities) {
            for (let i = 0; i < appConfig.entities.length; i++) {
                let entity = appConfig.entities[i];
                this.models[entity.name] = this.db[entity.name];
                this.services[entity.name] = new Repository(this.appConfig, this, entity);
            }
        }

        // system models and services
        this.models['user'] = this.db.user;
        this.services['user'] = new UserRepository(this.appConfig, this);
    }

    /**
     * Returns the given bookshelf model
     * @param modelName
     * @returns {*}
     */
    getModel(modelName) {
        if (!modelName) throw Error('\'modelName\' should be truthy');
        if (!this.models.hasOwnProperty(modelName))
            throw Error('model name is invalid');
        return this.models[modelName];
    }

    /**
     * Returns the given repository
     * @param modelName
     * @returns {*}
     */
    getRepository(modelName) {
        if (!modelName) throw Error('\'modelName\' should be truthy');
        if (!this.services.hasOwnProperty(modelName))
            throw Error('model name is invalid');
        return this.services[modelName];
    }

}


text:
namespace net {

namespace {

void CallInt64ToInt(const CompletionCallback& callback, int64 result) {
  callback.Run(static_cast<int>(result));
}

}  // namespace

FileStream::Context::IOResult::IOResult()
    : result(OK),
      os_error(0) {
}

FileStream::Context::IOResult::IOResult(int64 result,
                                        logging::SystemErrorCode os_error)
    : result(result),
      os_error(os_error) {
}

// static
FileStream::Context::IOResult FileStream::Context::IOResult::FromOSError(
    logging::SystemErrorCode os_error) {
  return IOResult(MapSystemError(os_error), os_error);
}

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

FileStream::Context::OpenResult::OpenResult() {
}

FileStream::Context::OpenResult::OpenResult(base::File file,
                                            IOResult error_code)
    : file(file.Pass()),
      error_code(error_code) {
}

FileStream::Context::OpenResult::OpenResult(RValue other)
    : file(other.object->file.Pass()),
      error_code(other.object->error_code) {
}

FileStream::Context::OpenResult& FileStream::Context::OpenResult::operator=(
    RValue other) {
  if (this != other.object) {
    file = other.object->file.Pass();
    error_code = other.object->error_code;
  }
  return *this;
}

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

void FileStream::Context::Orphan() {
  DCHECK(!orphaned_);

  orphaned_ = true;

  if (!async_in_progress_) {
    CloseAndDelete();
  } else if (file_.IsValid()) {
#if defined(OS_WIN)
    CancelIo(file_.GetPlatformFile());
#endif
  }
}

void FileStream::Context::Open(const base::FilePath& path,
                               int open_flags,
                               const CompletionCallback& callback) {
  DCHECK(!async_in_progress_);

  bool posted = base::PostTaskAndReplyWithResult(
      task_runner_.get(),
      FROM_HERE,
      base::Bind(
          &Context::OpenFileImpl, base::Unretained(this), path, open_flags),
      base::Bind(&Context::OnOpenCompleted, base::Unretained(this), callback));
  DCHECK(posted);

  async_in_progress_ = true;
}

void FileStream::Context::Close(const CompletionCallback& callback) {
  DCHECK(!async_in_progress_);
  bool posted = base::PostTaskAndReplyWithResult(
      task_runner_.get(),
      FROM_HERE,
      base::Bind(&Context::CloseFileImpl, base::Unretained(this)),
      base::Bind(&Context::OnAsyncCompleted,
                 base::Unretained(this),
                 IntToInt64(callback)));
  DCHECK(posted);

  async_in_progress_ = true;
}

void FileStream::Context::Seek(base::File::Whence whence,
                               int64 offset,
                               const Int64CompletionCallback& callback) {
  DCHECK(!async_in_progress_);

  bool posted = base::PostTaskAndReplyWithResult(
      task_runner_.get(),
      FROM_HERE,
      base::Bind(
          &Context::SeekFileImpl, base::Unretained(this), whence, offset),
      base::Bind(&Context::OnAsyncCompleted,
                 base::Unretained(this),
                 callback));
  DCHECK(posted);

  async_in_progress_ = true;
}

void FileStream::Context::Flush(const CompletionCallback& callback) {
  DCHECK(!async_in_progress_);

  bool posted = base::PostTaskAndReplyWithResult(
      task_runner_.get(),
      FROM_HERE,
      base::Bind(&Context::FlushFileImpl, base::Unretained(this)),
      base::Bind(&Context::OnAsyncCompleted,
                 base::Unretained(this),
                 IntToInt64(callback)));
  DCHECK(posted);

  async_in_progress_ = true;
}

FileStream::Context::OpenResult FileStream::Context::OpenFileImpl(
    const base::FilePath& path, int open_flags) {
  // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
  tracked_objects::ScopedTracker tracking_profile(
      FROM_HERE_WITH_EXPLICIT_FUNCTION(
          "423948 FileStream::Context::OpenFileImpl"));

#if defined(OS_POSIX)
  // Always use blocking IO.
  open_flags &= ~base::File::FLAG_ASYNC;
#endif
  base::File file;
#if defined(OS_ANDROID)
  if (path.IsContentUri()) {
    // Check that only Read flags are set.
    DCHECK_EQ(open_flags & ~base::File::FLAG_ASYNC,
              base::File::FLAG_OPEN | base::File::FLAG_READ);
    file = base::OpenContentUriForRead(path);
  } else {
#endif  // defined(OS_ANDROID)
    // FileStream::Context actually closes the file asynchronously,
    // independently from FileStream's destructor. It can cause problems for
    // users wanting to delete the file right after FileStream deletion. Thus
    // we are always adding SHARE_DELETE flag to accommodate such use case.
    // TODO(rvargas): This sounds like a bug, as deleting the file would
    // presumably happen on the wrong thread. There should be an async delete.
    open_flags |= base::File::FLAG_SHARE_DELETE;
    file.Initialize(path, open_flags);
#if defined(OS_ANDROID)
  }
#endif  // defined(OS_ANDROID)
  if (!file.IsValid())
    return OpenResult(base::File(),
                      IOResult::FromOSError(logging::GetLastSystemErrorCode()));

  return OpenResult(file.Pass(), IOResult(OK, 0));
}

FileStream::Context::IOResult FileStream::Context::CloseFileImpl() {
  file_.Close();
  return IOResult(OK, 0);
}

FileStream::Context::IOResult FileStream::Context::FlushFileImpl() {
  if (file_.Flush())
    return IOResult(OK, 0);

  return IOResult::FromOSError(logging::GetLastSystemErrorCode());
}

void FileStream::Context::OnOpenCompleted(const CompletionCallback& callback,
                                          OpenResult open_result) {
  file_ = open_result.file.Pass();
  if (file_.IsValid() && !orphaned_) {
    // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
    tracked_objects::ScopedTracker tracking_profile(
        FROM_HERE_WITH_EXPLICIT_FUNCTION(
            "423948 FileStream::Context::OnOpenCompleted"));

    OnFileOpened();
  }

  OnAsyncCompleted(IntToInt64(callback), open_result.error_code);
}

void FileStream::Context::CloseAndDelete() {
  // TODO(ananta)
  // Replace this CHECK with a DCHECK once we figure out the root cause of
  // http://crbug.com/455066
  CHECK(!async_in_progress_);

  if (file_.IsValid()) {
    bool posted = task_runner_.get()->PostTask(
        FROM_HERE,
        base::Bind(base::IgnoreResult(&Context::CloseFileImpl),
                   base::Owned(this)));
    DCHECK(posted);
  } else {
    delete this;
  }
}

Int64CompletionCallback FileStream::Context::IntToInt64(
    const CompletionCallback& callback) {
  return base::Bind(&CallInt64ToInt, callback);
}

void FileStream::Context::OnAsyncCompleted(
    const Int64CompletionCallback& callback,
    const IOResult& result) {
  // Reset this before Run() as Run() may issue a new async operation. Also it
  // should be reset before Close() because it shouldn't run if any async
  // operation is in progress.
  async_in_progress_ = false;
  if (orphaned_)
    CloseAndDelete();
  else
    callback.Run(result.result);
}

}  // namespace net


text:
from google.apputils import app
import gflags
from ortools.constraint_solver import pywrapcp
from ortools.linear_solver import pywraplp

FLAGS = gflags.FLAGS
gflags.DEFINE_integer('load_min', 480, 'Minimum load in minutes')
gflags.DEFINE_integer('load_max', 540, 'Maximum load in minutes')
gflags.DEFINE_integer('commute_time', 30, 'Commute time in minutes')
gflags.DEFINE_integer('num_workers', 98, 'Maximum number of workers.')

def FindCombinations(durations, load_min, load_max, commute_time):
  """This methods find all valid combinations of appointments.

  This methods find all combinations of appointments such that the sum of
  durations + commute times is between load_min and load_max.

  Args:
    durations: The durations of all appointments.
    load_min: The min number of worked minutes for a valid selection.
    load_max: The max number of worked minutes for a valid selection.
    commute_time: The commute time between two appointments in minutes.
  Returns:
    A matrix where each line is a valid combinations of appointments.
  """
  solver = pywrapcp.Solver('FindCombinations')
  variables = [solver.IntVar(0, load_max / (i + commute_time))
               for i in durations]
  lengths = [i + commute_time for i in durations]
  solver.Add(solver.ScalProd(variables, lengths) >= load_min)
  solver.Add(solver.ScalProd(variables, lengths) <= load_max)
  db = solver.Phase(variables,
                    solver.CHOOSE_FIRST_UNBOUND,
                    solver.ASSIGN_MIN_VALUE)
  results = []
  solver.NewSearch(db)
  while solver.NextSolution():
    combination = [v.Value() for v in variables]
    results.append(combination)
  solver.EndSearch()
  return results

def Select(combinations, loads, max_number_of_workers):
  """This method selects the optimal combination of appointments.

  This method uses Mixed Integer Programming to select the optimal mix of
  appointments.
  """
  solver = pywraplp.Solver('Select',
                           pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
  num_vars = len(loads)
  num_combinations = len(combinations)
  variables = [solver.IntVar(0, max_number_of_workers, 's[%d]' % i)
               for i in range(num_combinations)]
  achieved = [solver.IntVar(0, 1000, 'achieved[%d]' % i)
              for i in range(num_vars)]
  transposed = [[combinations[type][index] for type in range(num_combinations)]
                for index in range(num_vars)]

  # Maintain the achieved variables.
  for i in range(len(transposed)):
    ct = solver.Constraint(0.0, 0.0)
    ct.SetCoefficient(achieved[i], -1)
    coefs = transposed[i]
    for j in range(len(coefs)):
      ct.SetCoefficient(variables[j], coefs[j])

  # Simple bound.
  solver.Add(solver.Sum(variables) <= max_number_of_workers)

  obj_vars = [solver.IntVar(0, 1000, 'obj_vars[%d]' % i)
              for i in range(num_vars)]
  for i in range(num_vars):
    solver.Add(obj_vars[i] >= achieved[i] - loads[i])
    solver.Add(obj_vars[i] >= loads[i] - achieved[i])

  solver.Minimize(solver.Sum(obj_vars))

  result_status = solver.Solve()

  # The problem has an optimal solution.
  if result_status == pywraplp.Solver.OPTIMAL:
    print 'Problem solved in %f milliseconds' % solver.WallTime()
    return solver.Objective().Value(), [int(v.SolutionValue())
                                        for v in variables]
  return -1, []

def GetOptimalSchedule(demand):
  """Computes the optimal schedule for the appointment selection problem."""
  combinations = FindCombinations([a[2] for a in demand],
                                  FLAGS.load_min,
                                  FLAGS.load_max,
                                  FLAGS.commute_time)
  print 'found %d possible combinations of appointements' % len(combinations)

  cost, selection = Select(combinations,
                           [a[0] for a in demand],
                           FLAGS.num_workers)
  output = [(selection[i], [(combinations[i][t], demand[t][1])
                            for t in range(len(demand))
                            if combinations[i][t] != 0])
            for i in range(len(selection)) if selection[i] != 0]
  return cost, output

def main(unused_argv):
  demand = [(40, 'A1', 90), (30, 'A2', 120), (25, 'A3', 180)]
  print 'appointments: '
  for a in demand:
    print '   %d * %s : %d min' % (a[0], a[1], a[2])
  print 'commute time = %d' % FLAGS.commute_time
  print 'accepted total duration = [%d..%d]' % (FLAGS.load_min, FLAGS.load_max)
  print '%d workers' % FLAGS.num_workers
  cost, selection = GetOptimalSchedule(demand)
  print 'Optimal solution as a cost of %d' % cost
  for template in selection:
    print '%d schedules with ' % template[0]
    for t in template[1]:
      print '   %d installation of type %s' % (t[0], t[1])

if __name__ == '__main__':
  app.run()


text:
@interface HXServerTime()

// 最后一次设置的时间
@property (nonatomic, assign) double lastTime;

// 最后一次设置时 系统启动的时间
@property (nonatomic, assign) double startTime;

@end

@implementation HXServerTime
singleton_m(HXServerTime);

- (double)serverTime
{
    // 取不到服务器时间,取本地时间
    if (self.lastTime == 0) {
        return [[NSDate date] timeIntervalSinceReferenceDate];
    }

    double currentTime = [[NSProcessInfo processInfo] systemUptime];
    return self.lastTime + ( currentTime - self.startTime );
}

//
- (void)setServerTime:(double)serverTime
{
    self.lastTime = serverTime;
    self.startTime = [[NSProcessInfo processInfo] systemUptime];
}

@end


text:
<?php

namespace ZendTest\I18n\Filter;

use Zend\I18n\Filter\Alnum as AlnumFilter;
use Locale;

/**
 * @group      Zend_Filter
 */
class AlnumTest extends \PHPUnit_Framework_TestCase
{
    /**
     * AlnumFilter object
     *
     * @var AlnumFilter
     */
    protected $filter;

    /**
     * Is PCRE is compiled with UTF-8 and Unicode support
     *
     * @var mixed
     **/
    protected static $unicodeEnabled;

    /**
     * Locale in browser.
     *
     * @var string object
     */
    protected $locale;

    /**
     * The Alphabet means english alphabet.
     *
     * @var bool
     */
    protected static $meansEnglishAlphabet;

    /**
     * Creates a new AlnumFilter object for each test method
     *
     * @return void
     */
    public function setUp()
    {
        if (!extension_loaded('intl')) {
            $this->markTestSkipped('ext/intl not enabled');
        }

        $this->filter = new AlnumFilter();

        $this->locale               = Locale::getDefault();
        $language                   = Locale::getPrimaryLanguage($this->locale);
        static::$meansEnglishAlphabet = in_array($language, ['ja']);
        static::$unicodeEnabled       = (bool) @preg_match('/\pL/u', 'a');
    }

    /**
     * Ensures that the filter follows expected behavior
     *
     * @return void
     */
    public function testBasic()
    {
        if (!static::$unicodeEnabled) {
            // POSIX named classes are not supported, use alternative a-zA-Z match
            $valuesExpected = [
                'abc123'  => 'abc123',
                'abc 123' => 'abc123',
                'abcxyz'  => 'abcxyz',
                'AZ@#4.3' => 'AZ43',
                ''        => ''
            ];
        } elseif (static::$meansEnglishAlphabet) {
            // The Alphabet means english alphabet.

            /**
             * The first element contains multibyte alphabets and digits.
             *  But , AlnumFilter is expected to return only singlebyte alphabets and digits.
             *
             * The second contains multibyte or singebyte space.
             * The third  contains various multibyte or singebyte characters.
             */
            $valuesExpected = [
                'aABb3456'  => 'aB35',
                'z7 Y8 x9'  => 'z8x',
                ',s1.2r3#:q,' => 's12rq',
            ];
        } else {
            //The Alphabet means each language's alphabet.
            $valuesExpected = [
                'abc123'        => 'abc123',
                'abc 123'       => 'abc123',
                'abcxyz'        => 'abcxyz',
                'če2t3ně'       => 'če2t3ně',
                'grz5e4gżółka'  => 'grz5e4gżółka',
                'Be3l5gië'      => 'Be3l5gië',
                ''              => ''
            ];
        }

        foreach ($valuesExpected as $input => $expected) {
            $actual = $this->filter->filter($input);
            $this->assertEquals($expected, $actual);
        }
    }

    /**
     * Ensures that the allowWhiteSpace option works as expected
     *
     * @return void
     */
    public function testAllowWhiteSpace()
    {
        $this->filter->setAllowWhiteSpace(true);

        if (!static::$unicodeEnabled) {
            // POSIX named classes are not supported, use alternative a-zA-Z match
            $valuesExpected = [
                'abc123'  => 'abc123',
                'abc 123' => 'abc 123',
                'abcxyz'  => 'abcxyz',
                'AZ@#4.3' => 'AZ43',
                ''        => '',
                "\n"      => "\n",
                " \t "    => " \t "
            ];
        } elseif (static::$meansEnglishAlphabet) {
            //The Alphabet means english alphabet.
            $valuesExpected = [
                'a B 45' => 'a B 5',
                'z3 x'   => 'z3x'
            ];
        } else {
            //The Alphabet means each language's alphabet.
            $valuesExpected = [
                'abc123'        => 'abc123',
                'abc 123'       => 'abc 123',
                'abcxyz'        => 'abcxyz',
                'če2 t3ně'      => 'če2 t3ně',
                'gr z5e4gżółka' => 'gr z5e4gżółka',
                'Be3l5 gië'     => 'Be3l5 gië',
                ''              => '',
            ];
        }

        foreach ($valuesExpected as $input => $expected) {
            $actual = $this->filter->filter($input);
            $this->assertEquals($expected, $actual);
        }
    }

    public function testFilterSupportArray()
    {
        $filter = new AlnumFilter();

        $values = [
            'abc123'  => 'abc123',
            'abc 123' => 'abc123',
            'abcxyz'  => 'abcxyz',
            'AZ@#4.3' => 'AZ43',
            ''        => ''
        ];

        $actual = $filter->filter(array_keys($values));

        $this->assertEquals(array_values($values), $actual);
    }

    public function returnUnfilteredDataProvider()
    {
        return [
            [null],
            [new \stdClass()]
        ];
    }

    /**
     * @dataProvider returnUnfilteredDataProvider
     * @return void
     */
    public function testReturnUnfiltered($input)
    {
        $filter = new AlnumFilter();

        $this->assertEquals($input,  $filter->filter($input));
    }
}


text:
package KD405A_gabrielsson_j_uppgift4B;

/** Abstrata klassen Mammal är en subklass till Animal */
public abstract class Mammal extends Animal {
	protected int gestationTime;

	public Mammal(String latinName, int gestationTime) {
		super(latinName);
		this.gestationTime = gestationTime;
	}

	public int getGestationTime() {
		return this.gestationTime;
	}
}


text:
package net.rdrei.android.wakimail.guice;

import android.app.ActionBar;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class ActionBarProvider implements Provider<ActionBar> {

	@Inject
	protected Activity activity;

	@Override
	public ActionBar get() {
		return ((FragmentActivity) activity).getActionBar();
	}
}


text:
package com.android21buttons.fragmenttestrule;

import androidx.test.rule.ActivityTestRule;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import android.util.Log;

/**
 * This rule provides functional testing of a single fragment.
 *

 * Idea extracted from: http://stackoverflow.com/a/38393087/842697
 *
 * @param  The container activity for the fragment under test
 * @param <F> The fragment under test
 */
public class FragmentTestRule extends ActivityTestRule {
    private static final String TAG = "FragmentTestRule";

    private final Class<F> fragmentClass;
    private final boolean launchFragment;
    private F fragment;

    /**
     * Creates an {@link FragmentTestRule} for the Fragment under test.
     *

     * This factory uses a standard Activity to launch the fragment. If you need a special Activity
     * use the constructors.
     *
     * @param fragmentClass The fragment under test
     * @return the fragmentTestRule
     * @see FragmentTestRule#FragmentTestRule(Class, Class)
     */
    public static <F extends Fragment> FragmentTestRule<?, F> create(Class<F> fragmentClass) {
        return new FragmentTestRule<>(FragmentActivity.class, fragmentClass);
    }

    /**
     * Creates an {@link FragmentTestRule} for the Fragment under test.
     *

     * This factory uses a standard Activity to launch the fragment. If you need a special Activity
     * use the constructors.
     *
     * @param fragmentClass    The fragment under test
     * @param initialTouchMode true if the Activity should be placed into "touch mode" when started
     * @return the fragmentTestRule
     * @see FragmentTestRule#FragmentTestRule(Class, Class, boolean)
     */
    public static <F extends Fragment> FragmentTestRule<?, F> create(Class<F> fragmentClass, boolean initialTouchMode) {
        return new FragmentTestRule<>(FragmentActivity.class, fragmentClass, initialTouchMode);
    }

    /**
     * Creates an {@link FragmentTestRule} for the Fragment under test.
     *

     * This factory uses a standard Activity to launch the fragment. If you need a special Activity
     * use the constructors.
     *
     * @param fragmentClass    The fragment under test
     * @param initialTouchMode true if the Activity should be placed into "touch mode" when started
     * @param launchFragment   true if the Fragment should be launched once per
     *
     *                         Test method. It will be launched before the first
     *
     *                         Before method, and terminated after the last
     *
     *                         After method.
     * @return the fragmentTestRule
     * @see FragmentTestRule#FragmentTestRule(Class, Class, boolean, boolean, boolean)
     */
    public static <F extends Fragment> FragmentTestRule<?, F> create(Class<F> fragmentClass, boolean initialTouchMode, boolean launchFragment) {
        return new FragmentTestRule<>(FragmentActivity.class, fragmentClass, initialTouchMode, true, launchFragment);
    }

    /**
     * Similar to {@link #FragmentTestRule(Class, Class, boolean)} but with "touch mode" disabled.
     *
     * @param activityClass The container activity for the fragment under test. This must be a class
     *                      in the instrumentation targetPackage specified in the
     *                      AndroidManifest.xml
     * @param fragmentClass The fragment under test
     * @see FragmentTestRule#FragmentTestRule(Class, Class, boolean)
     */
    public FragmentTestRule(Class activityClass, Class<F> fragmentClass) {
        this(activityClass, fragmentClass, false);
    }

    /**
     * Similar to {@link #FragmentTestRule(Class, Class, boolean, boolean)} but defaults to launch
     * the activity under test once per
     * Test method.
     * It is launched before the first
     * Before
     * method, and terminated after the last
     * After
     * method.
     *
     * @param activityClass    The container activity for the fragment under test. This must be a
     *                         class in the instrumentation targetPackage specified in the
     *                         AndroidManifest.xml
     * @param fragmentClass    The fragment under test
     * @param initialTouchMode true if the Activity should be placed into "touch mode" when started
     * @see FragmentTestRule#FragmentTestRule(Class, Class, boolean, boolean)
     */
    public FragmentTestRule(Class activityClass, Class<F> fragmentClass, boolean initialTouchMode) {
        this(activityClass, fragmentClass, initialTouchMode, true);
    }

    /**
     * Similar to {@link #FragmentTestRule(Class, Class, boolean, boolean, boolean)} but defaults to
     * launch the fragment under test once per
     * Test method.
     * It is launched before the first
     * Before
     * method, and terminated after the last
     * After
     * method.
     *
     * @param activityClass    The container activity for the fragment under test. This must be a
     *                         class in the instrumentation targetPackage specified in the
     *                         AndroidManifest.xml
     * @param fragmentClass    The fragment under test
     * @param initialTouchMode true if the Activity should be placed into "touch mode" when started
     * @param launchActivity   true if the Activity should be launched once per
     *
     *                         Test method. It will be launched before the first
     *
     *                         Before method, and terminated after the last
     *
     *                         After method.
     * @see FragmentTestRule#FragmentTestRule(Class, Class, boolean, boolean, boolean)
     */
    public FragmentTestRule(Class activityClass, Class<F> fragmentClass, boolean initialTouchMode, boolean launchActivity) {
        this(activityClass, fragmentClass, initialTouchMode, launchActivity, true);
    }

    /**
     * Creates an {@link FragmentTestRule} for the Fragment under test.
     *
     * @param activityClass    The container activity for the fragment under test. This must be a
     *                         class in the instrumentation targetPackage specified in the
     *                         AndroidManifest.xml
     * @param fragmentClass    The fragment under test
     * @param initialTouchMode true if the Activity should be placed into "touch mode" when started
     * @param launchActivity   true if the Activity should be launched once per
     *
     *                         Test method. It will be launched before the first
     *
     *                         Before method, and terminated after the last
     *
     *                         After method.
     * @param launchFragment   true if the Fragment should be launched once per
     *
     *                         Test method. It will be launched before the first
     *
     *                         Before method, and terminated after the last
     *
     *                         After method.
     */
    public FragmentTestRule(Class activityClass, Class<F> fragmentClass, boolean initialTouchMode, boolean launchActivity, boolean launchFragment) {
        super(activityClass, initialTouchMode, launchActivity);
        this.fragmentClass = fragmentClass;
        this.launchFragment = launchFragment;
    }

    @Override
    protected void afterActivityLaunched() {
        if (launchFragment) {
            launchFragment(createFragment());
        }
    }

    /**
     * Launches the Fragment under test.
     *

     * Don't call this method directly, unless you explicitly requested not to lazily launch the
     * Fragment manually using the launchFragment flag in
     * {@link FragmentTestRule#FragmentTestRule(Class, Class, boolean, boolean, boolean)}.
     *

     * Usage:
     *

     *    @Test
     *    public void customIntentToStartActivity() {
     *        Fragment fragment = MyFragment.newInstance();
     *        fragmentRule.launchFragment(fragment);
     *    }
     *

     *
     * @param fragment The Fragment under test. If {@code fragment} is null, the fragment returned
     *                 by {@link FragmentTestRule#createFragment()} is used.
     * @see FragmentTestRule#createFragment()
     */
    public void launchFragment(final F fragment) {
        try {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    final F fragment2 = fragment == null ? createFragment() : fragment;
                    FragmentTestRule.this.fragment = fragment2;
                    getActivity().getSupportFragmentManager()
                            .beginTransaction()
                            .replace(android.R.id.content, fragment2)
                            .commitNow();
                }
            });
        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
        }
    }

    /**
     * Override this method to set up the desired Fragment.
     *

     * The default Fragment (if this method returns null or is not overwritten) is:
     * fragmentClass.newInstance()
     *
     * @return the fragment to test.
     */
    protected F createFragment() {
        try {
            return fragmentClass.newInstance();
        } catch (InstantiationException e) {
            throw new AssertionError(String.format("%s: Could not insert %s into %s: %s",
                    getClass().getSimpleName(),
                    fragmentClass.getSimpleName(),
                    getActivity().getClass().getSimpleName(),
                    e.getMessage()));
        } catch (IllegalAccessException e) {
            throw new AssertionError(String.format("%s: Could not insert %s into %s: %s",
                    getClass().getSimpleName(),
                    fragmentClass.getSimpleName(),
                    getActivity().getClass().getSimpleName(),
                    e.getMessage()));
        }
    }

    /**
     * @return The fragment under test.
     */
    public F getFragment() {
        if (fragment == null) {
            Log.w(TAG, "Fragment wasn't created yet");
        }
        return fragment;
    }
}