text:
# grunt-generator

Static site generator for Grunt supporting Handlebars, DustJS and custom template engines and authoring pages using HTML, markdown (showdown library), etc.

## Getting Started
Install this grunt plugin next to your project's [grunt.js gruntfile][getting_started] with: `npm install grunt-generator`

Then add this line to your project's `Gruntfile.js` gruntfile:

```javascript
grunt.loadNpmTasks('grunt-generator');
```

[grunt]: http://gruntjs.com/
[getting_started]: https://github.com/gruntjs/grunt/blob/master/docs/getting_started.md

## Documentation

Assuming the following your `Gruntfile.js`:

```javascript

var helpers = require('helpers');

grunt.initconfig({
  generator: {
    dev: {
      files: [
        { cwd: 'pages', src: ['**/*'], dest: 'build', ext: '.html' }
      ],
      options: {
        partialsGlob: 'pages/partials/*.html',
        templates: 'templates',
        handlebarshelpers: helpers,
        environment: 'dev'
      }
    }
  }
...

```

and the following in `helpers.js`:

```javascript
module.exports = {
  'test': function(s) {
    return "test " + s;
  }
};
```
grunt-generator will build HTML and markdown pages in the `pages/` directory. Outputting generated pages to `build/`. Each 'page' is run through handlebars.js and has access to the helpers specified above (in the example: helpers.js). Each page also has access to the optional metadata that can be specified at the top of every page as a JSON fragment:

```javascript
{
  "title" : "Test Title"
}
---

<div class="content">
...
```

A pages own metadata is available as the `page` variable. In addition all other pages can be accessed using the `pages` collection available to all pages. Using the above example: if the page is located at `dir1/test1.html` then it's title can be accessed using a handlebars helper like so:

```javascript
...

// example: {{ pageTitle 'dir1/test1' }}
'pageTitle': function(pageName) {
    return (this.pages[pageName] ? this.pages[pageName].title : "");
}

...
```

Since all metadata is available to all pages (and their templates) at build time complex processing can be done using handlebars helpers such as navigation hierarchies, tagging/categories, etc.

The templates in `templates/` will be used to render the final output and are also passed through handlebars.js. The templates are given a special variable `body` which is the rendered output of the current 'page' (**Note**: Make sure you use the "triple-stash" expression for `body`, so Handlebars doesn't escape the HTML: `{{{ body }}}`). To specify a non-default template for a page use the `template` metadata. The following will render using alternate.html as the template instead of the default (ie. index.html):

```javascript
{
  "title": "Test title",
  "template" : "alternate"
}
---

<div class....
```

Handlebars partials can be specified using the `partialsGlob` option. These will be available to all pages using their filename minus extension. Partials can be placed in the same directory as pages and will not be processed as unique pages.

See the `spec/pages` and `spec/templates` directory for a complete example.

### DustJS and Custom Template Engine Support

As of version `0.3.0` the template engine used can be changed to DustJS or overridden with your own custom template function:

#### Dust Templates

DustJS templates have a number of advantages such as supporting async helpers and better access to the context in helper functions. Remember to turn off escaping of the body content in your templates: `{body|s}`.

```javascript
  generator: {
    dev: {
      files: [
        { cwd: 'pages', src: ['**/*'], dest: 'build', ext: '.html' }
      ],
      options: {
        templateEngine: 'dust',
        templates: 'templates',
        helpers: helpers,
        environment: 'dev'
      }
    }
  }
...
```

Note: Dust templates support the dust partials syntax but it is not recommended to mix HTML/Markdown partials. Since the markdown compilation for pages occurs after the partials are processed HTML partials mixed into Markdown pages may produce undesired results.

#### Custom

Custom template functions must return the rendered template as a string or a promise-like object that resolves to the rendered template (or rejects). You may also throw an exception on error. Return a promise object if you need to perform asynchronous tasks. Note that the template function will be called *twice* for each page: once for the page itself and again when it is rendered into the template. grunt-generator uses the [Q library][q] for it's promises

```javascript
  generator: {
    dev: {
      files: [
        { cwd: 'pages', src: ['**/*'], dest: 'build', ext: '.html' }
      ],
      options: {
        templates: 'templates',
        helpers: helpers,
        environment: 'dev',
        templateEngine: function(content, context) {
          // custom template engines must return the output as a string
          // a promise, or throw an exception on error
          return "Hello, " + context.name + "\n" + content;
        }
      }
    }
  }
...
```

##### Custom Frontmatter

The frontmatter can be changed to use custom delimiters and also to use YAML syntax instead of JSON:

```javascript
  generator: {
    dev: {
      files: [
        { cwd: 'pages', src: ['**/*'], dest: 'build', ext: '.html' }
      ],
      options: {
        templates: 'templates',
        helpers: helpers,
        environment: 'dev',
        frontmatterDelimiter: '###',
        frontmatterType: 'yaml'
      }
    }
  }
...
```

[q]: [https://github.com/kriskowal/q/]

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt][grunt].

## Release History

See CHANGELOG.md

## License
Copyright (c) 2012 Charles Lavery
Licensed under the MIT license.


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<display-name>Demo - Restful Web Application</display-name>

	<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
		    classpath:spring/applicationContext.xml
		    classpath:spring/security-context.xml
		</param-value>
	</context-param>

	<servlet>
		<servlet-name>jersey-servlet</servlet-name>
		<servlet-class>
			org.glassfish.jersey.servlet.ServletContainer
		</servlet-class>
		<init-param>
			<param-name>javax.ws.rs.Application</param-name>
			<param-value>atom.demo.resource.RestJaxRsResourceConfig</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>jersey-servlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

    <!--Hook into spring security-->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/api/*</url-pattern>
    </filter-mapping>

	<resource-ref>
        <description>Database resource for rest web application </description>
        <res-ref-name>jdbc/bf</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
</web-app>

redpajama_set_name: RedPajamaGithub


text:
{% extends 'plain_layout.html' %}
{% block title %}
    The Title | {{super()}}
{% endblock %}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: Number.POSITIVE_INFINITY is +Infinity
es5id: 15.7.3.6_A1
description: Checking sign and finiteness of Number.POSITIVE_INFINITY
---*/

// CHECK#1
if (isFinite(Number.POSITIVE_INFINITY) !== false) {
  $ERROR('#1: Number.POSITIVE_INFINITY === Not-a-Finite');
} else {
  if ((Number.POSITIVE_INFINITY > 0) !== true) {
    $ERROR('#1: Number.POSITIVE_INFINITY === +Infinity');
  }
}


text:
package com.encoway.edu;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

/**
 * Page representing the demo for EDU.
 */
public class DemoPage extends AbstractPage<DemoPage> {

    @FindBy(xpath = "//form//input[@type='submit' and contains(@value, 'String')]")
    WebElement stringButton;

    @FindBy(xpath = "//form//input[@type='submit' and contains(@value, 'Integer')]")
    WebElement integerButton;

    @FindBy(xpath = "//form//a[contains(text(), 'Reset')]")
    WebElement resetLink;

    /**
     * Initializes a {@link DemoPage}.
     *
     * @param driver the driver used when interacting with this page
     */
    public DemoPage(WebDriver driver) {
        super(driver, "demo.xhtml");
    }

    /**
     * Clicks the "Update String" button.
     */
    public void updateStringValue() {
        clickAndWait(stringButton);
    }

    public void updateStringValue(String value) {
        getStringInput().click();
        getStringInput().sendKeys(value, Keys.TAB);
        getStringOutputText().click();
        wait(2);
    }

    /**
     * Clicks the "Update Integer" button.
     */
    public void updateIntegerValue() {
        clickAndWait(integerButton);
    }

    public void updateIntegerValue(Integer value) {
        getIntegerInput().click();
        getIntegerInput().sendKeys(value.toString(), Keys.TAB);
        getIntegerOutputText().click();
        wait(2);
    }

    /**
     * Clicks the reset link.
     */
    public void reset() {
        clickAndWait(resetLink);
    }

    public WebElement getStringOutputText() {
        return driver.findElement(By.id("hybridStringOutput"));
    }

    public WebElement getIntegerOutputText() {
        return driver.findElement(By.id("hybridIntOutput"));
    }

    public WebElement getStringInput() {
        return driver.findElement(By.xpath("//form//input[@type='text']"));
    }

    public WebElement getIntegerInput() {
        return driver.findElement(By.xpath("//form//input[@type='number']"));
    }

}


text:
module TrelloLeadTime
  module ArraySearcher
    def find_name_like(elements, name)
      elements.detect { |element| element_matches_expression?(element, name) }
    end

    def element_matches_expression?(element, expression)
      element =~ /#{Regexp.quote(expression)}/
    end
  end
end


text:
package com.chenantao.playtogether.chat.mvc.view.adapter;

import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.chenantao.autolayout.utils.AutoUtils;
import com.chenantao.playtogether.R;
import com.chenantao.playtogether.gallery.MyGalleryAdapter;
import com.jakewharton.rxbinding.view.RxView;
import com.squareup.picasso.Picasso;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * Created by Chenantao_gg on 2016/1/23.
 */
public class SelectPicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
{
	public static final int TYPE_ITEM_PIC = 0;
	public static final int TYPE_ITEM_FOOTER = 1;
	private Context mContext;
	private List<String> mDatas;//datas不包含footer,所以要记得做相应的加减
	private int mCount = 0;//有包含footer的数量

	public SelectPicAdapter(Context context, List<String> pathDatas)
	{
		mContext = context;
		mDatas = pathDatas;
		mCount = mDatas.size() + 1;
	}

	private boolean isFooter(int position)
	{
		return position == mCount - 1;
	}

	@Override
	public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
	{
		if (viewType == TYPE_ITEM_FOOTER)
		{
			return new FooterViewHolder(LayoutInflater.from(mContext).inflate(R.layout
							.item_select_pic_footer, parent, false));
		} else
		{
			return new SelectPicViewHolder(LayoutInflater.from(mContext).inflate(R.layout
											.item_select_pic, parent, false
			));
		}
	}

	@Override
	public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position)
	{
		AutoUtils.autoSize(holder.itemView);
		if (isFooter(position))
		{
			return;
		}
		final String path = mDatas.get(position);
		SelectPicViewHolder selectViewHolder = (SelectPicViewHolder) holder;
		ImageView ivPic = selectViewHolder.ivPic;
		int width = ivPic.getLayoutParams().width;
		int height = ivPic.getLayoutParams().height;
		Uri uri = Uri.parse("file:///" + path);
		Picasso.with(mContext)
						.load(uri)
						.placeholder(R.mipmap.pictures_no)
						.resize(width, height)
						.into(ivPic);
		ImageView ivDel = selectViewHolder.ivDel;
		//防止重复点击
		RxView.clicks(ivDel)
						.throttleFirst(500, TimeUnit.SECONDS)
						.subscribe(new Action1<Void>()
						{
							@Override
							public void call(Void aVoid)
							{
								notifyItemRemoved(holder.getAdapterPosition());
								MyGalleryAdapter.mSelectedImgs.remove(path);
								mCount = mCount - 1;
							}
						});
	}

	@Override
	public int getItemCount()
	{
		return mCount;
	}

	@Override
	public int getItemViewType(int position)
	{
		return position == mCount - 1 ? TYPE_ITEM_FOOTER : TYPE_ITEM_PIC;
	}

	class FooterViewHolder extends RecyclerView.ViewHolder
	{

		public FooterViewHolder(View itemView)
		{
			super(itemView);

		}
	}

	class SelectPicViewHolder extends RecyclerView.ViewHolder
	{
		@Bind(R.id.ivPic)
		public ImageView ivPic;
		@Bind(R.id.ivDel)
		public ImageView ivDel;

		public SelectPicViewHolder(View itemView)
		{
			super(itemView);
			ButterKnife.bind(this, itemView);
		}
	}
}


text:
package org.apache.camel.component.cxf;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.attachment.AttachmentMessage;
import org.apache.camel.component.cxf.common.message.CxfConstants;
import org.apache.camel.converter.IOConverter;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.HeaderFilterStrategy;
import org.apache.camel.support.DefaultExchange;
import org.apache.camel.support.DefaultHeaderFilterStrategy;
import org.apache.camel.support.ExchangeHelper;
import org.apache.cxf.attachment.AttachmentImpl;
import org.apache.cxf.binding.Binding;
import org.apache.cxf.binding.soap.SoapBindingConstants;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.message.Attachment;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class DefaultCxfBindingTest {

    private static final String SOAP_MESSAGE_1 = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\""
                                                 + " xmlns=\"http://www.mycompany.com/test/\" xmlns:ns1=\"http://www.mycompany.com/test/1/\">"
                                                 + " <soap:Body> <request> <ns1:identifier>TEST</ns1:identifier> </request>"
                                                 + " </soap:Body> </soap:Envelope>";

    private static final String SOAP_MESSAGE_2 = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\""
                                                 + " xmlns=\"http://www.mycompany.com/test/\" xmlns:ns1=\"http://www.mycompany.com/test/1/\">"
                                                 + " <soap:Body> <ns1:identifier xmlns:ns1=\"http://www.mycompany.com/test/\" xmlns=\"http://www.mycompany.com/test/1/\">TEST</ns1:identifier>"
                                                 + " </soap:Body> </soap:Envelope>";

    private DefaultCamelContext context;

    @BeforeEach
    protected void setUp() throws Exception {
        context = new DefaultCamelContext();
        context.start();
    }

    @Test
    public void testSetGetHeaderFilterStrategy() {
        DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
        HeaderFilterStrategy hfs = new DefaultHeaderFilterStrategy();

        cxfBinding.setHeaderFilterStrategy(hfs);
        assertSame(hfs, cxfBinding.getHeaderFilterStrategy(), "The header filter strategy is set");
    }

    private Document getDocument(String soapMessage) throws Exception {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(IOConverter.toInputStream(soapMessage, null));
        document.getDocumentElement().normalize();

        return document;
    }

    @Test
    public void testPayloadBodyNamespace() throws Exception {
        MessageImpl message = new MessageImpl();
        Map<String, String> nsMap = new HashMap<>();
        Document document = getDocument(SOAP_MESSAGE_1);
        message.setContent(Node.class, document);
        DefaultCxfBinding.getPayloadBodyElements(message, nsMap);

        assertEquals(2, nsMap.size());
        assertEquals("http://www.mycompany.com/test/", nsMap.get("xmlns"));

        Element element = document.createElement("tag");
        DefaultCxfBinding.addNamespace(element, nsMap);
        assertEquals("http://www.mycompany.com/test/", element.getAttribute("xmlns"));
        assertEquals("http://www.mycompany.com/test/1/", element.getAttribute("xmlns:ns1"));
    }

    @Test
    public void testOverridePayloadBodyNamespace() throws Exception {
        MessageImpl message = new MessageImpl();
        Map<String, String> nsMap = new HashMap<>();
        Document document = getDocument(SOAP_MESSAGE_2);
        message.setContent(Node.class, document);
        DefaultCxfBinding.getPayloadBodyElements(message, nsMap);

        assertEquals(2, nsMap.size());
        assertEquals("http://www.mycompany.com/test/", nsMap.get("xmlns"));

        Element element = (Element) document.getElementsByTagName("ns1:identifier").item(0);
        assertNotNull(element, "We should get the element");
        DefaultCxfBinding.addNamespace(element, nsMap);
        assertEquals("http://www.mycompany.com/test/1/", element.getAttribute("xmlns"));
        assertEquals("http://www.mycompany.com/test/", element.getAttribute("xmlns:ns1"));
    }

    @Test
    public void testSetCharsetWithContentType() {
        DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
        cxfBinding.setHeaderFilterStrategy(new DefaultHeaderFilterStrategy());
        Exchange exchange = new DefaultExchange(context);
        exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/xml;charset=ISO-8859-1");
        cxfBinding.setCharsetWithContentType(exchange);

        String charset = ExchangeHelper.getCharsetName(exchange);
        assertEquals("ISO-8859-1", charset, "Get a wrong charset");

        exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/xml");
        cxfBinding.setCharsetWithContentType(exchange);
        charset = ExchangeHelper.getCharsetName(exchange);
        assertEquals("UTF-8", charset, "Get a worng charset name");
    }

    @Test
    public void testPopulateCxfRequestFromExchange() {
        DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
        cxfBinding.setHeaderFilterStrategy(new DefaultHeaderFilterStrategy());
        Exchange exchange = new DefaultExchange(context);
        org.apache.cxf.message.Exchange cxfExchange = new org.apache.cxf.message.ExchangeImpl();
        exchange.setProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.PAYLOAD);
        Map<String, Object> requestContext = new HashMap<>();

        exchange.getIn().setHeader("soapAction", "urn:hello:world");
        exchange.getIn().setHeader("MyFruitHeader", "peach");
        exchange.getIn().setHeader("MyBrewHeader", Arrays.asList("cappuccino", "espresso"));
        exchange.getIn(AttachmentMessage.class).addAttachment("att-1", new DataHandler(new FileDataSource("pom.xml")));
        exchange.getIn(AttachmentMessage.class).getAttachmentObject("att-1").setHeader("attachment-header", "value 1");

        cxfBinding.populateCxfRequestFromExchange(cxfExchange, exchange, requestContext);

        // check the protocol headers
        Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) requestContext.get(Message.PROTOCOL_HEADERS));
        assertNotNull(headers);
        assertEquals(3, headers.size());

        verifyHeader(headers, "soapaction", "urn:hello:world");
        verifyHeader(headers, "SoapAction", "urn:hello:world");
        verifyHeader(headers, "SOAPAction", "urn:hello:world");
        verifyHeader(headers, "myfruitheader", "peach");
        verifyHeader(headers, "myFruitHeader", "peach");
        verifyHeader(headers, "MYFRUITHEADER", "peach");
        verifyHeader(headers, "MyBrewHeader", Arrays.asList("cappuccino", "espresso"));

        Set<Attachment> attachments
                = CastUtils.cast((Set<?>) requestContext.get(CxfConstants.CAMEL_CXF_ATTACHMENTS));
        assertNotNull(attachments);
        assertEquals(1, attachments.size());
        Attachment att = attachments.iterator().next();
        assertEquals("att-1", att.getId());
        assertEquals("value 1", att.getHeader("attachment-header"));
    }

    @Test
    public void testPopulateCxfSoapHeaderRequestFromExchange() {
        DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
        cxfBinding.setHeaderFilterStrategy(new DefaultHeaderFilterStrategy());
        Exchange exchange = new DefaultExchange(context);
        org.apache.cxf.message.Exchange cxfExchange = new org.apache.cxf.message.ExchangeImpl();
        Map<String, Object> requestContext = new HashMap<>();

        String expectedSoapActionHeader = "urn:hello:world";
        exchange.getIn().setHeader("soapAction", expectedSoapActionHeader);

        cxfBinding.populateCxfRequestFromExchange(cxfExchange, exchange, requestContext);

        String actualSoapActionHeader = (String) requestContext.get(SoapBindingConstants.SOAP_ACTION);
        assertEquals(expectedSoapActionHeader, actualSoapActionHeader);
    }

    @Test
    public void testPopulateCxfSoapHeaderRequestFromExchangeWithExplicitOperationName() {
        DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
        cxfBinding.setHeaderFilterStrategy(new DefaultHeaderFilterStrategy());
        Exchange exchange = new DefaultExchange(context);
        org.apache.cxf.message.Exchange cxfExchange = new org.apache.cxf.message.ExchangeImpl();
        Map<String, Object> requestContext = new HashMap<>();

        exchange.getIn().setHeader(CxfConstants.OPERATION_NAMESPACE, "http://test123");
        exchange.getIn().setHeader(CxfConstants.OPERATION_NAME, "testOperation");

        cxfBinding.populateCxfRequestFromExchange(cxfExchange, exchange, requestContext);

        String actualSoapActionHeader = (String) requestContext.get(SoapBindingConstants.SOAP_ACTION);
        assertNull(actualSoapActionHeader);
    }

    @Test
    public void testPopupalteExchangeFromCxfResponse() {
        DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
        cxfBinding.setHeaderFilterStrategy(new DefaultHeaderFilterStrategy());
        Exchange exchange = new DefaultExchange(context);
        org.apache.cxf.message.Exchange cxfExchange = new org.apache.cxf.message.ExchangeImpl();
        exchange.setProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.PAYLOAD);
        Map<String, Object> responseContext = new HashMap<>();
        responseContext.put(org.apache.cxf.message.Message.RESPONSE_CODE, Integer.valueOf(200));
        Map<String, List<String>> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        headers.put("content-type", Arrays.asList("text/xml;charset=UTF-8"));
        headers.put("Content-Length", Arrays.asList("241"));
        responseContext.put(org.apache.cxf.message.Message.PROTOCOL_HEADERS, headers);
        org.apache.cxf.message.Message cxfMessage = new org.apache.cxf.message.MessageImpl();
        cxfExchange.setInMessage(cxfMessage);

        Set<Attachment> attachments = new HashSet<>();
        AttachmentImpl attachment = new AttachmentImpl("att-1", new DataHandler(new FileDataSource("pom.xml")));
        attachment.setHeader("additional-header", "value 1");
        attachments.add(attachment);
        cxfMessage.setAttachments(attachments);

        cxfBinding.populateExchangeFromCxfResponse(exchange, cxfExchange, responseContext);

        Map<String, Object> camelHeaders = exchange.getMessage().getHeaders();
        assertNotNull(camelHeaders);
        assertEquals(responseContext, camelHeaders.get(Client.RESPONSE_CONTEXT));

        Map<String, org.apache.camel.attachment.Attachment> camelAttachments
                = exchange.getMessage(AttachmentMessage.class).getAttachmentObjects();
        assertNotNull(camelAttachments);
        assertNotNull(camelAttachments.get("att-1"));
        assertEquals("value 1", camelAttachments.get("att-1").getHeader("additional-header"));
    }

    @Test
    public void testPopupalteExchangeFromCxfResponseOfNullBody() {
        DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
        cxfBinding.setHeaderFilterStrategy(new DefaultHeaderFilterStrategy());
        Exchange exchange = new DefaultExchange(context);
        org.apache.cxf.message.Exchange cxfExchange = new org.apache.cxf.message.ExchangeImpl();
        exchange.setProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.PAYLOAD);
        Map<String, Object> responseContext = new HashMap<>();
        responseContext.put(org.apache.cxf.message.Message.RESPONSE_CODE, Integer.valueOf(200));
        Map<String, List<String>> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        responseContext.put(org.apache.cxf.message.Message.PROTOCOL_HEADERS, headers);
        org.apache.cxf.message.Message cxfMessage = new org.apache.cxf.message.MessageImpl();
        cxfExchange.setInMessage(cxfMessage);

        cxfBinding.populateExchangeFromCxfResponse(exchange, cxfExchange, responseContext);

        CxfPayload<?> cxfPayload = exchange.getMessage().getBody(CxfPayload.class);

        assertNotNull(cxfPayload);
        List<?> body = cxfPayload.getBody();
        assertNotNull(body);
        assertEquals(0, body.size());
    }

    @Test
    public void testPopupalteCxfResponseFromExchange() {
        DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
        cxfBinding.setHeaderFilterStrategy(new DefaultHeaderFilterStrategy());
        Exchange exchange = new DefaultExchange(context, ExchangePattern.InOut);
        org.apache.cxf.message.Exchange cxfExchange = new org.apache.cxf.message.ExchangeImpl();
        exchange.setProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.PAYLOAD);

        exchange.getMessage().setHeader("soapAction", "urn:hello:world");
        exchange.getMessage().setHeader("MyFruitHeader", "peach");
        exchange.getMessage(AttachmentMessage.class).addAttachment("att-1", new DataHandler(new FileDataSource("pom.xml")));
        exchange.getMessage(AttachmentMessage.class).getAttachmentObject("att-1").setHeader("attachment-header", "value 1");

        Endpoint endpoint = mock(Endpoint.class);
        Binding binding = mock(Binding.class);
        when(endpoint.getBinding()).thenReturn(binding);
        org.apache.cxf.message.Message cxfMessage = new org.apache.cxf.message.MessageImpl();
        when(binding.createMessage()).thenReturn(cxfMessage);
        cxfExchange.put(Endpoint.class, endpoint);

        cxfBinding.populateCxfResponseFromExchange(exchange, cxfExchange);

        cxfMessage = cxfExchange.getOutMessage();
        assertNotNull(cxfMessage);

        Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) cxfMessage.get(Message.PROTOCOL_HEADERS));
        assertNotNull(headers);
        assertEquals(2, headers.size());

        verifyHeader(headers, "soapaction", "urn:hello:world");
        verifyHeader(headers, "SoapAction", "urn:hello:world");
        verifyHeader(headers, "SOAPAction", "urn:hello:world");
        verifyHeader(headers, "myfruitheader", "peach");
        verifyHeader(headers, "myFruitHeader", "peach");
        verifyHeader(headers, "MYFRUITHEADER", "peach");

        Collection<Attachment> attachments = cxfMessage.getAttachments();
        assertNotNull(attachments);
        assertEquals(1, attachments.size());
        Attachment att = attachments.iterator().next();
        assertEquals("att-1", att.getId());
        assertEquals("value 1", att.getHeader("attachment-header"));
    }

    @Test
    public void testPopupalteExchangeFromCxfRequest() {
        DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
        cxfBinding.setHeaderFilterStrategy(new DefaultHeaderFilterStrategy());
        Exchange exchange = new DefaultExchange(context);
        org.apache.cxf.message.Exchange cxfExchange = new org.apache.cxf.message.ExchangeImpl();
        exchange.setProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.PAYLOAD);
        org.apache.cxf.message.Message cxfMessage = new org.apache.cxf.message.MessageImpl();
        Map<String, List<String>> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        headers.put("content-type", Arrays.asList("text/xml;charset=UTF-8"));
        headers.put("Content-Length", Arrays.asList("241"));
        headers.put("soapAction", Arrays.asList("urn:hello:world"));
        headers.put("myfruitheader", Arrays.asList("peach"));
        headers.put("mybrewheader", Arrays.asList("cappuccino", "espresso"));
        cxfMessage.put(org.apache.cxf.message.Message.PROTOCOL_HEADERS, headers);

        Set<Attachment> attachments = new HashSet<>();
        AttachmentImpl attachment = new AttachmentImpl("att-1", new DataHandler(new FileDataSource("pom.xml")));
        attachment.setHeader("attachment-header", "value 1");
        attachments.add(attachment);
        cxfMessage.setAttachments(attachments);

        cxfExchange.setInMessage(cxfMessage);

        cxfBinding.populateExchangeFromCxfRequest(cxfExchange, exchange);

        Map<String, Object> camelHeaders = exchange.getIn().getHeaders();
        assertNotNull(camelHeaders);
        assertEquals("urn:hello:world", camelHeaders.get("soapaction"));
        assertEquals("urn:hello:world", camelHeaders.get("SoapAction"));
        assertEquals("text/xml;charset=UTF-8", camelHeaders.get("content-type"));
        assertEquals("241", camelHeaders.get("content-length"));
        assertEquals("peach", camelHeaders.get("MyFruitHeader"));
        assertEquals(Arrays.asList("cappuccino", "espresso"), camelHeaders.get("MyBrewHeader"));

        Map<String, org.apache.camel.attachment.Attachment> camelAttachments
                = exchange.getIn(AttachmentMessage.class).getAttachmentObjects();
        assertNotNull(camelAttachments);
        assertNotNull(camelAttachments.get("att-1"));
        assertEquals("value 1", camelAttachments.get("att-1").getHeader("attachment-header"));
    }

    @Test
    public void testPopupalteExchangeFromCxfRequestWithHeaderMerged() {
        DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
        cxfBinding.setHeaderFilterStrategy(new DefaultHeaderFilterStrategy());
        Exchange exchange = new DefaultExchange(context);
        exchange.setProperty(CxfConstants.CAMEL_CXF_PROTOCOL_HEADERS_MERGED, Boolean.TRUE);
        org.apache.cxf.message.Exchange cxfExchange = new org.apache.cxf.message.ExchangeImpl();
        exchange.setProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.PAYLOAD);
        org.apache.cxf.message.Message cxfMessage = new org.apache.cxf.message.MessageImpl();
        Map<String, List<String>> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        headers.put("myfruitheader", Arrays.asList("peach"));
        headers.put("mybrewheader", Arrays.asList("cappuccino", "espresso"));
        cxfMessage.put(org.apache.cxf.message.Message.PROTOCOL_HEADERS, headers);

        cxfExchange.setInMessage(cxfMessage);

        cxfBinding.populateExchangeFromCxfRequest(cxfExchange, exchange);

        Map<String, Object> camelHeaders = exchange.getIn().getHeaders();
        assertNotNull(camelHeaders);
        assertEquals("peach", camelHeaders.get("MyFruitHeader"));
        assertEquals("cappuccino, espresso", camelHeaders.get("MyBrewHeader"));
    }

    private void verifyHeader(Map<String, List<String>> headers, String name, List<String> value) {
        List<String> values = headers.get(name);
        assertTrue(values != null && values.size() == ((List<?>) value).size(), "The entry must be available");
        assertEquals(value, values, "The value must match");
    }

    private void verifyHeader(Map<String, List<String>> headers, String name, String value) {
        List<String> values = headers.get(name);
        assertTrue(values != null && values.size() == 1, "The entry must be available");
        assertEquals(values.get(0), value, "The value must match");
    }

}


text:
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Metadata;
using Avalonia.Styling;

namespace Avalonia.Markup.Xaml.Templates
{
    public class ControlTemplate : IControlTemplate
    {
        [Content]
        public TemplateContent Content { get; set; }

        public IControl Build(ITemplatedControl control)
        {
            return Content.Load();
        }
    }
}


text:
///<reference path='../cheese/cheese.d.ts' />
///<reference path='references.ts' />
var ResourceService = (function () {
    function ResourceService($injector, $resource) {
        var _this = this;
        this.metadata = [];
        "use strict";
        this.config = $injector.get('ApplicationConfig');
        this.name = "elastic";
        this.type = "nosql";
        this.$injector = $injector;
        this.resource = $resource('', {}, {
            create: {
                url: this.config.elasticsearchBasePath + ':resourceName/:id',
                method: 'POST',
                params: { docId: '@id' }
            },
            update: {
                url: this.config.elasticsearchBasePath + ':resourceName/:id',
                method: 'PUT',
                params: { docId: '@id' },
                transformResponse: function (data) {
                    var response = angular.fromJson(data);
                    //console.log(response);
                }
            },
            delete: {
                url: this.config.elasticsearchBasePath + ':resourceName/:id',
                method: 'DELETE',
                params: { docId: '@id' },
                transformResponse: function (data) {
                    var response = angular.fromJson(data);
                    response.id = response._id;
                    return response;
                }
            },
            query: {
                url: this.config.elasticsearchBasePath + ':resourceName/_search',
                method: 'GET',
                isArray: true,
                transformResponse: function (data) {
                    //console.log(data);
                    var response = angular.fromJson(data);

                    //console.log(response);
                    var result = [];
                    for (var i = 0, max = response.hits.total; i < max; i++) {
                        var item = response.hits.hits[i];
                        if (item) {
                            var source = item._source;
                            if (source) {
                                source["id"] = item._id;
                                result.push(source);
                            }
                        }
                    }
                    return result;
                },
                interceptor: {
                    response: function (httpResponse) {
                        return _this.onGetListSuccess(httpResponse);
                    },
                    responseError: function (httpResponse) {
                        return this.onGetListError(httpResponse);
                    }
                }
            },
            get: {
                url: this.config.elasticsearchBasePath + ':resourceName/:docId',
                method: 'GET',
                params: { docId: '@id' },
                transformResponse: function (data) {
                    var response = angular.fromJson(data);
                    var result = response._source;
                    result["id"] = response._id;

                    //console.log(result);
                    return result;
                }
            },
            counter: {
                url: this.config.elasticsearchBasePath + 'counters/:resourceName',
                method: 'PUT',
                params: { resourceName: '@resourceName' }
            }
        });
    }
    ResourceService.prototype.onGetListSuccess = function (httpResponse) {
        this.items = httpResponse.data;
        return this.items;
    };

    ResourceService.prototype.onGetListError = function (httpResponse) {
        return httpResponse.data;
    };

    ResourceService.prototype.getList = function (params) {
        "use strict";
        var q = "";
        if (params.searchModel) {
            for (var prop in params.searchModel) {
                if (params.searchModel[prop]) {
                    q += "+" + prop + ":" + params.searchModel[prop] + " ";
                }
            }
        }

        //console.log("q="+q);
        var queryParams = { resourceName: params.resourceName };
        if (q) {
            queryParams["q"] = q;
        }
        queryParams["size"] = 1000000;
        return this.resource.query(queryParams).$promise;
    };

    ResourceService.prototype.createItem = function (params, item) {
        var _this = this;
        "use strict";

        //var _this = this;
        if (item.id) {
            return this.resource.create({ resourceName: params.resourceName }, item).$promise;
        } else {
            return this.resource.counter({}, { resourceName: params.resourceName }).$promise.then(function (data) {
                item.id = '' + data._version;
                return _this.resource.create({ resourceName: params.resourceName }, item).$promise;
            });
        }
    };

    ResourceService.prototype.getItem = function (params) {
        "use strict";
        return this.resource.get({ resourceName: params.resourceName }, { id: params.id }).$promise;
    };

    ResourceService.prototype.updateItem = function (params, item) {
        "use strict";
        return this.resource.update({ resourceName: params.resourceName }, item).$promise;
    };

    ResourceService.prototype.deleteItem = function (params, item) {
        "use strict";
        return this.resource.delete({ resourceName: params.resourceName }, item).$promise;
    };

    ResourceService.prototype.setParameters = function (params) {
        "use strict";
        this.params = params;
    };
    return ResourceService;
})();

angular.module('cheese').factory('ResourceService', ['$injector', '$resource', ResourceService]);
/*
Create "_design/api" document in database
curl -X PUT http://127.0.0.1:5984/work-requests
curl -X PUT http://127.0.0.1:5984/work-requests/_design/api --data-binary @mydesign.json
{
"_id": "_design/api",
"lists": {
"all": "function(head, req) { var values = []; while (row = getRow()) { values.push(row.value); } return JSON.stringify(values); }"
},
"shows": {
"detail": "function(doc, req) { var myDoc = JSON.parse(JSON.stringify( doc )); delete myDoc['_revisions']; myDoc.id = myDoc._id; return { 'json': myDoc }; }"
},
"views": {
"default": {
"map": "function (doc){ var myDoc = JSON.parse(JSON.stringify( doc )); myDoc.id = myDoc._id; emit(myDoc._id, myDoc); }"
}
}
}
*/


text:
"""streaming.py: Implementation of class AbstractTwitterStreamingCommand
and its subclasses.
"""

from argparse import ArgumentParser

from . import AbstractTwitterCommand
from ..parsers import cache

# Public API
# GET statuses/sample
STREAMING_STATUSES_SAMPLE = ('statuses/sample', 'sample')

# POST statuses/filter
STREAMING_STATUSES_FILTER = ('statuses/filter', 'filter')

# User Streams (domain='userstream.twitter.com')
# GET user
STREAMING_USER = ('user',)

# Site Streams (domain='sitestream.twitter.com')
# GET site
STREAMING_SITE = ('site',)

# GET c/:stream_id/info
# ?

# Firehose
# GET statuses/firehose
STREAMING_STATUSES_FIREHOSE = ('statuses/firehose', 'firehose', 'fire')

# pylint: disable=abstract-method
class AbstractTwitterStreamingCommand(AbstractTwitterCommand):
    """n/a"""
    pass

class StatusesSample(AbstractTwitterStreamingCommand):
    """Print a small random sample of all public statuses."""

    def create_parser(self, subparsers):
        parser = subparsers.add_parser(
            STREAMING_STATUSES_SAMPLE[0],
            aliases=STREAMING_STATUSES_SAMPLE[1:],
            help=self.__doc__)
        return parser

    def __call__(self):
        self.manager.request_statuses_sample()

class StatusesFilter(AbstractTwitterStreamingCommand):
    """Print public statuses that match one or more filter predicates."""

    def create_parser(self, subparsers):
        parser = subparsers.add_parser(
            STREAMING_STATUSES_FILTER[0],
            aliases=STREAMING_STATUSES_FILTER[1:],
            parents=[parser_follow(),
                     parser_track_and_locations(),],
            help=self.__doc__)
        return parser

    def __call__(self):
        self.manager.request_statuses_filter()

class User(AbstractTwitterStreamingCommand):
    """Stream messages for a single user."""

    def create_parser(self, subparsers):
        parser = subparsers.add_parser(
            STREAMING_USER[0],
            #aliases=STREAMING_USER[1:],
            parents=[parser_track_and_locations(),
                     parser_with_and_replies()],
            help=self.__doc__)
        return parser

    def __call__(self):
        self.manager.request_user()

class Site(AbstractTwitterStreamingCommand):
    """Stream messages for a set of users."""

    def create_parser(self, subparsers):
        parser = subparsers.add_parser(
            STREAMING_SITE[0],
            #aliases=STREAMING_SITE[1:],
            parents=[parser_follow(),
                     parser_with_and_replies()],
            help=self.__doc__)
        return parser

    def __call__(self):
        self.manager.request_site()

class StatusesFirehose(AbstractTwitterStreamingCommand):
    """Print all public statuses."""

    def create_parser(self, subparsers):
        parser = subparsers.add_parser(
            STREAMING_STATUSES_FIREHOSE[0],
            aliases=STREAMING_STATUSES_FIREHOSE[1:],
            help=self.__doc__)
        return parser

    def __call__(self):
        self.manager.request_statuses_firehose()

@cache
def parser_track_and_locations():
    """Return the parent parser object for --track and --locations
    optional arguments.
    """

    parser = ArgumentParser(add_help=False)
    parser.add_argument(
        '--track',
        metavar='CSV',
        help='A comma-separated list of phrases to filter tweets')
    parser.add_argument(
        '--locations',
        metavar='CSV',
        help='A comma-separated list of coordinates specifying a set of '
             'bounding boxes to filter tweets')

    return parser

@cache
def parser_follow():
    """Return the parent parser object for --follow optional
    argument.
    """

    parser = ArgumentParser(add_help=False)
    parser.add_argument(
        '--follow',
        metavar='CSV',
        help='A comma-separated list of user IDs to filter tweets')

    return parser

@cache
def parser_with_and_replies():
    """Return the parent parser object for --with and --replies
    optional arguments.
    """

    parser = ArgumentParser(add_help=False)
    parser.add_argument(
        '--with',
        choices=('user', 'followings',),
        help='the types of messages')
    parser.add_argument(
        '--replies',
        choices=('all',),
        help='show all replies')

    return parser

def make_commands(manager):
    """Prototype"""

    # pylint: disable=no-member
    return (cmd_t(manager) for cmd_t in
            AbstractTwitterStreamingCommand.__subclasses__())


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\LearningArea */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'id')->textInput() ?>

    <?= $form->field($model, 'grade_level_id')->textInput() ?>

    <?= $form->field($model, 'subject_id')->textInput() ?>

    <?= $form->field($model, 'sequence')->textInput() ?>

    <?= $form->field($model, 'semester')->textInput() ?>

    <?= $form->field($model, 'revision')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
<?php

namespace MediaWiki\Extension\Notifications\Formatters;

use EchoDiscussionParser;
use MediaWiki\Revision\RevisionRecord;

class EchoRevertedPresentationModel extends EchoEventPresentationModel {

	public function getIconType() {
		return 'revert';
	}

	public function canRender() {
		return (bool)$this->event->getTitle();
	}

	public function getHeaderMessage() {
		$msg = parent::getHeaderMessage();
		$msg->params( $this->getTruncatedTitleText( $this->event->getTitle(), true ) );
		$msg->params( $this->getNumberOfEdits() );
		return $msg;
	}

	public function getBodyMessage() {
		$summary = $this->event->getExtraParam( 'summary' );
		if (
			!$this->isAutomaticSummary( $summary ) &&
			$this->userCan( RevisionRecord::DELETED_COMMENT )
		) {
			$msg = $this->msg( 'notification-body-reverted' );
			$msg->plaintextParams( $this->formatSummary( $summary ) );
			return $msg;
		} else {
			return false;
		}
	}

	private function formatSummary( $wikitext ) {
		return EchoDiscussionParser::getTextSnippetFromSummary( $wikitext, $this->language );
	}

	public function getPrimaryLink() {
		$url = $this->event->getTitle()->getLocalURL( [
			'oldid' => 'prev',
			'diff' => $this->event->getExtraParam( 'revid' )
		] );
		return [
			'url' => $url,
			'label' => $this->msg( 'notification-link-text-view-changes', $this->getViewingUserForGender() )->text()
		];
	}

	public function getSecondaryLinks() {
		$links = [ $this->getAgentLink() ];

		$title = $this->event->getTitle();
		if ( $title->canHaveTalkPage() ) {
			$links[] = $this->getPageLink(
				$title->getTalkPage(), '', true
			);
		}

		return $links;
	}

	/**
	 * Return a number that represents if one or multiple edits
	 * have been reverted for formatting purposes.
	 * @return int
	 */
	private function getNumberOfEdits() {
		$method = $this->event->getExtraParam( 'method' );
		if ( $method && $method === 'rollback' ) {
			return 2;
		} else {
			return 1;
		}
	}

	private function isAutomaticSummary( $summary ) {
		$autoSummaryMsg = $this->msg( 'undo-summary' )->inContentLanguage();
		$autoSummaryMsg->params( $this->event->getExtraParam( 'reverted-revision-id' ) );
		$autoSummaryMsg->params( $this->getViewingUserForGender() );
		$autoSummary = $autoSummaryMsg->text();

		return $summary === $autoSummary;
	}

	protected function getSubjectMessageKey() {
		return 'notification-reverted-email-subject2';
	}

	public function getSubjectMessage() {
		return parent::getSubjectMessage()->params( $this->getNumberOfEdits() );
	}
}


text:
<?php

namespace Isolate\Symfony\IsolateBundle\Tests\Functional;

use Isolate\Symfony\IsolateBundle\Command\GenerateLazyObjectProxyCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;

class GenerateLazyObjectsProxyCommandTest extends BundleTestCase
{
    public function setUp()
    {
        static::$kernel = static::createKernel();
        static::$kernel->boot();
    }

    public function test_clearing_proxy_cache_during_cache_clear()
    {
        $fs = new Filesystem();
        $fs->remove($this->getProxyCacheDir());
        $fs->mkdir($this->getProxyCacheDir());

        $tester = $this->getGeneraterProxiesCommandTester();
        $tester->execute(array('command' => 'isolate:lazy-objects:generate:proxies'));

        $this->assertSame(
            PHP_EOL . "Proxy class generated for \"Isolate\\Symfony\\IsolateBundle\\Tests\\Functional\\Entity\\User\"" . PHP_EOL ,
            $tester->getDisplay()
        );
        $this->assertEquals(1, $this->getProxyClassesInCacheCount());
    }

    /**
     * @return CommandTester
     */
    private function getGeneraterProxiesCommandTester()
    {
        $application = new Application(static::$kernel);
        $application->add(new GenerateLazyObjectProxyCommand());

        $command = $application->find('isolate:lazy-objects:generate:proxies');
        return new CommandTester($command);
    }

    private function getProxyClassesInCacheCount()
    {
        $finder = new Finder();
        return $finder->in($this->getProxyCacheDir())->name("*.php")->count();
    }

    /**
     * @return mixed
     */
    private function getProxyCacheDir()
    {
        return static::$kernel->getContainer()->getParameter('isolate.lazy_objects.proxy_dir');
    }
}


text:
@implementation Context

- (instancetype)init
{
    if (self = [super init]) {
        _state = [[UnauthorizedState alloc] init];
    }

    return self;
}

- (NSString *)userId
{
    return [_state userIdOfContext:self];
}

- (BOOL)isAuthorized
{
    return [_state isAuthorizedWithContext:self];
}

- (void)changeStateToAuthorizedWithUserId:(NSString *)userId
{
    _state = [[AuthorizedState alloc] initWithUserId:userId];
}

- (void)changeStateToUnauthorized
{
    _state = [[UnauthorizedState alloc] init];
}

@end


text:
'use strict';

const fs = require('fs');
const path = require('path');

const filelist = require('./filelist')

const descriptionToFilelistMap = {
  "children": "Children",
  "general": "General",
  "history-art": "History",
  "mahayana": "Mahayana",
  "meditation": "Meditation",
  "theravada": "Theravada"
};

var targetDir = path.join(__dirname, 'missing');

if (!fs.existsSync(targetDir)){
  fs.mkdirSync(targetDirdir);
}

console.log('Attempting to resolve book names');

for(const fileSuffix of Object.keys(descriptionToFilelistMap)) {
  const jsonFileName = path.join(__dirname, 'json', fileSuffix + ".json");
  const filelistKey = descriptionToFilelistMap[fileSuffix];

  let targetFilelist = null;
  for(const currFilelist of filelist) {
    if(currFilelist.name == filelistKey) {
      targetFilelist = currFilelist;
      break;
    }
  }
  if(!targetFilelist) {
    throw "Couldn't find file list for " + filelistKey;
  }

  function findMissing(err, data) {
    const missingMapFileName = path.join(targetDir, fileSuffix + '.json');
    const fileList = targetFilelist.content
    const jsonData = JSON.parse(data);
    const fileBooks = new Set(fileList.map((b) => b.name.toLowerCase()));

    fs.readFile(missingMapFileName, 'utf8', function(err, data) {
      debugger
      let missingBookMap = {}

      if(!err) {
        missingBookMap = JSON.parse(data);
      }

      // Create a list of books that we can't find in the fileList
      // Assuming that it is not already accounted for.
      for(const bookName of Object.keys(jsonData)) {
        if(!fileBooks.has(bookName.toLowerCase())) {
          if(!missingBookMap[bookName]) {
            missingBookMap[bookName] = null;
          }
        } else {
          missingBookMap[bookName] = bookName;
        }
      }

      fs.writeFile(missingMapFileName, JSON.stringify(missingBookMap, null, 2),
          'utf8', () => console.log('Missing Books To ' + missingMapFileName));
    });

  }

  fs.readFile(jsonFileName, 'utf8', findMissing);
}


text:
package org.terasology.engine.modes.loadProcesses;

import org.terasology.context.Context;
import org.terasology.entitySystem.entity.EntityManager;
import org.terasology.world.block.BlockManager;
import org.terasology.world.block.internal.BlockManagerImpl;
import org.terasology.world.block.typeEntity.BlockTypeEntityGenerator;

/**
 * @author Immortius
 */
public class InitialiseBlockTypeEntities extends SingleStepLoadProcess {

    private final Context context;

    public InitialiseBlockTypeEntities(Context context) {
        this.context = context;
    }

    @Override
    public String getMessage() {
        return "Initialising Block Type Entities";
    }

    @Override
    public boolean step() {
        BlockManagerImpl blockManager = (BlockManagerImpl) context.get(BlockManager.class);
        blockManager.subscribe(new BlockTypeEntityGenerator(context.get(EntityManager.class), blockManager));
        return true;
    }

    @Override
    public int getExpectedCost() {
        return 1;
    }
}


text:
@interface GSDK_GTMABPerson : GSDK_GTMABRecord
{
}

+ (unsigned int)typeOfProperty:(int)arg1;
+ (unsigned int)compositeNameFormat;
+ (id)localizedPropertyName:(int)arg1;
+ (id)personWithFirstName:(id)arg1 lastName:(id)arg2;
- (id)description;
- (id)compositeName;
- (id)imageData;
- (_Bool)setImage:(struct UIImage *)arg1;
- (struct UIImage *)image;
- (_Bool)setImageData:(id)arg1;
- (id)init;

@end


text:
//
//  Histogram.h
//  Graphs
//
//  Created by Viktoras Laukevičius on 11/04/15.
//  Copyright (c) 2015 Viktoras Laukevicius. All rights reserved.
//

#ifndef __Graphs__Histogram__
#define __Graphs__Histogram__

#include <stdio.h>
#include <string>
#include <vector>

class Histogram
{
public:
    static void generate(std::vector<long> *segments, std::string fileName);
    static void generate(std::vector<long> *segments, long relationColumn, std::string fileName);
};

#endif /* defined(__Graphs__Histogram__) */


text:
import * as internal from "../../src/internal.js";
import CustomBackdrop from "./CustomBackdrop.js";
import CustomOverlayFrame from "./CustomOverlayFrame.js";
import Dialog from "../../src/Dialog.js";

class SampleDialog extends Dialog {
  get [internal.defaultState]() {
    return Object.assign(super[internal.defaultState], {
      backdropPartType: CustomBackdrop,
      framePartType: CustomOverlayFrame
    });
  }

  [internal.render](/** @type {PlainObject} */ changed) {
    if (super[internal.render]) {
      super[internal.render](changed);
    }
    if (changed.framePartType) {
      // Have the dialog close itself when the user clicks anywhere within it. In
      // many cases, you'll want to have a button ("OK", "Close", etc.) that
      // performs this action.
      this[internal.ids].frame.addEventListener("click", () => {
        this.close();
      });
    }
  }
}

customElements.define("sample-dialog", SampleDialog);
export default SampleDialog;


text:
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.adwords.lib.utils;

/**
 * Exception thrown when we receive an error response from the server.
 */
public class ReportDownloadResponseException extends Exception {

  private final int httpStatus;

  /**
   * Constructor.
   *
   * @param httpStatus the http status code
   */
  public ReportDownloadResponseException(int httpStatus) {
    this(httpStatus, null);
  }

  /**
   * Constructor.
   *
   * @param httpStatus the http status code
   * @param cause Underlying cause, if available.
   */
  public ReportDownloadResponseException(int httpStatus, Throwable cause) {
    super(String.valueOf(httpStatus), cause);
    this.httpStatus = httpStatus;
  }

  public int getHttpStatus() {
    return httpStatus;
  }
}


text:
package org.dvare.expression.literal;

import org.dvare.expression.datatype.FloatType;

public class FloatLiteral<T> extends LiteralExpression {

    public FloatLiteral(T value) {
        super(value, new FloatType());
    }
}


text:
option (USE_C11 "if use -std=c++11 flag" ON)
option (WALLE_DEBUG "if using debug mode" ON)
#install path
#header ~/include
#libs   ~/lib
#exe     ~/bin
set(CMAKE_INSTALL_PREFIX /root/install)

message(STATUS "program will be install to " ${CMAKE_INSTALL_PREFIX})

set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)

SET(CMAKE_VERBOSE_MAKEFILE on )
#do not modify belows
set(CMAKE_CONFIGURATION_TYPES Debug Release RelWithDebInfo)

if(WALLE_DEBUG)
	set(CMAKE_BUILD_TYPE Debug)
else ()
	set(CMAKE_BUILD_TYPE Release)
endif()
message(STATUS "program build type " ${CMAKE_BUILD_TYPE})


text:
<?php

namespace OrcaServices\Datatrans\Xml\Api\Request;

/**
 * Datatrans XML API Credit Request
 *
 * The Credit Request can be used for refunds of previously authorised and settled transactions.
 *
 * Please note:
 *
 * - The previously settled amount must not be exceeded.
 * - The key reference parameter is "uppTransactionId"; in the past, this used to be "authorizationCode";
 * this is still supported, but no longer recommended.
 * - Transactions can also be partially refunded; partial refund requests (i.e. 1 x settled transaction
 * of EUR 100 / 2 x credit of EUR 50) are supported for most payment methods; please refer to the Datatrans
 * support team for information about restrictions with certain payment methods.
 * - Some payment methods such as Sofort.com, German ELV or iDEAL do not support credit requests.
 *
 * This class does NOT support sending requests using the authorizationCode.
 *
 * @see https://www.datatrans.ch/showcase/settlement/xml-credit-request
 */
class Credit extends SettlementBase
{

    /**
     * Set the elements for the Request XML
     *
     * @param \SimpleXMLElement $requestChild The request XML element to set the elements into.
     * @return void
     */
    protected function _setRequestXmlElements($requestChild)
    {
        $requestChild->addChild('uppTransactionId', $this->_uppTransactionId);
        $requestChild->addChild('amount', $this->_amount);
        $requestChild->addChild('currency', $this->_currency);
        $transType = '06';
        $requestChild->addChild('transtype', $transType);
    }
}


text:
<?php
include('inc/header.php');
$buildHTML = '';
$submitHTML = '';
$result = '';
$count = count($builds);

if($status) {
    $result = $translator->translate('You have sucessfully distributed the Build to:

%s', [ $emails ]);
}

if($count > 0) {
    foreach($builds as $key => $build) {
        $selected = '';
        if($idbuild === $build['idbuild']) {
            $selected = ' selected="selected"';
        }
        $buildHTML .= <<<EOT
    <option value="{$build['idbuild']}"{$selected}>[{$build['platform']}] {$build['display']} - v{$build['version']}</option>
EOT;
    }

    $submitHTML = <<<EOT
    <button type="submit" class="btn btn-primary">{$translator->translate('Distribute')}</button>
EOT;
}
else {
    $buildHTML = <<<EOT
    <option>{$translator->translate('No builds available')}</option>
EOT;
}

echo <<<EOT

{$translator->translate('Distribution')}

            <form class="list list-group ui-distribute-form" method="POST">
                <input type="hidden" name="idapp" value="{$app->getId()}" />

                    {$translator->translate('Build')}
                    <select class="form-control" id="idbuild" name="idbuild">
{$buildHTML}
                    </select>

                    {$translator->translate('Emails to be sent')}
                    <textarea class="form-control" name="emails" id="emails">{$emails}</textarea>

                        {$translator->translate('_email_format_sample_text')}

                    {$translator->translate('Message to the users')}
                    <textarea class="form-control" name="message" id="message">{$message}</textarea>

{$submitHTML}

{$result}

            </form>

EOT;

include('inc/footer.html');
?>


text:
[![Build Status](https://travis-ci.org/orn688/randommap-website.svg?branch=master)](https://travis-ci.org/orn688/randommap-website)

The backend for the [RandomMap](https://chrome.google.com/webstore/detail/randommap/mcfelmkmgbibpgkklglafpenihjockij) Google Chrome extension.


text:
This is a snapshot of (the 1999 PC/PSX/DreamCast game) Urban Chaos source code recently retreived from an old SourceSafe backup pulled from an old MuckyFoot server.

The games source code is in the fallen directory (the working title for Urban Chaos)

At the time it was compiled with Visual Studio 6 I believe and possibly DirectX 6 and is entirey written in c (despite using cpp files).
(I notice also some Glide code in there) I have succesfully loaded the projects with VS2013 though.

There is also source code for the psx version, and maybe even the Dream Cast port.

Urban Chaos had its own map editor and animation keyframe editor, these ran if I remember correctly under a window system
implemented by Guy Simmons, the code is included in the Editor folder

MFlib1 and MFStdLib are some generic libraries shared across Urban Chaos and possibly Startopia
MuckyBasic is a inhouse scripting language written by Mark Adami
Thrust is a side project by Mark Adami

Note no data is included, and the source data used by the editor/Engine is likely somewhat different to the data used by the final disk image
(all though much of it is probably identical)

I am making this code public mainly out of historical interest, I doubt theres anything of any actual use to anyone, allthough people do
occasionally still ask me about data formats so they can dig them out themsleves now...

*BrainDump*

I tried compiling the code, but theres a lot of errors..

We used DirectX before it did hardware vertex transforms, at some point VertexBuffers came along and I seem to recall Eddie Edwards implementing their use.

a prim is simply a mesh (lampost etc)

There is no soft skinning characters are seperate meshes

The floor is a heightmap with a vertical offset possible for the kerbs see pap.h

The building meshes were created on the fly from wall data that could generate N stories high of side wall building.cpp

Fence meshes and fire escape meshes were similarily created on the fly

The editor allowed placement of waypoints and control code for ai. as well as map creation

The data set was limited to run on a 1 Meg Playstation1 (PSX)

Theres code for features that never shipped like a motorbike and a grappling hook with rope physics, also once
mav is the sequel to nav, it handles mavigation :)

I also had a tendency to increment the letter of a file type with new versions so map.h eventually became pap.h (much of the code was written with a 8.3 filename restriction)

yes we had pee physics

Thing could be considered a cpp base class

MapWho is a bullfrog thing, essentially a 2d spatial array that objects in the world attach themselves to as a linked list for fast spatial lookups

once upon a time the building all had procedural internals, also sewer systems..

Mike Diskett


text:
import { Service } from './src/service.class';
import { Application } from './src/app.class';

export {
  Service,
  Application
};


text:
module Rest
  class Sample < Base
  	def self.create(user_credentials, params, byte_data)
  		put(
  			"#{name.demodulize.downcase}",
  			byte_data,
  			headers(user_credentials['token']).merge('params' => params, 'Content-Type' => 'application/octet-stream')
  		)
		end

  	def self.list(user_credentials)
    	get(
        "#{name.demodulize.downcase}",
        headers(user_credentials['token'])
      )
    end

    def self.by_id(user_credentials, id)
      get(
        "#{name.demodulize.downcase}/#{id}",
        headers(user_credentials['token'])
      )
    end
  end
end


text:
<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\Npc;
use App\User;

class NpcLiked extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(Npc $npc, User $user)
    {
        $this->npc = $npc;
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', 'https://laravel.com')
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'npc_id' => $this->npc->id,
            'npc_name' => $this->npc->name,
            'user_name' => $this->user->name,
            'user_id' => $this->user->id,
        ];
    }
}


text:
package io.renren.service;

import io.renren.entity.SysArticleUserEntity;

import java.util.List;
import java.util.Map;

/**
 *
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-06-18 10:42:39
 */
public interface SysArticleUserService {

	SysArticleUserEntity queryObject(Integer id);

	List<SysArticleUserEntity> queryList(Map<String, Object> map);

	int queryTotal(Map<String, Object> map);

	void save(SysArticleUserEntity articleUser);

	void update(SysArticleUserEntity articleUser);

	void delete(Integer id);

	void deleteBatch(Integer[] ids);
}


text:
package org.apache.giraph.tools.utils;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.hadoop.io.Writable;

public class GeneralPartialQueryWritableMemOp
implements Writable{
	/*
	 * -2^32 indicates the vertex is not matched
	 */
	private final int PARTIAL_QUERY_NOT_MATCHED = 0x80000000;
	private final byte QUERY_SEQUENCE_TYPE_UNKNOWN = -1;

	/*
	 * we fix the order of query node in preprocess.
	 * the positive matched value indicates matched and accessed
	 * the negative matched value indicates matched, but not accessed
	 */
	private int[] dataGraphNode;
	private byte totalPairs;
	private byte remainEdges;

	/* indicate the sequence of a query. */
	private byte querySequenceType;

	/* record previous matched vertex id. */
	private byte previousMatchedVertexIndex;

	public GeneralPartialQueryWritableMemOp(){
		totalPairs = 0;
		remainEdges = 0;
		querySequenceType = QUERY_SEQUENCE_TYPE_UNKNOWN;
		dataGraphNode = null;
	}

	/**
	 * undirected edges count once.
	 */
	public GeneralPartialQueryWritableMemOp(int queryNodeSize, int totalEdges){
		dataGraphNode = new int[queryNodeSize];
		totalPairs = (byte)queryNodeSize;

		this.initialize(queryNodeSize, totalEdges);
//		remainEdges = (byte)totalEdges;
//		previousMatchedVertexIndex = -1;
//		querySequenceType = QUERY_SEQUENCE_TYPE_UNKNOWN;
//		for(int i = 0; i < totalPairs; i++){
//			dataGraphNode[i] = PARTIAL_QUERY_NOT_MATCHED;
//		}
	}

	public void initialize(int queryNodeSize, int totalEdges){
		remainEdges = (byte)totalEdges;
		previousMatchedVertexIndex = -1;
		querySequenceType = QUERY_SEQUENCE_TYPE_UNKNOWN;
		for(int i = 0; i < totalPairs; i++){
			dataGraphNode[i] = PARTIAL_QUERY_NOT_MATCHED;
		}
	}

	public void setQuerySequenceType(int querySequenceType){
		this.querySequenceType = (byte)querySequenceType;
	}

	public int getQuerySequenceType(){
		return this.querySequenceType;
	}

	/**
	 * The query is fixed when all the edges are accessed.
	 * @return
	 */
	public Boolean isCompelete(){
		return remainEdges == 0;
	}

	public void decRemainEdges(){
		remainEdges--;
	}

	public void decRemainEdges(int value){
		remainEdges -= value;
	}

	/**
	 * nodeIndex means the index in QueryGraph, not the accurate node id.
	 * @param nodeIndex
	 * @return
	 */
	public Boolean isMatched(int nodeIndex){
		return (dataGraphNode[nodeIndex] != PARTIAL_QUERY_NOT_MATCHED);
	}

	public Boolean isAccessed(int nodeIndex){
		return (dataGraphNode[nodeIndex] > 0);
	}

	public boolean checkValid(){
		for(int i = 0; i < totalPairs; i++){
			if(dataGraphNode[i] == PARTIAL_QUERY_NOT_MATCHED){
				return false;
			}
		}
		return true;
	}

	/**
	 * nodeIndex means the index in QueryGraph, not the accurate node id.
	 * Before calling this method, we should make sure that the vertex is matched, i.e
	 * calling isMatched(nodeIndex) before calling this method.
	 * In order to avoid vertexId is ZERO, we add a shift of 1.
	 * @param nodeIndex
	 * @return
	 */
	public int getMappedDataGraphNode(int nodeIndex){
		return dataGraphNode[nodeIndex] > 0 ? (dataGraphNode[nodeIndex]-1) : (-dataGraphNode[nodeIndex]-1);
	}

	/**
	 * return the index of unaccessed query vertex
	 * @return
	 */
	public ArrayList<Integer> getUnaccessedList(){
		ArrayList<Integer> al = new ArrayList<Integer>();
		for(int i = 0; i < totalPairs; i++){
			if(dataGraphNode[i] < 0 && dataGraphNode[i] != PARTIAL_QUERY_NOT_MATCHED){
				al.add(i);
			}
		}
		return al;
	}

	public void update(int candIndex, int i) {
//		if(dataGraphNode[candIndex] == PARTIAL_QUERY_NOT_MATCHED)
//			currentPairs++;
		dataGraphNode[candIndex] = (i == PARTIAL_QUERY_NOT_MATCHED ? PARTIAL_QUERY_NOT_MATCHED : -(i+1));
	}

	public int getPreviousMatchedVertexIndex() {
		return previousMatchedVertexIndex;
	}

	public void setPreviousMatchedVertexIndex(int index){
		if(dataGraphNode[index] < 0){
			dataGraphNode[index] = -dataGraphNode[index];
		}
		else{
			System.out.println("Conflict in mapping for matched vertex!");
		}
		previousMatchedVertexIndex = (byte)index;
	}

	public boolean hasUsed(int dataVertexId) {
		int tmpTarget = dataVertexId + 1;
		for(int i = 0; i < totalPairs; i++){
			if(dataGraphNode[i] == -tmpTarget || dataGraphNode[i] == tmpTarget){
				return true;
			}
		}
		return false;
	}

	public int getRemainEdges() {
		return remainEdges;
	}

	public void copy(GeneralPartialQueryWritableMemOp pq) {
		dataGraphNode = pq.dataGraphNode.clone();
		totalPairs = pq.totalPairs;
		remainEdges = pq.remainEdges;
		querySequenceType = pq.querySequenceType;
		previousMatchedVertexIndex = pq.previousMatchedVertexIndex;
	}

	@Override
	public void write(DataOutput out) throws IOException {
		out.writeByte(totalPairs); //1B
		out.writeByte(remainEdges); //1B
		out.writeByte(querySequenceType); //1B
		out.writeByte(previousMatchedVertexIndex);//1B
		for(int i = 0; i < totalPairs; ++i){
			out.writeInt(dataGraphNode[i]); // totalPairs * 4B
		}
	}

	@Override
	public void readFields(DataInput in) throws IOException {
		totalPairs = in.readByte();
		remainEdges = in.readByte();
		querySequenceType = in.readByte();
		previousMatchedVertexIndex = in.readByte();
//		System.out.println("Incoming:\n"+totalPairs+" "+currentPairs+" "+previousMatchedVertexIndex+"\n");
		dataGraphNode = new int[totalPairs];
		for(int i = 0; i < totalPairs; ++i){
			dataGraphNode[i] = in.readInt();
		}
	}

	public String toString(){
		String ans = "totalPairs = " + totalPairs
				+"\nremainEdges= "+ remainEdges
				+"\nquerySequenceType= "+ querySequenceType
				+"\npreviousMatchedVertexIndex= "+ previousMatchedVertexIndex
				+"\n";

		for(int i = 0; i < totalPairs; i++){
			ans = ans + (dataGraphNode[i] > 0 ? (dataGraphNode[i]-1) : (dataGraphNode[i]+1))+" ";
		}

		return ans;
	}

}


text:
from paddle.fluid.default_scope_funcs import (
    enter_local_scope,
    find_var,
    get_cur_scope,
    leave_local_scope,
    scoped_function,
    var,
)
import unittest

class TestDefaultScopeFuncs(unittest.TestCase):
    def test_cur_scope(self):
        self.assertIsNotNone(get_cur_scope())

    def test_none_variable(self):
        self.assertIsNone(find_var("test"))

    def test_create_var_get_var(self):
        var_a = var("var_a")
        self.assertIsNotNone(var_a)
        self.assertIsNotNone(get_cur_scope().find_var('var_a'))
        enter_local_scope()
        self.assertIsNotNone(get_cur_scope().find_var('var_a'))
        leave_local_scope()

    def test_var_get_int(self):
        def __new_scope__():
            i = var("var_i")
            self.assertFalse(i.is_int())
            i.set_int(10)
            self.assertTrue(i.is_int())
            self.assertEqual(10, i.get_int())

        for _ in range(10):
            scoped_function(__new_scope__)

if __name__ == '__main__':
    unittest.main()


text:
package io.silverspoon.bulldog.core;

public enum Parity {
   None,
   Odd,
   Even,
   Mark,
   Space
}


text:
package de.mickare.routernet;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

import de.mickare.routernet.protocol.ComponentsProtocol.UUIDMessage;

public class ProtocolUtils {

	/**
	 * Converts the UUID from protocol to java object
	 * @param uuid protocol message
	 * @return uuid as java object
	 */
	public static UUID convert( final UUIDMessage uuid ) {
		if ( uuid == null ) {
			return null;
		}
		return new UUID( uuid.getMostSignificantBits(), uuid.getLeastSignificantBits() );
	}
	/**
	 * Converts UUID from java object to protocol
	 * @param uuid java object
	 * @return uuid as protocol message
	 */
	public static UUIDMessage convert( final UUID uuid ) {
		if ( uuid == null ) {
			return null;
		}
		return UUIDMessage.newBuilder().setMostSignificantBits( uuid.getMostSignificantBits() ).setLeastSignificantBits( uuid.getLeastSignificantBits() ).build();
	}

	/**
	 * Converts a list of protocol UUIDs to java objects
	 * @param c list of uuid protocol messages
	 * @return  list of java uuid objects
	 */
	public static List<UUID> convertAllMessages( Collection<UUIDMessage> c ) {
		if ( c == null ) {
			return null;
		}
		final List<UUID> result = new ArrayList<>( c.size() );
		c.forEach( old -> result.add( convert( old ) ) );
		return result;
	}

	/**
	 * Converts a list of java UUID objects to protocol messages
	 * @param c list of java uuid objects
	 * @return  list of uuid protocol messages
	 */
	public static List<UUIDMessage> convertAll( Collection<UUID> c ) {
		if ( c == null ) {
			return null;
		}
		final List<UUIDMessage> result = new ArrayList<>( c.size() );
		c.forEach( old -> result.add( convert( old ) ) );
		return result;
	}

}


text:
using Eto.OpenTK;
using Eto.Forms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace TestEtoGl.WPF_Framebuffer
{
  static class Program
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      var platform = new Eto.WinForms.Platform();
      platform.Add<GLSurface.IHandler>(() => new Eto.OpenTK.WinForms.WinGLSurfaceHandler());

      new Application(platform).Run(new MainForm());
    }
  }
}


text:
package org.onedatashare.server.service;

import org.onedatashare.server.model.core.EndpointType;
import org.onedatashare.server.model.core.Stat;
import org.onedatashare.server.model.filesystem.operations.*;
import org.onedatashare.server.module.HttpResource;
import org.onedatashare.server.module.VfsResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

@Service
public class HttpFileService extends ResourceServiceBase {

    @Autowired
    CredentialService credentialService;

    @Override
    protected Mono<? extends org.onedatashare.server.module.Resource> getResource(String credId) {
        return  credentialService.fetchAccountCredential(EndpointType.http, credId)
                .flatMap(HttpResource::initialize)
                .subscribeOn(Schedulers.elastic());
    }

    @Override
    public Mono<Stat> list(ListOperation listOperation) {
        return getResource(listOperation.getCredId())
                .flatMap(resource -> resource.list(listOperation));
    }

    @Override
    public Mono<Void> mkdir(MkdirOperation mkdirOperation) {
        return getResource(mkdirOperation.getCredId())
                .flatMap(resource -> resource.mkdir(mkdirOperation));
    }

    @Override
    public Mono<Void> delete(DeleteOperation deleteOperation) {
        return getResource(deleteOperation.getCredId())
                .flatMap(resource -> resource.delete(deleteOperation));
    }

    /**
     * Not needed unless we wanna support downloading linearly thorugh a browser. Could probably use C^2
     * @param downloadOperation
     * @return
     */
    @Override
    public Mono<String> download(DownloadOperation downloadOperation) {
        return null;
    }
}


text:
require "multi_json"

module BaiduUeditorRails
  class AssetManifest
    def self.load(manifest_path)
      YamlManifest.try(manifest_path) ||
        JsonManifest.try(manifest_path) ||
        NullManifest.new
    end
  end
end

class YamlManifest
  def self.try(manifest_path)
    yaml_file = File.join(manifest_path, "manifest.yml")
    new(yaml_file) if File.exists?(yaml_file)
  end

  def initialize(file)
    @file = file
    @manifest = YAML.load_file(file)
  end

  def append(logical_path, file)
    @manifest[logical_path] = logical_path
  end

  def remove(logical_path)
    @manifest.delete(logical_path)
  end

  def remove_digest(logical_path)
    if digested = @manifest[logical_path]
      @manifest[logical_path] = logical_path
      yield digested, logical_path if block_given?
    end
  end

  def each(pattern)
    @manifest.each_key do |asset|
      yield asset if asset =~ pattern
    end
  end

  def to_s
    dump
  end

  def dump(io=nil)
    YAML.dump(@manifest, io)
  end

  def write
    File.open(@file, "wb") { |f| dump(f) }
  end
end

class JsonManifest
  def self.try(manifest_path)
    paths = Dir[File.join(manifest_path, "manifest*.json")]
    new(paths.first) if paths.any?
  end

  def initialize(file)
    @file = file
    @manifest = MultiJson.load(File.read(file))
  end

  def append(logical_path, file)
    stat = File.stat(file)

    @manifest["assets"][logical_path] = logical_path
    @manifest["files"][logical_path] = {
      "logical_path" => logical_path,
      "mtime"        => stat.mtime.iso8601,
      "size"         => stat.size,
      "digest"       => nil
    }
  end

  def remove(logical_path)
    if digested = @manifest["assets"].delete(logical_path)
      @manifest["files"].delete(digested)
    end
  end

  def remove_digest(logical_path)
    if digested = @manifest["assets"][logical_path]
      @manifest["assets"][logical_path] = logical_path
      @manifest["files"][logical_path] = @manifest["files"].delete(digested).tap { |f| f["digest"] = nil }
      yield digested, logical_path if block_given?
    end
  end

  def each(pattern)
    @manifest["assets"].each_key do |asset|
      yield asset if asset =~ pattern
    end
  end

  def to_s
    dump
  end

  def dump
    MultiJson.dump(@manifest)
  end

  def write
    File.open(@file, "wb") { |f| f.write(dump) }
  end
end

class NullManifest
  def append(*); end
  def remove(*); end
  def remove_digest(*); end
  def each(*); end
  def write; end
end


text:
package route53

import (
	"github.com/aws/aws-sdk-go/service/route53"

	"k8s.io/kubernetes/federation/pkg/dnsprovider"
	"k8s.io/kubernetes/pkg/util"
)

// Compile time check for interface adeherence
var _ dnsprovider.Zones = Zones{}

type Zones struct {
	interface_ *Interface
}

func (zones Zones) List() ([]dnsprovider.Zone, error) {
	input := route53.ListHostedZonesInput{}
	response, err := zones.interface_.service.ListHostedZones(&input)
	if err != nil {
		return []dnsprovider.Zone{}, err
	}
	hostedZones := response.HostedZones
	// TODO: Handle result truncation
	// https://docs.aws.amazon.com/sdk-for-go/api/service/route53/Route53.html#ListHostedZones-instance_method
	zoneList := make([]dnsprovider.Zone, len(hostedZones))
	for i, zone := range hostedZones {
		zoneList[i] = &Zone{zone, &zones}
	}
	return zoneList, nil
}

func (zones Zones) Add(zone dnsprovider.Zone) (dnsprovider.Zone, error) {
	dnsName := zone.Name()
	callerReference := string(util.NewUUID())
	input := route53.CreateHostedZoneInput{Name: &dnsName, CallerReference: &callerReference}
	output, err := zones.interface_.service.CreateHostedZone(&input)
	if err != nil {
		return nil, err
	}
	return &Zone{output.HostedZone, &zones}, nil
}

func (zones Zones) Remove(zone dnsprovider.Zone) error {
	zoneId := zone.(*Zone).impl.Id
	input := route53.DeleteHostedZoneInput{Id: zoneId}
	_, err := zones.interface_.service.DeleteHostedZone(&input)
	if err != nil {
		return err
	}
	return nil
}
func (zones Zones) New(name string) (dnsprovider.Zone, error) {
	id := string(util.NewUUID())
	managedZone := route53.HostedZone{Id: &id, Name: &name}
	return &Zone{&managedZone, &zones}, nil
}


text:
const chai = require('chai');
chai.use(require('sinon-chai'));
const expect = chai.expect;
const sinon = require('sinon');

const { fetchMock, theGlobal } = testGlobals;
describe('spy()', () => {
	it('when mocking globally, spy falls through to global fetch', async () => {
		const originalFetch = theGlobal.fetch;
		const fetchSpy = sinon.stub().returns(Promise.resolve('example'));

		theGlobal.fetch = fetchSpy;

		fetchMock.spy();

		await theGlobal.fetch('http://a.com/', { method: 'get' });
		expect(fetchSpy).calledWith('http://a.com/', { method: 'get' });
		fetchMock.restore();
		theGlobal.fetch = originalFetch;
	});

	it('when mocking locally, spy falls through to configured fetch', async () => {
		const fetchSpy = sinon.stub().returns(Promise.resolve('dummy'));

		const fm = fetchMock.sandbox();
		fm.config.fetch = fetchSpy;

		fm.spy();
		await fm.fetchHandler('http://a.com/', { method: 'get' });
		expect(fetchSpy).calledWith('http://a.com/', { method: 'get' });
		fm.restore();
	});

	it('can restrict spying to a route', async () => {
		const fetchSpy = sinon.stub().returns(Promise.resolve('dummy'));

		const fm = fetchMock.sandbox();
		fm.config.fetch = fetchSpy;

		fm.spy({ url: 'http://a.com/', method: 'get' });
		await fm.fetchHandler('http://a.com/', { method: 'get' });
		expect(fetchSpy).calledWith('http://a.com/', { method: 'get' });
		expect(() =>
			fm.fetchHandler('http://b.com/', { method: 'get' })
		).to.throw();
		expect(() =>
			fm.fetchHandler('http://a.com/', { method: 'post' })
		).to.throw();
		fm.restore();
	});
});


text:
package org.ovirt.engine.ui.userportal.client.protocols;

import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.ui.frontend.Frontend;

import com.google.gwt.core.client.GWT;

public class RdpConnector {
    private String server;
    private Boolean fullScreen = true;
    private String fullScreenTitle;
    private Integer width = 640;
    private Integer height = 480;
    private Integer authenticationLevel = 2;
    private Boolean enableCredSspSupport = false; // Disable 'Credential Security Support Provider (CredSSP)' to enable
    // SSO.
    private Boolean redirectDrives = false;
    private Boolean redirectPrinters = false;
    private Boolean redirectClipboard = false;
    private Boolean redirectSmartCards = false;

    private Event disconnectedEvent;

    public RdpConnector() {

    }

    public RdpConnector(String server, Event disconnectedEvent) {
        setServer(server);
        setDisconnectedEvent(disconnectedEvent);
    }

    public Event getDisconnectedEvent() {
        return disconnectedEvent;
    }

    public void setDisconnectedEvent(Event disconnectedEvent) {
        this.disconnectedEvent = disconnectedEvent;
    }

    public String getServer() {
        return server;
    }

    public void setServer(String server) {
        this.server = server;
    }

    public Boolean getFullScreen() {
        return fullScreen;
    }

    public void setFullScreen(Boolean fullScreen) {
        this.fullScreen = fullScreen;
    }

    public String getFullScreenTitle() {
        return fullScreenTitle;
    }

    public void setFullScreenTitle(String fullScreenTitle) {
        this.fullScreenTitle = fullScreenTitle;
    }

    public Integer getWidth() {
        return width;
    }

    public void setWidth(Integer width) {
        this.width = width;
    }

    public Integer getHeight() {
        return height;
    }

    public void setHeight(Integer height) {
        this.height = height;
    }

    public Integer getAuthenticationLevel() {
        return authenticationLevel;
    }

    public void setAuthenticationLevel(Integer authenticationLevel) {
        this.authenticationLevel = authenticationLevel;
    }

    public Boolean getEnableCredSspSupport() {
        return enableCredSspSupport;
    }

    public void setEnableCredSspSupport(Boolean enableCredSspSupport) {
        this.enableCredSspSupport = enableCredSspSupport;
    }

    public Boolean getRedirectDrives() {
        return redirectDrives;
    }

    public void setRedirectDrives(Boolean redirectDrives) {
        this.redirectDrives = redirectDrives;
    }

    public Boolean getRedirectPrinters() {
        return redirectPrinters;
    }

    public void setRedirectPrinters(Boolean redirectPrinters) {
        this.redirectPrinters = redirectPrinters;
    }

    public Boolean getRedirectClipboard() {
        return redirectClipboard;
    }

    public void setRedirectClipboard(Boolean redirectClipboard) {
        this.redirectClipboard = redirectClipboard;
    }

    public Boolean getRedirectSmartCards() {
        return redirectSmartCards;
    }

    public void setRedirectSmartCards(Boolean redirectSmartCards) {
        this.redirectSmartCards = redirectSmartCards;
    }

    public String getRdpCabURL() {
        return GWT.getModuleBaseURL() + "msrdp.cab";
    }

    public String getVdcUserNameAndDomain() {
        String username = Frontend.getLoggedInUser().getUserName();
        String domain = Frontend.getLoggedInUser().getDomainControler();

        return username.contains("@") ? username : username + "@" + domain;
    }

    public String getVdcUserName() {
        return Frontend.getLoggedInUser().getUserName();
    }

    public String getVdcUserPassword() {
        return Frontend.getLoggedInUser().getPassword();
    }

    public String getVdcUserDomainController() {
        return Frontend.getLoggedInUser().getDomainControler();
    }

    public native void init() /*-{
        var server = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getServer()();
        var rdpCabURL = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getRdpCabURL()();
        var connectAreaDiv = document.createElement("<div style='display: none' id='connectArea'/>");
        //var objStr = "<object id='MsRdpClient_" + server + "' onReadyStateChange='OnControlLoad()' onError='OnControlLoadError()' classid='CLSID:4eb89ff4-7f78-4a0f-8b8d-2bf02e94e4b2' width='800' height='600'></object>";
        var objStr = "<object id='MsRdpClient_" + server + "' codebase='" + rdpCabURL
                + "' classid='CLSID:4eb89ff4-7f78-4a0f-8b8d-2bf02e94e4b2' width='800' height='600'></object>";
        var client = document.createElement(objStr);
        connectAreaDiv.appendChild(client);
        document.body.appendChild(connectAreaDiv);

        function OnControlLoad() {
        }

        function OnControlLoadError() {
        }
    }-*/;

    public native void connect() /*-{
        function OnConnected() {
        }

        function OnDisconnected(disconnectCode) {
            var extendedDiscReason = MsRdpClient.ExtendedDisconnectReason;
            var errorCodeEventArgs = @org.ovirt.engine.ui.uicommon.models.vms.ErrorCodeEventArgs::new(I)(disconnectCode);
            disconnectedEvent.@org.ovirt.engine.core.compat.Event::raise(Ljava/lang/Object;Lorg/ovirt/engine/core/compat/EventArgs;)(model, errorCodeEventArgs);

            $wnd.document.body.removeChild(MsRdpClient);
        }

        var server = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getServer()();
        var fullScreen = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getFullScreen()();
        var fullScreenTitle = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getFullScreenTitle()();
        var width = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getWidth()();
        var height = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getHeight()();
        var authenticationLevel = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getAuthenticationLevel()();
        var enableCredSspSupport = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getEnableCredSspSupport()();
        var redirectDrives = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getRedirectDrives()();
        var redirectPrinters = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getRedirectPrinters()();
        var redirectClipboard = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getRedirectClipboard()();
        var redirectSmartCards = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getRedirectSmartCards()();
        var disconnectedEvent = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getDisconnectedEvent()();
        var userName = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getVdcUserNameAndDomain()();
        var password = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getVdcUserPassword()();
        var domain = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getVdcUserDomainController()();
        var model = this;

        //		var MsRdpClient = document.getElementById("MsRdpClient_"+server);
        //TODO: Only in DEBUG mode
        //		alert("Server [" + server + "] fullScreen? [" + fullScreen + "], FullScreen Title [" +
        //			fullScreenTitle + "], width [" + width + "], height [" + height + "], auth level [" + authenticationLevel + "] enableCredSSPSupport? [" +
        //			enableCredSspSupport + "] redirect drives? [" + redirectDrives + "], redirect printers? [" + redirectPrinters + "], redirect clipboard? [" +
        //			redirectClipboard + "], redirect SmartCards [" + redirectSmartCards + "]");

        // Remove previous client object
        var previousMsRdpClient = $wnd.document.getElementById('MsRdpClient_' + server);
        if (previousMsRdpClient)
            $wnd.document.body.removeChild(previousMsRdpClient);

        var MsRdpClient = $wnd.document.createElement("object");
        $wnd.document.body.appendChild(MsRdpClient);

        MsRdpClient.id = "MsRdpClient_" + server;
        MsRdpClient.classid = "CLSID:4eb89ff4-7f78-4a0f-8b8d-2bf02e94e4b2";
        MsRdpClient.server = server;
        MsRdpClient.FullScreen = fullScreen;
        MsRdpClient.desktopWidth = screen.width;
        MsRdpClient.desktopHeight = screen.height;
        MsRdpClient.width = 1;
        MsRdpClient.height = 1;
        MsRdpClient.UserName = userName;
        MsRdpClient.AdvancedSettings.ClearTextPassword = password;
        MsRdpClient.AdvancedSettings5.AuthenticationLevel = authenticationLevel;
        MsRdpClient.AdvancedSettings7.EnableCredSspSupport = enableCredSspSupport;
        MsRdpClient.AdvancedSettings2.RedirectDrives = redirectDrives;
        MsRdpClient.AdvancedSettings2.RedirectPrinters = redirectPrinters;
        MsRdpClient.AdvancedSettings2.RedirectClipboard = redirectClipboard;
        MsRdpClient.AdvancedSettings2.RedirectSmartCards = redirectSmartCards;
        MsRdpClient.AdvancedSettings2.ConnectionBarShowRestoreButton = false;

        MsRdpClient.attachEvent('OnConnected', OnConnected);
        MsRdpClient.attachEvent('OnDisconnected', OnDisconnected);

        MsRdpClient.connect();
    }-*/;
}


text:
Aria.classDefinition({
    $classpath : "test.aria.utils.FunctionWriterTest",
    $extends : "aria.jsunit.TestCase",
    $dependencies : ["aria.utils.FunctionWriter"],
    $prototype : {
        testCreateFunction : function () {
            var writer = new aria.utils.FunctionWriter(["a", "b"]);
            writer.write("return a+b;");
            var fn = writer.createFunction();
            writer.$dispose();
            this.assertTrue(fn(1, 3) == 4);
            this.assertTrue(fn(5, 6) == 11);
        },

        testGetDotProperty : function () {
            this.dotPropertyTest("varName");
            this.dotPropertyTest("otherValue");
            this.dotPropertyTest("137");
            this.dotPropertyTest("1blabla");
            this.dotPropertyTest("blabla123");
            this.dotPropertyTest("bla?bla");
            this.dotPropertyTest("bla-bla");
            this.dotPropertyTest("bla*bla");
            this.dotPropertyTest("bla+bla");
            this.dotPropertyTest("bla'bla");
            this.dotPropertyTest('bla"bla');
            this.dotPropertyTest('bla"b\'la');
        },

        dotPropertyTest : function (propName) {
            var writer = new aria.utils.FunctionWriter(["arg"]);
            writer.write("return arg", writer.getDotProperty(propName), ";");
            var fn = writer.createFunction();
            writer.$dispose();
            var okValue = {};
            var myObj = {};
            myObj[propName] = okValue;
            this.assertTrue(fn(myObj) === okValue);
        }
    }
});