text:
package com.github.ljtfreitas.restify.http.client.jdk;

import java.net.Proxy;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.Optional;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;

public class HttpClientRequestConfiguration {

	private static final int DEFAULT_CHUNK_SIZE = 4096;

	private int connectionTimeout = 0;
	private int readTimeout = 0;
	private boolean followRedirects = true;
	private boolean useCaches = true;
	private boolean bufferRequestBody = true;
	private boolean outputStreaming = true;
	private int chunkSize = DEFAULT_CHUNK_SIZE;

	private Charset charset = Charset.forName("UTF-8");
	private Proxy proxy = null;

	private HttpClientRequestSsl ssl = new HttpClientRequestSsl();

	private HttpClientRequestConfiguration() {
	}

	private HttpClientRequestConfiguration(HttpClientRequestConfiguration source) {
		this.connectionTimeout = source.connectionTimeout;
		this.readTimeout = source.readTimeout;
		this.followRedirects = source.followRedirects;
		this.useCaches = source.useCaches;
		this.bufferRequestBody = source.bufferRequestBody;
		this.outputStreaming = source.outputStreaming;
		this.chunkSize = source.chunkSize;
		this.charset = source.charset;
		this.proxy = source.proxy;
		this.ssl = new HttpClientRequestSsl(source.ssl);
	}

	public int connectionTimeout() {
		return connectionTimeout;
	}

	public int readTimeout() {
		return readTimeout;
	}

	public boolean followRedirects() {
		return followRedirects;
	}

	public boolean useCaches() {
		return useCaches;
	}

	public boolean bufferRequestBody() {
		return bufferRequestBody;
	}

	public boolean outputStreaming() {
		return outputStreaming;
	}

	public int chunkSize() {
		return chunkSize;
	}

	public Charset charset() {
		return charset;
	}

	public Optional<Proxy> proxy() {
		return Optional.ofNullable(proxy);
	}

	public HttpClientRequestSsl ssl() {
		return ssl;
	}

	public static HttpClientRequestConfiguration useDefault() {
		return new HttpClientRequestConfiguration();
	}

	public class HttpClientRequestSsl {

		private SSLSocketFactory sslSocketFactory;
		private HostnameVerifier hostnameVerifier;

		private HttpClientRequestSsl() {
		}

		private HttpClientRequestSsl(HttpClientRequestSsl source) {
			this.sslSocketFactory = source.sslSocketFactory;
			this.hostnameVerifier = source.hostnameVerifier;
		}

		public Optional<SSLSocketFactory> sslSocketFactory() {
			return Optional.ofNullable(sslSocketFactory);
		}

		public Optional<HostnameVerifier> hostnameVerifier() {
			return Optional.ofNullable(hostnameVerifier);
		}
	}

	public static class Builder {

		private HttpClientRequestConfiguration configuration = new HttpClientRequestConfiguration();

		public Builder connectionTimeout(int connectionTimeout) {
			configuration.connectionTimeout = connectionTimeout;
			return this;
		}

		public Builder connectionTimeout(Duration duration) {
			configuration.connectionTimeout = (int) duration.toMillis();
			return this;
		}

		public Builder readTimeout(int readTimeout) {
			configuration.readTimeout = readTimeout;
			return this;
		}

		public Builder readTimeout(Duration duration) {
			configuration.readTimeout = (int) duration.toMillis();
			return this;
		}

		public Builder charset(Charset charset) {
			configuration.charset = charset;
			return this;
		}

		public Builder proxy(Proxy proxy) {
			configuration.proxy = proxy;
			return this;
		}

		public FolllowRedirectsBuilder followRedirects() {
			return new FolllowRedirectsBuilder();
		}

		public Builder followRedirects(boolean enabled) {
			configuration.followRedirects = enabled;
			return this;
		}

		public UseCachesBuilder useCaches() {
			return new UseCachesBuilder();
		}

		public Builder useCaches(boolean enabled) {
			configuration.useCaches = enabled;
			return this;
		}

		public BufferRequestBodyBuilder bufferRequestBody() {
			return new BufferRequestBodyBuilder();
		}

		public Builder bufferRequestBody(boolean enabled) {
			configuration.bufferRequestBody = enabled;
			return this;
		}

		public OutputStreamingBuilder outputStreaming() {
			return new OutputStreamingBuilder();
		}

		public Builder outputStreaming(boolean enabled) {
			configuration.outputStreaming = enabled;
			return this;
		}

		public SslBuilder ssl() {
			return new SslBuilder();
		}

		public HttpClientRequestConfiguration build() {
			return new HttpClientRequestConfiguration(configuration);
		}

		public class FolllowRedirectsBuilder {

			public Builder enabled() {
				configuration.followRedirects = true;
				return Builder.this;
			}

			public Builder disabled() {
				configuration.followRedirects = false;
				return Builder.this;
			}
		}

		public class UseCachesBuilder {

			public Builder enabled() {
				configuration.useCaches = true;
				return Builder.this;
			}

			public Builder disabled() {
				configuration.followRedirects = false;
				return Builder.this;
			}
		}

		public class BufferRequestBodyBuilder {

			public Builder enabled() {
				configuration.bufferRequestBody = true;
				return Builder.this;
			}

			public Builder disabled() {
				configuration.bufferRequestBody = false;
				return Builder.this;
			}
		}

		public class OutputStreamingBuilder {

			public OutputStreamingBuilder enabled() {
				configuration.outputStreaming = true;
				return this;
			}

			public Builder disabled() {
				configuration.outputStreaming = false;
				return Builder.this;
			}

			public OutputStreamingBuilder chunkSize(int chunkSize) {
				configuration.chunkSize = chunkSize;
				return this;
			}

			public Builder and() {
				return Builder.this;
			}
		}

		public class SslBuilder {

			public SslBuilder sslSocketFactory(SSLSocketFactory sslSocketFactory) {
				configuration.ssl().sslSocketFactory = sslSocketFactory;
				return this;
			}

			public SslBuilder hostnameVerifier(HostnameVerifier hostnameVerifier) {
				configuration.ssl().hostnameVerifier = hostnameVerifier;
				return this;
			}

			public Builder and() {
				return Builder.this;
			}
		}
	}
}


text:
@interface MRCShowcaseHeaderView : UIView <MRCReactiveView>

@end

redpajama_set_name: RedPajamaGithub


text:
<!--

********************************************************************************

WARNING:

    DO NOT EDIT "mediawiki/README.md"

    IT IS AUTO-GENERATED

    (from the other files in "mediawiki/" combined with a set of templates)

********************************************************************************

-->

# Quick reference

-	**Maintained by**:
	[MediaWiki community & Docker Community](https://github.com/wikimedia/mediawiki-docker)

-	**Where to get help**:
	[the Docker Community Forums](https://forums.docker.com/), [the Docker Community Slack](https://dockr.ly/slack), or [Stack Overflow](https://stackoverflow.com/search?tab=newest&q=docker)

# Supported tags and respective `Dockerfile` links

-	[`1.37.1`, `1.37`, `stable`, `latest`](https://github.com/wikimedia/mediawiki-docker/blob/daebab6abd474474deb62c5544127f86dd507172/1.37/apache/Dockerfile)
-	[`1.37.1-fpm`, `1.37-fpm`, `stable-fpm`](https://github.com/wikimedia/mediawiki-docker/blob/daebab6abd474474deb62c5544127f86dd507172/1.37/fpm/Dockerfile)
-	[`1.37.1-fpm-alpine`, `1.37-fpm-alpine`, `stable-fpm-alpine`](https://github.com/wikimedia/mediawiki-docker/blob/daebab6abd474474deb62c5544127f86dd507172/1.37/fpm-alpine/Dockerfile)
-	[`1.36.3`, `1.36`, `legacy`](https://github.com/wikimedia/mediawiki-docker/blob/daebab6abd474474deb62c5544127f86dd507172/1.36/apache/Dockerfile)
-	[`1.36.3-fpm`, `1.36-fpm`, `legacy-fpm`](https://github.com/wikimedia/mediawiki-docker/blob/daebab6abd474474deb62c5544127f86dd507172/1.36/fpm/Dockerfile)
-	[`1.36.3-fpm-alpine`, `1.36-fpm-alpine`, `legacy-fpm-alpine`](https://github.com/wikimedia/mediawiki-docker/blob/daebab6abd474474deb62c5544127f86dd507172/1.36/fpm-alpine/Dockerfile)
-	[`1.35.5`, `1.35`, `lts`, `legacylts`](https://github.com/wikimedia/mediawiki-docker/blob/daebab6abd474474deb62c5544127f86dd507172/1.35/apache/Dockerfile)
-	[`1.35.5-fpm`, `1.35-fpm`, `lts-fpm`, `legacylts-fpm`](https://github.com/wikimedia/mediawiki-docker/blob/daebab6abd474474deb62c5544127f86dd507172/1.35/fpm/Dockerfile)
-	[`1.35.5-fpm-alpine`, `1.35-fpm-alpine`, `lts-fpm-alpine`, `legacylts-fpm-alpine`](https://github.com/wikimedia/mediawiki-docker/blob/daebab6abd474474deb62c5544127f86dd507172/1.35/fpm-alpine/Dockerfile)

# Quick reference (cont.)

-	**Where to file issues**:
	[https://phabricator.wikimedia.org/project/view/3094/](https://phabricator.wikimedia.org/project/view/3094/)

-	**Supported architectures**: ([more info](https://github.com/docker-library/official-images#architectures-other-than-amd64))
	[`amd64`](https://hub.docker.com/r/amd64/mediawiki/), [`arm32v5`](https://hub.docker.com/r/arm32v5/mediawiki/), [`arm32v6`](https://hub.docker.com/r/arm32v6/mediawiki/), [`arm32v7`](https://hub.docker.com/r/arm32v7/mediawiki/), [`arm64v8`](https://hub.docker.com/r/arm64v8/mediawiki/), [`i386`](https://hub.docker.com/r/i386/mediawiki/), [`ppc64le`](https://hub.docker.com/r/ppc64le/mediawiki/)

-	**Published image artifact details**:
	[repo-info repo's `repos/mediawiki/` directory](https://github.com/docker-library/repo-info/blob/master/repos/mediawiki) ([history](https://github.com/docker-library/repo-info/commits/master/repos/mediawiki))
	(image metadata, transfer size, etc)

-	**Image updates**:
	[official-images repo's `library/mediawiki` label](https://github.com/docker-library/official-images/issues?q=label%3Alibrary%2Fmediawiki)
	[official-images repo's `library/mediawiki` file](https://github.com/docker-library/official-images/blob/master/library/mediawiki) ([history](https://github.com/docker-library/official-images/commits/master/library/mediawiki))

-	**Source of this description**:
	[docs repo's `mediawiki/` directory](https://github.com/docker-library/docs/tree/master/mediawiki) ([history](https://github.com/docker-library/docs/commits/master/mediawiki))

# What is MediaWiki?

MediaWiki is free and open-source wiki software. Originally developed by Magnus Manske and improved by Lee Daniel Crocker, it runs on many websites, including Wikipedia, Wiktionary and Wikimedia Commons. It is written in the PHP programming language and stores the contents into a database. Like WordPress, which is based on a similar licensing and architecture, it has become the dominant software in its category.

> [wikipedia.org/wiki/MediaWiki](https://en.wikipedia.org/wiki/MediaWiki)

![logo](https://raw.githubusercontent.com/docker-library/docs/27b797857efd9253c0981c09696f579a167062d4/mediawiki/logo.svg?sanitize=true)

# How to use this image

The basic pattern for starting a `mediawiki` instance is:

```console
$ docker run --name some-mediawiki -d mediawiki
```

If you'd like to be able to access the instance from the host without the container's IP, standard port mappings can be used:

```console
$ docker run --name some-mediawiki -p 8080:80 -d mediawiki
```

Then, access it via `http://localhost:8080` or `http://host-ip:8080` in a browser.

There are multiple database types supported by this image, most easily used via standard container linking. In the default configuration, SQLite can be used to avoid a second container and write to flat-files. More detailed instructions for different (more production-ready) database types follow.

When first accessing the webserver provided by this image, it will go through a brief setup process. The details provided below are specifically for the "Set up database" step of that configuration process.

## MySQL

```console
$ docker run --name some-mediawiki --link some-mysql:mysql -d mediawiki
```

-	Database type: `MySQL, MariaDB, or equivalent`
-	Database name/username/password: `<details for accessing your MySQL instance>` (`MYSQL_USER`, `MYSQL_PASSWORD`, `MYSQL_DATABASE`; see environment variables in the description for [`mariadb`](https://hub.docker.com/_/mariadb/))
-	ADVANCED OPTIONS; Database host: `some-mysql` (for using the `/etc/hosts` entry added by `--link` to access the linked container's MySQL instance)

## Volumes

By default, this image does not include any volumes.

The paths `/var/www/html/images` and `/var/www/html/LocalSettings.php` are things that generally ought to be volumes, but do not explicitly have a `VOLUME` declaration in this image because volumes cannot be removed.

```console
$ docker run --rm mediawiki tar -cC /var/www/html/sites . | tar -xC /path/on/host/sites
```

## ... via [`docker stack deploy`](https://docs.docker.com/engine/reference/commandline/stack_deploy/) or [`docker-compose`](https://github.com/docker/compose)

Example `stack.yml` for `mediawiki`:

```yaml
# MediaWiki with MariaDB
#
# Access via "http://localhost:8080"
#   (or "http://$(docker-machine ip):8080" if using docker-machine)
version: '3'
services:
  mediawiki:
    image: mediawiki
    restart: always
    ports:
      - 8080:80
    links:
      - database
    volumes:
      - /var/www/html/images
      # After initial setup, download LocalSettings.php to the same directory as
      # this yaml and uncomment the following line and use compose to restart
      # the mediawiki service
      # - ./LocalSettings.php:/var/www/html/LocalSettings.php
  database:
    image: mariadb
    restart: always
    environment:
      # @see https://phabricator.wikimedia.org/source/mediawiki/browse/master/includes/DefaultSettings.php
      MYSQL_DATABASE: my_wiki
      MYSQL_USER: wikiuser
      MYSQL_PASSWORD: example
      MYSQL_RANDOM_ROOT_PASSWORD: 'yes'
```

[![Try in PWD](https://github.com/play-with-docker/stacks/raw/cff22438cb4195ace27f9b15784bbb497047afa7/assets/images/button.png)](http://play-with-docker.com?stack=https://raw.githubusercontent.com/docker-library/docs/7b72bad5e2c684fa5829aecd3bf5b17a6e685963/mediawiki/stack.yml)

Run `docker stack deploy -c stack.yml mediawiki` (or `docker-compose -f stack.yml up`), wait for it to initialize completely, and visit `http://swarm-ip:8080`, `http://localhost:8080`, or `http://host-ip:8080` (as appropriate).

## Adding additional libraries / extensions

This image does not provide any additional PHP extensions or other libraries, even if they are required by popular plugins. There are an infinite number of possible plugins, and they potentially require any extension PHP supports. Including every PHP extension that exists would dramatically increase the image size.

If you need additional PHP extensions, you'll need to create your own image `FROM` this one. The [documentation of the `php` image](https://github.com/docker-library/docs/blob/31280550a3c7104fef824450753844d2f3d917be/php/README.md#how-to-install-more-php-extensions) explains how to compile additional extensions.

The following Docker Hub features can help with the task of keeping your dependent images up-to-date:

-	[Automated Builds](https://docs.docker.com/docker-hub/builds/) let Docker Hub automatically build your Dockerfile each time you push changes to it.

# Image Variants

The `mediawiki` images come in many flavors, each designed for a specific use case.

## `mediawiki:<version>`

This is the defacto image. If you are unsure about what your needs are, you probably want to use this one. It is designed to be used both as a throw away container (mount your source code and start the container to start your app), as well as the base to build other images off of.

## `mediawiki:<version>-alpine`

This image is based on the popular [Alpine Linux project](https://alpinelinux.org), available in [the `alpine` official image](https://hub.docker.com/_/alpine). Alpine Linux is much smaller than most distribution base images (~5MB), and thus leads to much slimmer images in general.

This variant is useful when final image size being as small as possible is your primary concern. The main caveat to note is that it does use [musl libc](https://musl.libc.org) instead of [glibc and friends](https://www.etalabs.net/compare_libcs.html), so software will often run into issues depending on the depth of their libc requirements/assumptions. See [this Hacker News comment thread](https://news.ycombinator.com/item?id=10782897) for more discussion of the issues that might arise and some pro/con comparisons of using Alpine-based images.

To minimize image size, it's uncommon for additional related tools (such as `git` or `bash`) to be included in Alpine-based images. Using this image as a base, add the things you need in your own Dockerfile (see the [`alpine` image description](https://hub.docker.com/_/alpine/) for examples of how to install packages if you are unfamiliar).

# License

View [license information](https://phabricator.wikimedia.org/source/mediawiki/browse/master/COPYING) for the software contained in this image.

As with all Docker images, these likely also contain other software which may be under other licenses (such as Bash, etc from the base distribution, along with any direct or indirect dependencies of the primary software being contained).

Some additional license information which was able to be auto-detected might be found in [the `repo-info` repository's `mediawiki/` directory](https://github.com/docker-library/repo-info/tree/master/repos/mediawiki).

As for any pre-built image usage, it is the image user's responsibility to ensure that any use of this image complies with any relevant licenses for all software contained within.


text:
This WordPress plugin has been deprecated. The [Twitter plugin for WordPress](https://github.com/twitter/wordpress) includes support for Vine embeds with helper JavaScript; webmasters can choose to enable or disable specific product features by acting on a filter.

Vine embeds have been available as an [oEmbed provider default](https://codex.wordpress.org/Embeds) since [WordPress version 4.1](https://codex.wordpress.org/Version_4.1), released in December 2014.

The Vine plugin for WordPress replaces a Vine video URL or Vine macro with Vine embed HTML retrieved from [Vine's oEmbed API endpoint](https://dev.twitter.com/web/vine/oembed).

* `https://vine.co/v/Ml16lZVTTxe`
* `[vine id="Ml16lZVTTxe"]`

The Vine plugin adjusts Vine embed HTML to match the [$content_width](http://codex.wordpress.org/Content_Width) defined by your theme.

Vine JavaScript loads asynchronously using the `vine-embed-js` registered script handle: an improvement over the standard oEmbed response combining HTML markup and script loading.

see [readme.txt](readme.txt) for readme documentation compatible with the [WordPress plugin readme standard](https://wordpress.org/plugins/about/readme.txt). Release versions of this plugin are distributed through [the Vine listing in the WordPress plugin repository](https://wordpress.org/plugins/vine/).

## Authors
* Niall Kennedy <https://twitter.com/niall>

A full list of [contributors](https://github.com/vine/wordpress/graphs/contributors) can be found on GitHub.

## License
Copyright 2014 Vine Labs, Inc.

Licensed under the MIT License: http://opensource.org/licenses/MIT


text:
package com.jhlabs.math;

public class MarbleFunction extends CompoundFunction2D {

  public MarbleFunction() {
    super(new TurbulenceFunction(new Noise(), 6));
  }

  public MarbleFunction(Function2D basis) {
    super(basis);
  }

  @Override
  public float evaluate(float x, float y) {
    return (float) Math.pow(0.5 * (Math.sin(8. * basis.evaluate(x, y)) + 1), 0.77);
  }
}


text:
using System.Collections.Generic;

namespace Azure.Management.Resources.Models
{
    /// <summary> List of deployments. </summary>
    public partial class DeploymentListResult
    {
        /// <summary> Initializes a new instance of DeploymentListResult. </summary>
        internal DeploymentListResult()
        {
        }

        /// <summary> Initializes a new instance of DeploymentListResult. </summary>
        /// <param name="value"> An array of deployments. </param>
        /// <param name="nextLink"> The URL to use for getting the next set of results. </param>
        internal DeploymentListResult(IReadOnlyList<DeploymentExtended> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> An array of deployments. </summary>
        public IReadOnlyList<DeploymentExtended> Value { get; }
        /// <summary> The URL to use for getting the next set of results. </summary>
        public string NextLink { get; }
    }
}


text:
var Twitter = require('twitter'),
    app = require('express')();

var twitterClient = new Twitter({
    consumer_key: process.env.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
    access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});

function getTweets(req, res) {
    var params = {screen_name: req.params.screen_name},
        textOfTweets;

    twitterClient.get('statuses/user_timeline', params, function (error, tweets, response) {
        if (!error) {
            textOfTweets = tweets.map(function (tweet) {
                return tweet.text;
            });
            console.log(textOfTweets);
            res.json(textOfTweets);
        } else {
            console.error(error);
            res.status(500).json({error: 'Something went wrong!'});
        }
    });
}

// app routes:
app.get('/tweets/:screen_name', getTweets);

// start app listening
var port = process.env.VCAP_APP_PORT || 3000;
app.listen(port);
console.log('listening at:', port);


text:
package org.apache.axis2.context;

import java.io.Serializable;

/**
 * This class holds the difference between two properties which are stored in the
 * AbstractContext
 */
public class PropertyDifference implements Serializable {

    private String key;
    private Object value;
    private boolean isRemoved;

    public PropertyDifference(String key, Object value, boolean isRemoved) {
        this.key = key;
        this.value = value;
        this.isRemoved = isRemoved;
    }

    public String getKey() {
        return key;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public boolean isRemoved() {
        return isRemoved;
    }

    public void setRemoved(boolean removed) {
        isRemoved = removed;
    }
}


text:
const puppeteer = require('puppeteer')

;(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    slowMo: 100,
    defaultViewport: { width: 1440, height: 1000 },
    args: [`--window-size=${1440},${1000}`],
    ignoreHTTPSErrors: false, //忽略 https 报错
  })
  const page = await browser.newPage()
  await page.goto('https://www.baidu.com')
})()


text: Github client for iOS


text:
typedef struct _tHeapEntry {
	UWORD uwPriority;
	void *pData;
} tHeapEntry;

typedef struct _tHeap {
	UWORD uwMaxEntries;
	UWORD uwCount;
	tHeapEntry *pEntries;
} tHeap;

tHeap *heapCreate(UWORD uwMaxEntries);

void heapDestroy(tHeap *pHeap);

void heapPush(tHeap *pHeap, void *pData, UWORD uwPriority);

void *heapPop(tHeap *pHeap);

static inline void heapClear(tHeap *pHeap) {
	pHeap->uwCount = 0;
}

#endif // GUARD_OF_GAMESTATES_GAME_AI_HEAP_H


text:
import json
from config.api1_1_config import *
from on_http_api1_1 import ProfilesApi as Profiles
from on_http_api1_1 import rest
from on_http_api1_1.rest import ApiException
from modules.logger import Log
from datetime import datetime
from proboscis.asserts import assert_equal
from proboscis.asserts import assert_false
from proboscis.asserts import assert_raises
from proboscis.asserts import assert_not_equal
from proboscis.asserts import assert_true
from proboscis import SkipTest
from proboscis import test
from json import dumps, loads

LOG = Log(__name__)

@test(groups=['profiles.tests'])
class ProfilesTests(object):

    def __init__(self):
        self.__client = config.api_client
        self.addedName = "ProfileName_1"
        self.addedContents = "Random Content"

    @test(groups=['profiles.tests', 'profile_library_get'])
    def test_profiles_library_get(self):
        """ Testing GET:/library"""
        Profiles().profiles_library_get()
        assert_equal(200,self.__client.last_response.status)
        assert_not_equal(0, len(json.loads(self.__client.last_response.data)), message='Profile list was empty!')

    #Skipping this test until the Profile_API module supports content-type octet-stream
    #@test(groups=['profile_library_put'], depends_on_groups=['profile_library_get'])
    def test_profiles_put(self):
        """ Testing PUT:/nodes """
        #Get the number of profiles before we add one
        Profiles().profiles_library_get()
        profilesBefore = len(json.loads(self.__client.last_response.data))

        #Make sure that there is no profile with the same name from previous test runs
        rawj=  json.loads(self.__client.last_response.data)
        listLen =len(json.loads(self.__client.last_response.data))

        lastProfile =  rawj[listLen-1]
        lastName = str(lastProfile.get('name'))

        inList = False
        for i, val in enumerate (rawj):
            if ( self.addedName ==  str (rawj[i].get('name')) or inList ):
                inList = True
                nameList = str (rawj[i].get('name')).split('_')
                suffix= int (nameList[1]) + 1
                self.addedName = nameList[0]+ '_' + str(suffix)

        LOG.info ("added name " +  self.addedName)

        #add a profile
        LOG.info('Adding a profile named= {0}'.format(self.addedName))
        Profiles().profiles_library_identifier_put(self.addedName,body=self.addedContents)
        resp= self.__client.last_response
        assert_equal(200,resp.status)

        #Get the number of profiles after we added one
        Profiles().profiles_library_get()
        profilesAfter = len(json.loads(self.__client.last_response.data))
        resp= self.__client.last_response
        assert_equal(200,resp.status, message=resp.reason)

        #Validate that the profile has been added
        assert_equal(profilesAfter,profilesBefore+1)

        #Validate the content is as expected
        rawj=  json.loads(self.__client.last_response.data)
        listLen =len(json.loads(self.__client.last_response.data))
        readDict= rawj[listLen-1]
        readName= readDict.get('name')
        readContents  = readDict.get('contents')
        assert_equal(readName,self.addedName)
        assert_equal(readContents,self.addedContents)

    #Skipging since it is dependent on the PUT function
    #@test(groups=['profiles_library_identifier'], depends_on_groups=['profile_library_put'])
    def test_profiles_library_identifier_get_putdependent(self):
        """ Testing GET:/library/:id"""

        Profiles().profiles_library_identifier_get(self.addedName)
        readDict=  json.loads(self.__client.last_response.data)
        readContents  = readDict.get('contents')
        LOG.info('Reading the profile that was added,  {0}'.format(self.addedName))
        assert_equal(readContents,self.addedContents)

    @test(groups=['profiles_library_identifier'])
    def test_profiles_library_identifier_get(self):
        """ Testing GET:/library/:id"""
        Profiles().profiles_library_identifier_get( "boilerplate.ipxe")
        readDict=  json.loads(self.__client.last_response.data)
        readName  = readDict.get('name')
        LOG.info('Reading the profile that was added,  {0}'.format(readName))
        assert_equal(readName,"boilerplate.ipxe")

    @test(groups=['profiles_library_identifier_negative'], depends_on_groups=['profile_library_put'])
    def test_profiles_library_identifier_negative_get(self):
        """ Negative Testing GET:/library/:id"""
        try:
            Profiles().profiles_library_identifier_get('wrongProfileName')
        except ApiException as e:
           assert_equal(404,e.status, message = 'status should be 404')
        except (TypeError, ValueError) as e:
           assert(e.message);


text:
package io.github.mthli.Bitocle.Repo;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.database.SQLException;
import android.view.*;
import android.widget.*;
import io.github.mthli.Bitocle.Commit.CommitItemAdapter;
import io.github.mthli.Bitocle.Commit.CommitTask;
import io.github.mthli.Bitocle.Database.Bookmark.BAction;
import io.github.mthli.Bitocle.Database.Repo.RAction;
import io.github.mthli.Bitocle.Main.MainFragment;
import io.github.mthli.Bitocle.Main.RefreshType;
import io.github.mthli.Bitocle.R;

import java.util.List;

public class RepoItemAdapter extends ArrayAdapter<RepoItem> {
    private MainFragment mainFragment;
    private Context context;
    private int layoutResId;
    private List<RepoItem> repoItemList;

    public RepoItemAdapter(
            MainFragment mainFragment,
            Context context,
            int layoutResId,
            List<RepoItem> repoItemList
    ) {
        super(context, layoutResId, repoItemList);

        this.mainFragment = mainFragment;
        this.context = context;
        this.layoutResId = layoutResId;
        this.repoItemList = repoItemList;
    }

    private class Holder {
        ImageView icon;
        TextView title;
        TextView date;
        TextView content;
        TextView info;
        ImageButton overflow;
    }

    @Override
    public View getView(
            final int position,
            final View convertView,
            ViewGroup viewGroup
    ) {
        Holder holder;
        View view = convertView;

        if (view == null) {
            LayoutInflater layoutInflater = ((Activity) context).getLayoutInflater();
            view = layoutInflater.inflate(layoutResId, viewGroup, false);

            holder = new Holder();
            holder.icon = (ImageView) view.findViewById(R.id.repo_item_icon);
            holder.title = (TextView) view.findViewById(R.id.repo_item_title);
            holder.date = (TextView) view.findViewById(R.id.repo_item_date);
            holder.content = (TextView) view.findViewById(R.id.repo_item_content);
            holder.info = (TextView) view.findViewById(R.id.repo_item_info);
            holder.overflow = (ImageButton) view.findViewById(R.id.repo_item_overflow);

            view.setTag(holder);
        } else {
            holder = (Holder) view.getTag();
        }

        if (repoItemList.size() > 0) {
            final RepoItem repoItem = repoItemList.get(position);
            holder.icon.setImageDrawable(repoItem.getIcon());
            holder.title.setText(repoItem.getTitle());
            holder.date.setText(repoItem.getDate());
            holder.content.setText(repoItem.getContent());
            holder.info.setText(repoItem.getInfo());

            final PopupMenu popupMenu = new PopupMenu(context, holder.overflow);
            popupMenu.getMenuInflater().inflate(R.menu.repo_item_overflow, popupMenu.getMenu());
            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    mainFragment.getActionMenu().close(true);
                    switch (menuItem.getItemId()) {
                        case R.id.repo_item_overflow_commit:
                            ListView listView = mainFragment.getListView();
                            CommitItemAdapter commitItemAdapter = mainFragment.getCommitItemAdapter();

                            ActionBar actionBar = mainFragment.getActionBar();
                            actionBar.setTitle(repoItem.getTitle());
                            actionBar.setSubtitle(context.getString(R.string.commit_label));
                            actionBar.setDisplayHomeAsUpEnabled(true);

                            listView.setAdapter(commitItemAdapter);
                            commitItemAdapter.notifyDataSetChanged();
                            mainFragment.setRefreshType(RefreshType.COMMIT_FIRST);
                            mainFragment.CURRENT_ID = MainFragment.COMMIT_ID;

                            mainFragment.setLocation(position);
                            CommitTask commitTask = new CommitTask(mainFragment, repoItem);
                            mainFragment.setCommitTask(commitTask);
                            commitTask.execute();
                            break;
                        case R.id.repo_item_overflow_remove:
                            RAction rAction = new RAction(context);
                            BAction bAction = new BAction(context);
                            try {
                                rAction.openDatabase(true);
                            } catch (SQLException s) {
                                Toast.makeText(
                                        context,
                                        context.getString(R.string.repo_remove_failed),
                                        Toast.LENGTH_SHORT
                                ).show();
                                rAction.closeDatabase();
                                return false;
                            }
                            try {
                                bAction.openDatabase(true);
                            } catch (SQLException s) {
                                Toast.makeText(
                                        context,
                                        context.getString(R.string.bookmark_remove_failed),
                                        Toast.LENGTH_SHORT
                                ).show();
                                bAction.closeDatabase();
                                return false;
                            }

                            rAction.deleteRepo(repoItem.getGit());
                            String key = repoItem.getOwner() + context.getString(R.string.repo_path_root) + repoItem.getTitle();
                            bAction.unMarkByKey(key);
                            bAction.closeDatabase();
                            rAction.closeDatabase();

                            mainFragment.setRefreshType(RefreshType.REPO_ALREADY);
                            RepoTask repoTask = new RepoTask(mainFragment);
                            mainFragment.setRepoTask(repoTask);
                            repoTask.execute();

                            break;
                        default:
                            break;
                    }
                    return true;
                }
            });

            holder.overflow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mainFragment.getActionMenu().close(true);
                    popupMenu.show();
                }
            });
        }

        return view;
    }
}


text:
module Mixers
  # Access to project metadata.
  def self.metadata
    @metadata ||= (
      require 'yaml'
      YAML.load(File.new(File.dirname(__FILE__) + '/mixers.yml'))
    )
  end

  # Access to project metadata as constants.
  def self.const_missing(name)
    metadata[name.to_s.downcase] || super(name)
  end

  # TODO: Only here b/c of issue in Ruby 1.8.x.
  VERSION = version['version']
end

require 'mixers/cloneable.rb'
require 'mixers/enumargs.rb'
require 'mixers/equitable.rb'
require 'mixers/expirable.rb'
require 'mixers/hook.rb'
require 'mixers/instantiable.rb'
require 'mixers/ostructable.rb'
require 'mixers/preinitialize.rb'
require 'mixers/registerable.rb'


text:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "logger.h"

#include <event.h>
#include <event2/bufferevent_ssl.h>

#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ulimit.h>

#define MAX_BANNER_LEN 1024
#define BASE64_ALPHABET  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

struct config {
	uint16_t port;
	int connect_timeout;	// how long to wait for connecting (seconds)
	int read_timeout;		// how long to wait once connected for the banner (seconds)
	int current_running;
	int max_concurrent;
	struct event_base *base;
	struct bufferevent *stdin_bev;
	int stdin_closed;
	enum {FORMAT_HEX, FORMAT_BASE64, FORMAT_ASCII} format;
	char *send_str;
	long send_str_size;

	struct stats_st {
		int init_connected_hosts;	// Number of hosts we have even tried to connect to
		int connected_hosts;		// # hosts that picked up
		int conn_timed_out;			// # hosts that timed out during connection
		int read_timed_out;			// # hosts that connected, but sent no data (banner)
		int timed_out;				// # hosts that timed out at all (conn_timed_out+read_timed_out)?
		int completed_hosts;		// # hosts that presented a banner
	} stats;
};

struct state {
	struct config *conf;
	uint32_t ip;
	enum {CONNECTING, CONNECTED, RECEIVED} state;
};

void stdin_readcb(struct bufferevent *bev, void *arg);

void print_status(evutil_socket_t fd, short events, void *arg)
{
	struct event *ev;
	struct config *conf = arg;
	struct event_base *base = conf->base;
	struct timeval status_timeout = {1, 0};
	ev = evtimer_new(base, print_status, conf);
	evtimer_add(ev, &status_timeout);
	(void)fd; (void)events;

	log_info("banner-grab-tcp", "(%d/%d in use) - Totals: %d inited, %d connected, %d conn timeout, %d read timeout %d completed",
			conf->current_running, conf->max_concurrent,
			conf->stats.init_connected_hosts,
			conf->stats.connected_hosts, conf->stats.conn_timed_out,
			conf->stats.read_timed_out, conf->stats.completed_hosts);
}

void decrement_cur_running(struct state *st)
{
	struct config *conf = st->conf;
	conf->current_running--;
	log_debug("banner-grab-tcp", "done, down to %d",
			conf->current_running);
	if (evbuffer_get_length(bufferevent_get_input(conf->stdin_bev)) > 0) {
		stdin_readcb(conf->stdin_bev, conf);
	}
	free(st);

	if (conf->stdin_closed && conf->current_running == 0) {
		// Done
		log_info("banner-grab-tcp", "done");
		print_status(0, 0, conf);
		exit(0);
	}

}

void connect_cb(struct bufferevent *bev, short events, void *arg)
{
	struct state *st = arg;
	struct config *conf = st->conf;
	struct in_addr addr;
	addr.s_addr = st->ip;
	if (events & BEV_EVENT_CONNECTED) {
		struct timeval tv = {st->conf->read_timeout, 0};
		log_debug("banner-grab-tcp", "%s connected", inet_ntoa(addr));

		// Send data
		if (conf->send_str) {
			struct evbuffer *evout = bufferevent_get_output(bev);
			// HACK!!! TODO: make some messy parser that replaces ${IP} with IP etc
			// and allow null characters
			evbuffer_add_printf(evout, conf->send_str,
					inet_ntoa(addr), inet_ntoa(addr), inet_ntoa(addr), inet_ntoa(addr));
		}

		// Change from connect timeout to read timeout
		bufferevent_set_timeouts(bev, &tv, &tv);

		// Update state/stats
		st->state = CONNECTED;
		st->conf->stats.connected_hosts++;
	} else {
		if (st->state == CONNECTED) {
			// Print out that we just didn't receive data
			printf("%s X\n", inet_ntoa(addr));
			fflush(stdout);

			st->conf->stats.read_timed_out++;
		} else {
			st->conf->stats.conn_timed_out++;
		}
		log_debug("banner-grab-tcp", "%s bailing..", inet_ntoa(addr));
		bufferevent_free(bev);
		st->conf->stats.timed_out++;
		decrement_cur_running(st);
	}
}

// Grab these bytes, and close the connection.
// Even if we don't need to read any bytes,
// we have to have this so that libevent thinks we have
// a read event, so that it can timeout TCP connects
// (as a read timeout)
void read_cb(struct bufferevent *bev, void *arg)
{
	struct evbuffer *in = bufferevent_get_input(bev);
	struct state *st = arg;
	size_t len = evbuffer_get_length(in);
	struct in_addr addr;
	addr.s_addr = st->ip;

	log_debug("banner-grab-tcp", "read_cb for %s", inet_ntoa(addr));

	if (len > MAX_BANNER_LEN) {
		len = MAX_BANNER_LEN;
	}

	if (len > 0) {
		// Grab the banner
		unsigned int i;
		unsigned char *buf = malloc(len+1);

		st->state = RECEIVED;

		if (!buf) {
			log_fatal("banner-grab-tcp", "cannot alloc %d byte buf", len+1);
			return;
		}
		evbuffer_remove(in, buf, len);

		printf("%s ", inet_ntoa(addr));

		if (st->conf->format == FORMAT_ASCII) {
			// Ascii
			buf[len] = '\0';
			printf("%s\n", buf);
		} else if (st->conf->format == FORMAT_HEX) {
			// Hex output
			for (i=0; i<len; i++) {
				printf("%02x", buf[i]);
			}
			printf("\n");
		} else if (st->conf->format == FORMAT_BASE64) {
			// Base64
			int i=0;
			char out[4] = {0,0,0,0};
			while (i < len) {
				uint32_t value = 0;
				value += (i < len) ? buf[i++] << 16 : 0;
				value += (i < len) ? buf[i++] <<  8 : 0;
				value += (i < len) ? buf[i++]       : 0;
				out[0] = BASE64_ALPHABET[(value >> 18) & 0x3F];
				out[1] = BASE64_ALPHABET[(value >> 12) & 0x3F];
				out[2] = BASE64_ALPHABET[(value >>  6) & 0x3F];
				out[3] = BASE64_ALPHABET[(value      ) & 0x3F];
				if (i < len) {
					printf("%c%c%c%c", out[0], out[1], out[2], out[3]);
				}
			}
			if (len > 0) {
				switch (len % 3) {
				case 1:
					out[2] = '=';
				case 2:
					out[3] = '=';
				default:
					break;
				}
				printf("%c%c%c%c\n", out[0], out[1], out[2], out[3]);
			}
		}
		fflush(stdout);

		free(buf);
		st->conf->stats.completed_hosts++;
	}
	bufferevent_free(bev);
	decrement_cur_running(st);
}

void grab_banner(struct state *st)
{
	struct sockaddr_in addr;
	struct bufferevent *bev;
	struct timeval read_to = {st->conf->connect_timeout, 0};

	addr.sin_family = AF_INET;
	addr.sin_port = htons(st->conf->port);
	addr.sin_addr.s_addr = st->ip;
	log_debug("banner-grab-tcp", "connect %s:%d",
			  inet_ntoa(addr.sin_addr), st->conf->port);

	bev = bufferevent_socket_new(st->conf->base, -1, BEV_OPT_CLOSE_ON_FREE);

	bufferevent_set_timeouts(bev, &read_to, &read_to);

	bufferevent_setcb(bev, read_cb, NULL, connect_cb, st);
	bufferevent_enable(bev, EV_READ);

	st->state = CONNECTING;

	st->conf->stats.init_connected_hosts++;

	if (bufferevent_socket_connect(bev,
		(struct sockaddr *)&addr, sizeof(addr)) < 0) {
		log_warn("banner-grab-tcp", "could not connect socket %d (%d open) %d %d",
			bufferevent_getfd(bev), st->conf->current_running, errno, ENFILE);
		perror("connect");

		bufferevent_free(bev);
		decrement_cur_running(st);
		return;
	}
}

void stdin_eventcb(struct bufferevent *bev, short events, void *ptr) {
	struct config *conf = ptr;

	if (events & BEV_EVENT_EOF) {
		log_debug("banner-grab-tcp",
				  "received EOF; quitting after buffer empties");
		conf->stdin_closed = 1;
		if (conf->current_running == 0) {
			log_info("banner-grab-tcp", "done");
			print_status(0, 0, conf);
			exit(0);
		}
	}
}

void stdin_readcb(struct bufferevent *bev, void *arg)
{
	struct evbuffer *in = bufferevent_get_input(bev);
	struct config *conf = arg;

	log_debug("banner-grab-tcp", "stdin cb %d < %d ?",
		conf->current_running, conf->max_concurrent);

	while (conf->current_running < conf->max_concurrent &&
		   evbuffer_get_length(in) > 0) {
		char *ip_str;
		size_t line_len;
		char *line = evbuffer_readln(in, &line_len, EVBUFFER_EOL_LF);
		struct state *st;
		if (!line)
			break;
		log_debug("banner-grab-tcp", "line: %s", line);

		ip_str = line;
		/*
		port_str = strstr(line, ":") + 1;
		if (!port_str)
			port_str = strstr(line, " ") + 1;
		if (!port_str)
			break;

		*(port_str-1) = '\0';
		port = atoi(port_str);
		*/
		//printf("scanning %s:%d\n", ip

		conf->current_running++;
		st = malloc(sizeof(*st));
		st->conf = conf;
		st->ip = inet_addr(ip_str);
		grab_banner(st);
	}
}

int main(int argc, char *argv[])
{
	struct event_base *base;
	struct event *status_timer;
	struct timeval status_timeout = {1, 0};
	int c;
	struct option long_options[] = {
		{"concurrent", required_argument, 0, 'c'},
		{"port", required_argument, 0, 'p'},
		{"conn-timeout", required_argument, 0, 't'},
		{"read-timeout", required_argument, 0, 'r'},
		{"verbosity", required_argument, 0, 'v'},
		{"format", no_argument, 0, 'f'},
		{"data", required_argument, 0, 'd'},
		{0, 0, 0, 0} };

	struct config conf;
	int ret;
	FILE *fp;

	log_init(stderr, LOG_INFO, 0, "banner-grab");

	ret = ulimit(4, 1000000);	// Allow us to open 1 million fds (instead of 1024)
	if (ret < 0) {
		log_fatal("banner-grab-tcp", "cannot set ulimit");
		perror("ulimit");
		exit(1);
	}

	base = event_base_new();
	conf.base = base;

	// buffer stdin as an event
	conf.stdin_bev = bufferevent_socket_new(base, 0, BEV_OPT_DEFER_CALLBACKS);
	bufferevent_setcb(conf.stdin_bev, stdin_readcb, NULL, stdin_eventcb, &conf);
	bufferevent_enable(conf.stdin_bev, EV_READ);

	// Status timer
	status_timer = evtimer_new(base, print_status, &conf);
	evtimer_add(status_timer, &status_timeout);

	// Defaults
	conf.max_concurrent = 1;
	conf.current_running = 0;
	memset(&conf.stats, 0, sizeof(conf.stats));
	conf.connect_timeout = 4;
	conf.read_timeout = 4;
	conf.stdin_closed = 0;
	conf.format = FORMAT_BASE64;
	conf.send_str = NULL;

	// Parse command line args
	while (1) {
		int option_index = 0;
		c = getopt_long(argc, argv, "c:p:t:r:v:f:d:",
				long_options, &option_index);

		if (c < 0) {
			break;
		}

		switch (c) {
		case 'c':
			conf.max_concurrent = atoi(optarg);
			break;
		case 'p':
			conf.port = atoi(optarg);
			break;
		case 't':
			conf.connect_timeout = atoi(optarg);
			break;
		case 'r':
			conf.read_timeout = atoi(optarg);
			break;
		case 'v':
			if (atoi(optarg) >= 0 && atoi(optarg) <= 5) {
				log_init(stderr, atoi(optarg), 0, "banner-grab");
			}
			break;
		case 'f':
			if (strcmp(optarg, "hex") == 0) {
				conf.format = FORMAT_HEX;
			} else if (strcmp(optarg, "base64") == 0) {
				conf.format = FORMAT_BASE64;
			} else if (strcmp(optarg, "ascii") == 0) {
				conf.format = FORMAT_ASCII;
			} else {
				log_fatal("banner-grab-tcp", "Unknown format '%s'; use 'hex', 'base64', or 'ascii'",
						  optarg);
			}
			break;
		case 'd':
			fp = fopen(optarg, "r");
			if (!fp) {
				log_error("banner-grab-tcp", "Could not open send data file '%s':", optarg);
				perror("fopen");
				exit(-1);
			}
			fseek(fp, 0L, SEEK_END);
			conf.send_str_size = ftell(fp);
			fseek(fp, 0L, SEEK_SET);
			//assert(conf.send_str_size < 10000);	// jumbo frames?
			conf.send_str = malloc(conf.send_str_size+1);
			if (!conf.send_str) {
				log_fatal("banner-grab-tcp", "Could not malloc %d bytes", conf.send_str_size+1);
			}
			if (fread(conf.send_str, conf.send_str_size, 1, fp) != 1) {
				log_fatal("banner-grab-tcp", "Couldn't read from send data file '%s':", optarg);
			}
			conf.send_str[conf.send_str_size] = '\0';
			fclose(fp);
			break;
		case '?':
			printf("Usage:\n");
			printf("\t%s [-c max_concurrency] [-t connect_timeout] [-r read_timeout] \n\t"
				   "[-v verbosity=0-5] [-d send_data_file] [-f ascii|hex|base64] -p port\n", argv[0]);
			exit(1);
		default:
			log_info("banner-grab-tcp", "hmmm..");
			break;
		}
	}

	log_info("banner-grab-tcp", "Using port %d with max_concurrency %d, %d s conn timeout, %d s read timeout",
			conf.port, conf.max_concurrent, conf.connect_timeout, conf.read_timeout);

	event_base_dispatch(base);

	return 0;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

		<meta http-equiv="Content-Style-Type" content="text/css">
		<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
		<title>Protection and Rolling Counter Configuration</title>
		<link rel="STYLESHEET" type="text/css" href="css/VSsystemexplorer.css">

		<link rel="STYLESHEET" type="text/css" href="css/expandable_tree.css">

JavaScript is disabled. Details

Protection and Rolling Counter Configuration

The Protection and Rolling Counter custom device allows the user to easily select data channels for calculating a CRC or Checksum.  It creates and maps rolling counters and protection channels to selected outgoing signals.

A quick start document provides an overview of the addon capabilities. It is located at:

"C:\Users\Public\Documents\National Instruments\NI VeriStand (Year)\Custom Devices\Protection and Counter Addon\Windows\Quick Start Documentation\Protection and Counter Addon Quick Start.html"

Most of the addon sections contain additional built-in documentation.

What do you want to do?

Change CAN Settings

The default CAN settings are imported from the database, and can be changed when first adding the custom device to the VeriStand system definition.  You can also change the CAN port settings in the CAN Settings section of this page.  Note:  Check the Legacy? checkbox for VeriStand 2017 (and earlier) implementations of CAN FD.  CAN frame generation is handled in an Asynchronous loop with a priority set by the Loop Priority setting.  Please see the LabVIEW Help for additional information on applicable values.

Add A Frame Configuration

To add a frame configuration, right-click on the 'Cyclic' message type in the configuration tree, and select Import Frames.

Disable Add-on

To disable this add-on, right-click on the add-on instance and select Disable from the shortcut menu.

Delete multiple items

To delete multiple items, right-click the object in the configuration tree and select Delete Multiple Items from the shortcut menu.


text:
@interface ParentalGate ()
@property IBOutlet UILabel *parentsOnlyTop;
@property IBOutlet UILabel *parentsOnlyBottom;
@property IBOutlet UILabel *gateInstructions;
@property NSUInteger numberOfTouchesRequired;
@property UISwipeGestureRecognizerDirection directionRequired;
@property NSMutableArray *swipeGestureRecognizers;
@property UITapGestureRecognizer *tapGestureRecognizer;
@property UIView *itemView;
@end

@implementation ParentalGate

+ (ParentalGate *)newWithCompletion:(ParentalGateCompletion)completion
{
  NSBundle *parentalGateBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"ParentalGate" ofType:@"bundle"]];
  ParentalGate *parentalGate = [parentalGateBundle loadNibNamed:@"ParentalGate" owner:nil options:nil][0];
  parentalGate.completion = completion;
  return parentalGate;
}

+ (void)showWithSuccess:(ParentalGateSuccess)completion;
{
  ParentalGate *parentalGate = [ParentalGate newWithCompletion:^(BOOL success) {
    if (success && completion) {
      completion();
    }
  }];
  [parentalGate show];
}

- (void)awakeFromNib
{
  [super awakeFromNib];

  // defaults to a single tap by a single touch, whish is what we want
  self.tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)];

  self.swipeGestureRecognizers = NSMutableArray.new;

  NSArray *swipeDirections = @[@(UISwipeGestureRecognizerDirectionRight),@(UISwipeGestureRecognizerDirectionLeft),@(UISwipeGestureRecognizerDirectionUp),@(UISwipeGestureRecognizerDirectionDown)];

  // that's just a ridonculous number of gesture recognizers, ugh
  for (NSUInteger numberOfTouches = 1; numberOfTouches < 4; numberOfTouches++) {
    for (NSNumber *swipeDirection in swipeDirections) {
      UISwipeGestureRecognizer *swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRecognized:)];
      swipeGestureRecognizer.direction = swipeDirection.integerValue;
      swipeGestureRecognizer.numberOfTouchesRequired = numberOfTouches;
      [self.swipeGestureRecognizers addObject:swipeGestureRecognizer];
    }
  }

  // choose a random number of fingers, 1 to 3, a random swipe direction
  self.numberOfTouchesRequired = (arc4random() % 3) + 1;
  self.directionRequired = ((NSNumber *)swipeDirections[arc4random() % 4]).integerValue;

  // localize a whole lot of number of fingers & direction strings in each language :(
  NSString *gateInstructionsKey = [NSString stringWithFormat:@"kParentalGateInstructions%02lu%02lu",(unsigned long)self.numberOfTouchesRequired, (unsigned long)self.directionRequired];

  NSBundle *parentalGateBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"ParentalGate" ofType:@"bundle"]];
  self.parentsOnlyTop.text    = [parentalGateBundle localizedStringForKey:@"kParentalGateTop" value:@"" table:@"ParentalGate"]; //NSLocalizedStringFromTable(@"kParentalGateTop", @"ParentalGate", @"");
  self.parentsOnlyBottom.text = [parentalGateBundle localizedStringForKey:@"kParentalGateBottom" value:@"" table:@"ParentalGate"]; //NSLocalizedStringFromTable(@"kParentalGateBottom", @"ParentalGate", @"");
  self.gateInstructions.text  = [parentalGateBundle localizedStringForKey:gateInstructionsKey value:@"" table:@"ParentalGate"]; //NSLocalizedStringFromTable(gateInstructionsKey, @"ParentalGate", @"");

  UIColor *stopSignRedColor = [UIColor colorWithRed:(191.0/255.0) green:(21.0/255.0) blue:(51.0/255.0) alpha:1.0];
  self.backgroundColor = stopSignRedColor;
  self.layer.masksToBounds = YES;
  self.layer.cornerRadius = self.frame.size.width / 2.0;
  self.layer.borderColor = stopSignRedColor.CGColor;
  self.layer.borderWidth = 10.5f;
  self.layer.shadowOffset = CGSizeZero;
  self.layer.shadowRadius = 10;
  self.layer.shadowOpacity = 0.5;
}

- (void)show
{
  // TODO: on iOS6+ would be nice to gaussian blur the background
  BlockBackground *blockBackground = [BlockBackground sharedInstance];
  UIImageView *modalBackground = [[UIImageView alloc] initWithFrame:self.bounds];
  modalBackground.contentMode = UIViewContentModeScaleToFill;
  [self insertSubview:modalBackground atIndex:0];

  [blockBackground addToMainWindow:self];

  [blockBackground addGestureRecognizer:self.tapGestureRecognizer];
  for (UIGestureRecognizer *swipeGestureRecognizer in self.swipeGestureRecognizers) {
    [blockBackground addGestureRecognizer:swipeGestureRecognizer];
  }

  CGPoint center = self.center;
  center.x = blockBackground.bounds.size.width / 2.0;
  center.y = blockBackground.bounds.size.height / 2.0;
  self.transform = CGAffineTransformMakeScale(1.5, 1.5);
  self.center = center;

  [UIView animateWithDuration:0.4
                        delay:0.0
                      options:UIViewAnimationOptionCurveEaseOut
                   animations:^{
                     [BlockBackground sharedInstance].alpha = 1.0f;
                     self.transform = CGAffineTransformIdentity;
                   }
                   completion:^(BOOL finished) {
                     [[NSNotificationCenter defaultCenter] postNotificationName:@"AlertViewFinishedAnimations" object:nil];
                   }];
  [self retain];  // allows caller to let go of the gate UI while it's displaying
}

- (void)tapRecognized:(UITapGestureRecognizer *)tapRecognizer
{
  [self dismissWithResult:false animated:true];
}

- (void)swipeRecognized:(UISwipeGestureRecognizer *)swipeRecognizer
{
  NSLog(@"swipe: %@", swipeRecognizer);
  BOOL properSwipe = ((swipeRecognizer.direction == self.directionRequired) &&
                      (swipeRecognizer.numberOfTouches == self.numberOfTouchesRequired));
  [self dismissWithResult:properSwipe animated:true];
}

- (void)dismissWithResult:(BOOL)passed animated:(BOOL)animated
{
  void (^finished)(BOOL) = ^(BOOL animationFinished) {
    if (self.completion) {
      self.completion(passed);
    }
    [[BlockBackground sharedInstance] removeView:self];
    //[self autorelease];
  };

  if (animated) {
    void (^closeAnimation)() = ^{
      [UIView animateWithDuration:0.4
                            delay:0.0
                          options:UIViewAnimationOptionCurveEaseIn
                       animations:^{
                         self.transform = CGAffineTransformMakeScale(1.5, 1.5);
                         [[BlockBackground sharedInstance] reduceAlphaIfEmpty];
                       }
                       completion:finished];
    };
    if (passed) {
      closeAnimation();
    } else {
      self.transform = CGAffineTransformMakeTranslation(2.0, -2.0);
      [UIView animateWithDuration:0.07
                            delay:0.0
                          options:UIViewAnimationOptionAutoreverse
                       animations:^{
                         UIView.animationRepeatCount = 4;
                         self.transform = CGAffineTransformMakeTranslation(-2.0, 2.0);
                       }
                       completion:^(BOOL finished){
                         self.transform = CGAffineTransformIdentity;
                         closeAnimation();
                       }];
    }
  } else {
    finished(true);
  }
}

@end


text:
/*
 * ConfigFile.h
 *   Thanks: this file was Obtained from http://www.adp-gmbh.ch/cpp/
 *   It is used to read a property file !!
 */

#ifndef CONFIGFILE_H_
#define CONFIGFILE_H_

#include <string>
#include <map>

#include "Chameleon.h"

class ConfigFile {
  std::map<std::string,Chameleon> content_;

public:
  ConfigFile(std::string const& configFile);

  Chameleon const& Value(std::string const& section, std::string const& entry) const;

  Chameleon const& Value(std::string const& section, std::string const& entry, double value);
  Chameleon const& Value(std::string const& section, std::string const& entry, std::string const& value);
};

#endif /* CONFIGFILE_H_ */


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\Plugins\DBStats\Reports;

use Piwik\Piwik;
use Piwik\Plugin\ViewDataTable;
use Piwik\Plugins\CoreVisualizations\Visualizations\Graph;
use Piwik\Plugins\CoreVisualizations\Visualizations\HtmlTable;

/**
 * Shows a datatable that displays how many occurances there are of each individual
 * metric type stored in the MySQL database.
 *
 * Goal metrics, metrics of the format .*_[0-9]+ and 'done...' metrics are grouped together.
 */
class GetIndividualMetricsSummary extends Base
{
    public function configureView(ViewDataTable $view)
    {
        $this->addBaseDisplayProperties($view);
        $this->addPresentationFilters($view, $addTotalSizeColumn = false, $addPercentColumn = false,
            $sizeColumns = array('estimated_size'));

        $view->requestConfig->filter_sort_order = 'asc';
        $view->config->addTranslation('label', Piwik::translate('General_Metric'));

        $this->setIndividualSummaryFooterMessage($view);
    }

}


text:
package org.apache.activemq.broker;

import java.util.concurrent.atomic.AtomicReference;

import javax.jms.Connection;
import javax.jms.InvalidClientIDException;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.util.Wait;
import org.apache.activemq.util.Wait.Condition;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class LinkStealingTest {

    private static final Logger LOG = LoggerFactory.getLogger(LinkStealingTest.class);

    private BrokerService brokerService;
    private final AtomicReference<Throwable> removeException = new AtomicReference<Throwable>();

    private String stealableConnectionURI;
    private String unstealableConnectionURI;

    @Before
    public void setUp() throws Exception {
        brokerService = new BrokerService();
        brokerService.setPersistent(false);
        brokerService.setPlugins(new BrokerPlugin[] { new BrokerPluginSupport() {
            @Override
            public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception {
                LOG.info("Remove Connection called for connection [{}] with error: {}", info.getConnectionId(), error);
                removeException.set(error);
                super.removeConnection(context, info, error);
            }
        }});

        stealableConnectionURI = brokerService.addConnector("tcp://0.0.0.0:0?allowLinkStealing=true").getPublishableConnectString();
        unstealableConnectionURI = brokerService.addConnector("tcp://0.0.0.0:0?allowLinkStealing=false").getPublishableConnectString();

        brokerService.start();
    }

    @After
    public void tearDown() throws Exception {
        if (brokerService != null) {
            brokerService.stop();
            brokerService = null;
        }
    }

    @Test(timeout = 60000)
    public void testStealLinkFails() throws Exception {
        final String clientID = "ThisIsAClientId";
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(unstealableConnectionURI);
        Connection connection1 = factory.createConnection();
        connection1.setClientID(clientID);
        connection1.start();

        try {
            Connection connection2 = factory.createConnection();
            connection2.setClientID(clientID);
            connection2.start();
            fail("Should not have been able to steal the link.");
        } catch (InvalidClientIDException e) {
            LOG.info("Caught expected error on trying to steal link: {}", e.getMessage());
            LOG.trace("Error: ", e);
        }
    }

    @Test(timeout = 60000)
    public void testStealLinkSuccess() throws Exception {
        final String clientID = "ThisIsAClientId";
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(stealableConnectionURI);
        Connection connection1 = factory.createConnection();
        connection1.setClientID(clientID);
        connection1.start();

        try {
            Connection connection2 = factory.createConnection();
            connection2.setClientID(clientID);
            connection2.start();
        } catch (InvalidClientIDException e) {
            LOG.info("Should not have failed while stealing the link: {}", e.getMessage());
            LOG.info("Error details: ", e);
            fail("Shouldn't have failed when stealing the link");
        } catch (Throwable error) {
            LOG.info("Unexpected exception ", error);
            fail("Unexcpected exception causes test failure");
        }

        //Need to wait because removeConnection might not be called yet
        assertTrue(Wait.waitFor(new Condition() {
            @Override
            public boolean isSatisified() throws Exception {
                return removeException.get() != null;
            }
        }, 5000, 100));

        LOG.info("removeException: {}", removeException.get().getMessage());
    }
}


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

namespace HeapImplementation
{
  class HeapTree
  {
    private Node rootNode = null;
    private Node lastNode = null;

    public void Insert(int value)
    {
      Node newNode = new Node() { Priority = 0, StockValue = value };

      if (lastNode == null)
      {
        lastNode = newNode;
        rootNode = newNode;
      }

      //Insert Left if Left is empty.
      if (lastNode.LeftNode == null)
      {
        lastNode.LeftNode = newNode;
        newNode.ParentNode = lastNode;
      }

      //Insert Right if Left is full and right is empty. And then shift the LastNode pointer to newNode
      if (lastNode.LeftNode != null && lastNode.RightNode == null)
      {
        lastNode.RightNode = newNode;
        newNode.ParentNode = lastNode;
        lastNode = newNode;
      }

      ShiftUp(newNode);
    }

    private void ShiftUp(Node newNode)
    {
      Node parentNode;
      Node tempNode;
      parentNode = getParentNode(newNode);
      if (parentNode.StockValue > newNode.StockValue)
      {
        tempNode = parentNode;
        parentNode = newNode;
        newNode = tempNode;

        ShiftUp(parentNode);
      }
    }

    private Node getParentNode(Node currentNode)
    {
      Node parentNode = null;

      parentNode = currentNode.ParentNode;

      return parentNode;
    }

  }
}


text:
package org.apache.asterix.transaction.management.resource;

import java.util.Map;

import org.apache.asterix.common.api.IAppRuntimeContext;
import org.apache.hyracks.api.application.INCApplicationContext;
import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import org.apache.hyracks.api.dataflow.value.ILinearizeComparatorFactory;
import org.apache.hyracks.api.dataflow.value.ITypeTraits;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.api.io.IIOManager;
import org.apache.hyracks.storage.am.common.api.IMetadataPageManagerFactory;
import org.apache.hyracks.storage.am.common.api.IPrimitiveValueProviderFactory;
import org.apache.hyracks.storage.am.common.api.TreeIndexException;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationCallbackFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndex;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMMergePolicyFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMOperationTrackerFactory;
import org.apache.hyracks.storage.am.lsm.rtree.utils.LSMRTreeUtils;
import org.apache.hyracks.storage.am.rtree.frames.RTreePolicyType;
import org.apache.hyracks.storage.common.file.LocalResource;

/**
 * The local resource class for disk only lsm r-tree
 */
public class ExternalRTreeLocalResourceMetadata extends LSMRTreeLocalResourceMetadata {

    private static final long serialVersionUID = 1L;

    public ExternalRTreeLocalResourceMetadata(ITypeTraits[] typeTraits, IBinaryComparatorFactory[] rtreeCmpFactories,
            IBinaryComparatorFactory[] btreeCmpFactories, IPrimitiveValueProviderFactory[] valueProviderFactories,
            RTreePolicyType rtreePolicyType, ILinearizeComparatorFactory linearizeCmpFactory, int datasetID,
            int partition, ILSMMergePolicyFactory mergePolicyFactory, Map<String, String> mergePolicyProperties,
            int[] btreeFields, boolean isPointMBR, ILSMOperationTrackerFactory opTrackerProvider,
            ILSMIOOperationCallbackFactory ioOpCallbackFactory,
            IMetadataPageManagerFactory metadataPageManagerFactory) {
        super(typeTraits, rtreeCmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType,
                linearizeCmpFactory, datasetID, partition, mergePolicyFactory, mergePolicyProperties, null, null, null,
                btreeFields, null, isPointMBR, opTrackerProvider, ioOpCallbackFactory, metadataPageManagerFactory);
    }

    @Override
    public ILSMIndex createIndexInstance(INCApplicationContext appCtx, LocalResource resource)
            throws HyracksDataException {
        IAppRuntimeContext runtimeContextProvider = (IAppRuntimeContext) appCtx.getApplicationObject();
        IIOManager ioManager = runtimeContextProvider.getIOManager();
        FileReference file = ioManager.resolve(resource.getPath());
        try {
            return LSMRTreeUtils.createExternalRTree(ioManager, file, runtimeContextProvider.getBufferCache(),
                    runtimeContextProvider.getFileMapManager(), typeTraits, rtreeCmpFactories, btreeCmpFactories,
                    valueProviderFactories, rtreePolicyType, runtimeContextProvider.getBloomFilterFalsePositiveRate(),
                    mergePolicyFactory.createMergePolicy(mergePolicyProperties,
                            runtimeContextProvider.getDatasetLifecycleManager()),
                    opTrackerProvider.getOperationTracker(appCtx), runtimeContextProvider.getLSMIOScheduler(),
                    ioOpCallbackFactory.createIoOpCallback(), linearizeCmpFactory, btreeFields, -1, true, isPointMBR,
                    metadataPageManagerFactory);
        } catch (TreeIndexException e) {
            throw new HyracksDataException(e);
        }
    }
}


text:
package com.facebook.buck.android;

import static com.facebook.buck.testutil.RegexMatcher.containsRegex;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import com.facebook.buck.android.relinker.Symbols;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.testutil.integration.BuckBuildLog;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TemporaryPaths;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.testutil.integration.ZipInspector;
import com.facebook.buck.util.DefaultPropertyFinder;
import com.facebook.buck.util.environment.Platform;
import com.facebook.buck.zip.ZipConstants;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.Hashing;

import org.apache.commons.compress.archivers.zip.ZipUtil;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

public class AndroidBinaryIntegrationTest {

  @ClassRule
  public static TemporaryPaths projectFolderWithPrebuiltTargets = new TemporaryPaths();

  @Rule
  public TemporaryPaths tmpFolder = new TemporaryPaths();

  private ProjectWorkspace workspace;

  private static final String SIMPLE_TARGET = "//apps/multidex:app";
  private static final String RAW_DEX_TARGET = "//apps/multidex:app-art";

  @BeforeClass
  public static void setUpOnce() throws IOException {
    AssumeAndroidPlatform.assumeSdkIsAvailable();
    AssumeAndroidPlatform.assumeNdkIsAvailable();
    ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(
        new AndroidBinaryIntegrationTest(),
        "android_project",
        projectFolderWithPrebuiltTargets);
    workspace.setUp();
    workspace.runBuckBuild(SIMPLE_TARGET).assertSuccess();
  }

  @Before
  public void setUp() throws IOException {
    workspace = new ProjectWorkspace(
        projectFolderWithPrebuiltTargets.getRoot(), tmpFolder.getRoot());
    workspace.setUp();
  }

  @Test
  public void testNonExopackageHasSecondary() throws IOException {
    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(SIMPLE_TARGET), "%s.apk")));
    zipInspector.assertFileExists("assets/secondary-program-dex-jars/metadata.txt");
    zipInspector.assertFileExists("assets/secondary-program-dex-jars/secondary-1.dex.jar");
    zipInspector.assertFileDoesNotExist("classes2.dex");

    zipInspector.assertFileExists("classes.dex");
    zipInspector.assertFileExists("lib/armeabi/libfakenative.so");
  }

  @Test
  public void testRawSplitDexHasSecondary() throws IOException {
    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("build", RAW_DEX_TARGET);
    result.assertSuccess();

    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(RAW_DEX_TARGET), "%s.apk")));
    zipInspector.assertFileDoesNotExist("assets/secondary-program-dex-jars/metadata.txt");

    zipInspector.assertFileDoesNotExist("assets/secondary-program-dex-jars/secondary-1.dex.jar");
    zipInspector.assertFileExists("classes2.dex");

    zipInspector.assertFileExists("classes.dex");
    zipInspector.assertFileExists("lib/armeabi/libfakenative.so");
  }

  @Test
  public void testDisguisedExecutableIsRenamed() throws IOException {
    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(SIMPLE_TARGET), "%s.apk")));

    zipInspector.assertFileExists("lib/armeabi/libmybinary.so");
  }

  @Test
  public void testEditingPrimaryDexClassForcesRebuildForSimplePackage() throws IOException {
    workspace.replaceFileContents(
        "java/com/sample/app/MyApplication.java",
        "package com",
        "package\ncom");

    workspace.resetBuildLogFile();
    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("build", SIMPLE_TARGET);
    result.assertSuccess();
    BuckBuildLog buildLog = workspace.getBuildLog();

    buildLog.assertTargetBuiltLocally(SIMPLE_TARGET);
  }

  @Test
  public void testEditingSecondaryDexClassForcesRebuildForSimplePackage() throws IOException {
    workspace.replaceFileContents(
        "java/com/sample/lib/Sample.java",
        "package com",
        "package\ncom");

    workspace.resetBuildLogFile();
    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("build", SIMPLE_TARGET);
    result.assertSuccess();
    BuckBuildLog buildLog = workspace.getBuildLog();

    buildLog.assertTargetBuiltLocally(SIMPLE_TARGET);
  }

  @Test
  public void testPreprocessorForcesReDex() throws IOException {
    String target = "//java/com/preprocess:disassemble";
    Path outputFile = workspace.buildAndReturnOutput(target);
    String output = new String(Files.readAllBytes(outputFile), UTF_8);
    assertThat(output, containsString("content=2"));

    workspace.replaceFileContents(
        "java/com/preprocess/convert.py",
        "content=2",
        "content=3");

    outputFile = workspace.buildAndReturnOutput(target);
    output = new String(Files.readAllBytes(outputFile), UTF_8);
    assertThat(output, containsString("content=3"));
  }

  @Test
  public void testCxxLibraryDep() throws IOException {
    String target = "//apps/sample:app_cxx_lib_dep";
    workspace.runBuckCommand("build", target).assertSuccess();

    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(target), "%s.apk")));
    zipInspector.assertFileExists("lib/armeabi/libnative_cxx_lib.so");
    zipInspector.assertFileExists("lib/armeabi/libgnustl_shared.so");
    zipInspector.assertFileExists("lib/armeabi-v7a/libnative_cxx_lib.so");
    zipInspector.assertFileExists("lib/armeabi-v7a/libgnustl_shared.so");
    zipInspector.assertFileExists("lib/x86/libnative_cxx_lib.so");
    zipInspector.assertFileExists("lib/x86/libgnustl_shared.so");
  }

  @Test
  public void testCxxLibraryDepClang() throws IOException {
    String target = "//apps/sample:app_cxx_lib_dep";
    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand(
            "build",
            "-c", "ndk.compiler=clang",
            "-c", "ndk.cxx_runtime=libcxx",
            target);
    result.assertSuccess();

    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(
                BuildTargetFactory.newInstance(target),
                "%s.apk")));
    zipInspector.assertFileExists("lib/armeabi/libnative_cxx_lib.so");
    zipInspector.assertFileExists("lib/armeabi/libc++_shared.so");
    zipInspector.assertFileExists("lib/armeabi-v7a/libnative_cxx_lib.so");
    zipInspector.assertFileExists("lib/armeabi-v7a/libc++_shared.so");
    zipInspector.assertFileExists("lib/x86/libnative_cxx_lib.so");
    zipInspector.assertFileExists("lib/x86/libc++_shared.so");
  }

  @Test
  public void testCxxLibraryDepWithNoFilters() throws IOException {
    String target = "//apps/sample:app_cxx_lib_dep_no_filters";
    workspace.runBuckCommand("build", target).assertSuccess();

    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(target), "%s.apk")));
    zipInspector.assertFileExists("lib/armeabi/libnative_cxx_lib.so");
    zipInspector.assertFileExists("lib/armeabi-v7a/libnative_cxx_lib.so");
    zipInspector.assertFileExists("lib/x86/libnative_cxx_lib.so");
  }

  @Test
  public void testNoCxxDepsDoesNotIncludeNdkRuntime() throws IOException {
    String target = "//apps/sample:app_no_cxx_deps";
    workspace.runBuckCommand("build", target).assertSuccess();

    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(target), "%s.apk")));
    zipInspector.assertFileDoesNotExist("lib/armeabi/libgnustl_shared.so");
    zipInspector.assertFileDoesNotExist("lib/armeabi-v7a/libgnustl_shared.so");
    zipInspector.assertFileDoesNotExist("lib/x86/libgnustl_shared.so");
  }

  @Test
  public void testProguardDontObfuscateGeneratesMappingFile() throws IOException {
    String target = "//apps/sample:app_proguard_dontobfuscate";
    workspace.runBuckCommand("build", target).assertSuccess();

    Path mapping = workspace.getPath(
        BuildTargets.getGenPath(
            BuildTargetFactory.newInstance(target)
                .withFlavors(AndroidBinaryGraphEnhancer.AAPT_PACKAGE_FLAVOR),
            "__%s__proguard__/.proguard/mapping.txt"));
    assertTrue(Files.exists(mapping));
  }

  @Test
  public void testStaticCxxLibraryDep() throws IOException {
    String target = "//apps/sample:app_static_cxx_lib_dep";
    workspace.runBuckCommand("build", target).assertSuccess();

    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(target), "%s.apk")));
    zipInspector.assertFileExists("lib/x86/libnative_cxx_foo1.so");
    zipInspector.assertFileExists("lib/x86/libnative_cxx_foo2.so");
    zipInspector.assertFileDoesNotExist("lib/x86/libnative_cxx_bar.so");
  }

  private Path unzip(Path tmpDir, Path zipPath, String name) throws IOException {
    Path outPath = tmpDir.resolve(zipPath.getFileName());
    try (ZipFile zipFile = new ZipFile(zipPath.toFile())) {
      Files.copy(
          zipFile.getInputStream(zipFile.getEntry(name)),
          outPath,
          StandardCopyOption.REPLACE_EXISTING);
      return outPath;
    }
  }

  @Test
  public void testNativeRelinker() throws IOException, InterruptedException {
    // TODO(cjhopman): is this really the simplest way to get the objdump tool?
    AndroidDirectoryResolver androidResolver = new DefaultAndroidDirectoryResolver(
        workspace.asCell().getFilesystem(),
        Optional.<String>absent(),
        Optional.<String>absent(),
        new DefaultPropertyFinder(
            workspace.asCell().getFilesystem(),
            ImmutableMap.copyOf(System.getenv())));

    Optional<Path> ndkPath = androidResolver.findAndroidNdkDir();
    assertTrue(ndkPath.isPresent());

    ImmutableCollection<NdkCxxPlatform> platforms = NdkCxxPlatforms.getPlatforms(
        new ProjectFilesystem(ndkPath.get()),
        NdkCxxPlatformCompiler.builder()
            .setType(NdkCxxPlatforms.DEFAULT_COMPILER_TYPE)
            .setVersion(NdkCxxPlatforms.DEFAULT_GCC_VERSION)
            .setGccVersion(NdkCxxPlatforms.DEFAULT_GCC_VERSION)
            .build(),
        NdkCxxPlatforms.DEFAULT_CXX_RUNTIME,
        NdkCxxPlatforms.DEFAULT_TARGET_APP_PLATFORM,
        NdkCxxPlatforms.DEFAULT_CPU_ABIS,
        Platform.detect()).values();
    assertFalse(platforms.isEmpty());
    NdkCxxPlatform platform = platforms.iterator().next();

    SourcePathResolver pathResolver = new SourcePathResolver(
        new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer())
    );

    Path apkPath = workspace.buildAndReturnOutput("//apps/sample:app_xdso_dce");

    ZipInspector zipInspector = new ZipInspector(apkPath);
    zipInspector.assertFileExists("lib/x86/libnative_xdsodce_top.so");
    zipInspector.assertFileExists("lib/x86/libnative_xdsodce_mid.so");
    zipInspector.assertFileExists("lib/x86/libnative_xdsodce_bot.so");

    Path tmpDir = tmpFolder.newFolder("xdso");
    Path lib = unzip(
        tmpDir, apkPath, "lib/x86/libnative_xdsodce_top.so");
    Symbols sym = Symbols.getSymbols(platform.getObjdump(), pathResolver, lib);

    assertTrue(sym.global.contains("_Z10JNI_OnLoadii"));
    assertTrue(sym.undefined.contains("_Z10midFromTopi"));
    assertTrue(sym.undefined.contains("_Z10botFromTopi"));
    assertFalse(sym.all.contains("_Z6unusedi"));

    lib = unzip(tmpDir, apkPath, "lib/x86/libnative_xdsodce_mid.so");
    sym = Symbols.getSymbols(platform.getObjdump(), pathResolver, lib);

    assertTrue(sym.global.contains("_Z10midFromTopi"));
    assertTrue(sym.undefined.contains("_Z10botFromMidi"));
    assertFalse(sym.all.contains("_Z6unusedi"));

    lib = unzip(tmpDir, apkPath, "lib/x86/libnative_xdsodce_bot.so");
    sym = Symbols.getSymbols(platform.getObjdump(), pathResolver, lib);

    assertTrue(sym.global.contains("_Z10botFromTopi"));
    assertTrue(sym.global.contains("_Z10botFromMidi"));
    assertFalse(sym.all.contains("_Z6unusedi"));

    // Run some verification on the same apk with native_relinker disabled.
    apkPath = workspace.buildAndReturnOutput("//apps/sample:app_no_xdso_dce");
    zipInspector = new ZipInspector(apkPath);
    zipInspector.assertFileExists("lib/x86/libnative_xdsodce_top.so");
    zipInspector.assertFileExists("lib/x86/libnative_xdsodce_mid.so");
    zipInspector.assertFileExists("lib/x86/libnative_xdsodce_bot.so");

    lib = unzip(
        tmpDir, apkPath, "lib/x86/libnative_xdsodce_top.so");
    sym = Symbols.getSymbols(platform.getObjdump(), pathResolver, lib);

    assertTrue(sym.all.contains("_Z6unusedi"));

    lib = unzip(tmpDir, apkPath, "lib/x86/libnative_xdsodce_mid.so");
    sym = Symbols.getSymbols(platform.getObjdump(), pathResolver, lib);

    assertTrue(sym.all.contains("_Z6unusedi"));

    lib = unzip(tmpDir, apkPath, "lib/x86/libnative_xdsodce_bot.so");
    sym = Symbols.getSymbols(platform.getObjdump(), pathResolver, lib);

    assertTrue(sym.all.contains("_Z6unusedi"));
  }

  @Test
  public void testHeaderOnlyCxxLibrary() throws IOException {
    String target = "//apps/sample:app_header_only_cxx_lib_dep";
    workspace.runBuckCommand("build", target).assertSuccess();
    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(target), "%s.apk")));
    zipInspector.assertFileDoesNotExist("lib/x86/libnative_cxx_headeronly.so");
  }

  @Test
  public void testX86OnlyCxxLibrary() throws IOException {
    String target = "//apps/sample:app_with_x86_lib";
    workspace.runBuckCommand("build", target).assertSuccess();
    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(target), "%s.apk")));
    zipInspector.assertFileDoesNotExist("lib/armeabi-v7a/libnative_cxx_x86-only.so");
    zipInspector.assertFileDoesNotExist("lib/armeabi-v7a/libgnustl_shared.so");
    zipInspector.assertFileDoesNotExist("lib/armeabi/libnative_cxx_x86-only.so");
    zipInspector.assertFileDoesNotExist("lib/armeabi/libgnustl_shared.so");
    zipInspector.assertFileExists("lib/x86/libnative_cxx_x86-only.so");
    zipInspector.assertFileExists("lib/x86/libgnustl_shared.so");
  }

  @Test
  public void testApksHaveDeterministicTimestamps() throws IOException {
    String target = "//apps/sample:app";
    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("build", target);
    result.assertSuccess();

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    Path apk = workspace.getPath(
        BuildTargets.getGenPath(BuildTargetFactory.newInstance(target), "%s.apk"));
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(Files.newInputStream(apk))) {
      for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
        assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
      }
    }
  }

  @Test
  public void testCxxLibraryAsAsset() throws IOException {
    String target = "//apps/sample:app_cxx_lib_asset";
    workspace.runBuckCommand("build", target).assertSuccess();
    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(target), "%s.apk")));
    zipInspector.assertFileExists("assets/lib/x86/libnative_cxx_libasset.so");
    zipInspector.assertFileDoesNotExist("lib/x86/libnative_cxx_libasset.so");
    zipInspector.assertFileExists("lib/x86/libnative_cxx_foo1.so");
    zipInspector.assertFileExists("lib/x86/libnative_cxx_foo2.so");
    zipInspector.assertFileDoesNotExist("assets/lib/x86/libnative_cxx_foo1.so");
    zipInspector.assertFileDoesNotExist("assets/lib/x86/libnative_cxx_foo2.so");
  }

  @Test
  public void testCxxLibraryAsAssetWithoutPackaging() throws IOException {
    String target = "//apps/sample:app_cxx_lib_asset_no_package";
    workspace.runBuckCommand("build", target).assertSuccess();
    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(target), "%s.apk")));
    zipInspector.assertFileDoesNotExist("assets/lib/x86/libnative_cxx_libasset.so");
    zipInspector.assertFileExists("lib/x86/libnative_cxx_libasset.so");
  }

  @Test
  public void testCompressAssetLibs() throws IOException {
    String target = "//apps/sample:app_compress_lib_asset";
    workspace.runBuckCommand("build", target).assertSuccess();
    ZipInspector zipInspector = new ZipInspector(
        workspace.getPath(
            BuildTargets.getGenPath(BuildTargetFactory.newInstance(target), "%s.apk")));
    zipInspector.assertFileExists("assets/lib/libs.xzs");
    zipInspector.assertFileExists("assets/lib/metadata.txt");
    zipInspector.assertFileDoesNotExist("assets/lib/x86/libnative_cxx_libasset.so");
    zipInspector.assertFileDoesNotExist("lib/x86/libnative_cxx_libasset.so");
    zipInspector.assertFileExists("lib/x86/libnative_cxx_foo1.so");
    zipInspector.assertFileExists("lib/x86/libnative_cxx_foo2.so");
    zipInspector.assertFileDoesNotExist("assets/lib/x86/libnative_cxx_foo1.so");
    zipInspector.assertFileDoesNotExist("assets/lib/x86/libnative_cxx_foo2.so");
  }

  @Test
  public void testLibraryMetadataChecksum() throws IOException {
    String target = "//apps/sample:app_cxx_lib_asset";
    workspace.runBuckCommand("build", target).assertSuccess();
    Path pathToZip = workspace.getPath(
        BuildTargets.getGenPath(BuildTargetFactory.newInstance(target), "%s.apk"));
    ZipFile file = new ZipFile(pathToZip.toFile());
    ZipEntry metadata = file.getEntry("assets/lib/metadata.txt");
    assertNotNull(metadata);

    BufferedReader contents = new BufferedReader(
        new InputStreamReader(file.getInputStream(metadata)));
    String line = contents.readLine();
    byte[] buffer = new byte[512];
    while (line != null) {
      // Each line is of the form <filename> <filesize> <SHA256 checksum>
      String[] tokens = line.split(" ");
      assertSame(tokens.length, 3);
      String filename = tokens[0];
      int filesize = Integer.parseInt(tokens[1]);
      String checksum = tokens[2];

      ZipEntry lib = file.getEntry("assets/lib/" + filename);
      assertNotNull(lib);
      InputStream is = file.getInputStream(lib);
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      while (filesize > 0) {
        int read = is.read(buffer, 0, Math.min(buffer.length, filesize));
        assertTrue(read >= 0);
        out.write(buffer, 0, read);
        filesize -= read;
      }
      String actualChecksum = Hashing.sha256().hashBytes(out.toByteArray()).toString();
      assertEquals(checksum, actualChecksum);
      is.close();
      out.close();
      line = contents.readLine();
    }
    file.close();
    contents.close();
  }

  @Test
  public void testApkEmptyResDirectoriesBuildsCorrectly() throws IOException {
    workspace.runBuckBuild("//apps/sample:app_no_res").assertSuccess();
  }

  @Test
  public void testInstrumentationApkWithEmptyResDepBuildsCorrectly() throws IOException {
    workspace.runBuckBuild("//apps/sample:instrumentation_apk").assertSuccess();
  }

  @Test
  public void testInvalidKeystoreKeyAlias() throws IOException {
    workspace.replaceFileContents(
        "keystores/debug.keystore.properties",
        "key.alias=my_alias",
        "key.alias=invalid_alias"
    );

    workspace.resetBuildLogFile();
    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("build", SIMPLE_TARGET);
    result.assertFailure("Invalid keystore key alias should fail.");

    assertThat(
        "error message for invalid keystore key alias is incorrect.",
        result.getStderr(),
        containsRegex("The keystore \\[.*\\] key\\.alias \\[.*\\].*does not exist"));
  }
}


text:
make clean
export CC=clang
export CFLAGS="-g -O3 -Werror -Weverything -Wno-padded -Wno-covered-switch-default"
make -e test


text:
package com.google.classyshark.silverghost.translator;

import com.google.classyshark.silverghost.translator.apk.ApkTranslator;
import com.google.classyshark.silverghost.translator.dex.DexInfoTranslator;
import com.google.classyshark.silverghost.translator.elf.ElfTranslator;
import com.google.classyshark.silverghost.translator.jar.JarInfoTranslator;
import com.google.classyshark.silverghost.translator.java.JavaTranslator;
import com.google.classyshark.silverghost.translator.xml.AndroidXmlTranslator;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

/**
 *  Creates translators based on class names and archives
 */
public class TranslatorFactory {

    public static Translator createTranslator(String className, File archiveFile) {
        return createTranslator(className, archiveFile, new LinkedList<String>());
    }

    public static Translator createTranslator(String className, File archiveFile,
                                              List<String> allClassNames) {
        if(className.endsWith(".xml")) {
            return new AndroidXmlTranslator(className, archiveFile);
        }

        if (className.endsWith(".dex")) {
           return new DexInfoTranslator(className, archiveFile);
        }

        if (className.endsWith(".jar")) {
            return new JarInfoTranslator(archiveFile, allClassNames);
        }

        if (className.endsWith(".apk")) {
            return new ApkTranslator(archiveFile);
        }

        if (className.endsWith(".so")) {
            return new ElfTranslator(className, archiveFile);
        }

        return new JavaTranslator(className, archiveFile);
    }
}


text:
<?php

namespace Dwo\Ispec\Decorator;

use Dwo\Ispec\Model\IpInfo;

/**
 * Class ArrayDecorator
 *
 * @author Dave Www <davewwwo@gmail.com>
 */
class ArrayDecorator implements DecoratorInterface
{
    protected $data = array();

    /**
     * @param array $data
     */
    public function __construct(array $data)
    {
        $this->data = $data;
    }

    /**
     * {@inheritdoc}
     */
    public function decorate(IpInfo $ipInfo, $overwrite = false)
    {
        foreach ($ipInfo->toArray(false) as $key => $value) {
            if ((empty($value) || $overwrite) && isset($this->data[$key]) && !empty($this->data[$key])) {
                $ipInfo->$key = $this->data[$key];
            }
        }

        return $ipInfo;
    }
}


text:
<?php

namespace FOS\RestBundle\Decoder;

/**
 * Defines the interface of decoder providers
 *
 * @author Igor Wiedler <igor@wiedler.ch>
 */
interface DecoderProviderInterface
{
    /**
     * Check if a certain format is supported.
     *
     * @param string $format Format for the requested decoder.
     * @return Boolean
     */
    function supports($format);

    /**
     * Provides decoders, possibly lazily.
     *
     * @param string $format Format for the requested decoder.
     * @return FOS\RestBundle\Decoder\DecoderInterface
     */
    function getDecoder($format);
}


text:
// File: vogl_light_state.cpp
#include "vogl_light_state.h"

vogl_light_state::vogl_light_state()
    : m_valid(false)
{
    VOGL_FUNC_TRACER
}

vogl_light_state::~vogl_light_state()
{
    VOGL_FUNC_TRACER
}

bool vogl_light_state::snapshot(const vogl_context_info &context_info)
{
    VOGL_FUNC_TRACER

    clear();

    VOGL_CHECK_GL_ERROR;

    bool any_gl_errors = false;

    m_lights.resize(context_info.get_max_lights());
    for (uint32_t light = 0; light < context_info.get_max_lights(); light++)
    {
#define GET_FLOAT(light, pname)                                            \
    do                                                                     \
    {                                                                      \
        float values[4] = { 0, 0, 0, 0 };                                  \
        GL_ENTRYPOINT(glGetLightfv)(get_light_enum(light), pname, values); \
        if (vogl_check_gl_error())                                          \
            any_gl_errors = true;                                          \
        m_lights[light].insert(pname, 0, values, sizeof(values[0]));       \
    } while (0)
        GET_FLOAT(light, GL_CONSTANT_ATTENUATION);
        GET_FLOAT(light, GL_LINEAR_ATTENUATION);
        GET_FLOAT(light, GL_QUADRATIC_ATTENUATION);
        GET_FLOAT(light, GL_SPOT_EXPONENT);
        GET_FLOAT(light, GL_SPOT_CUTOFF);
        GET_FLOAT(light, GL_AMBIENT);
        GET_FLOAT(light, GL_DIFFUSE);
        GET_FLOAT(light, GL_SPECULAR);
        GET_FLOAT(light, GL_POSITION);
        GET_FLOAT(light, GL_SPOT_DIRECTION);
#undef GET_FLOAT
    }

    if (any_gl_errors)
    {
        clear();

        vogl_error_printf("GL error while enumerating light params\n");

        return false;
    }

    m_valid = true;

    return true;
}

bool vogl_light_state::set_light_parameter(uint32_t light, GLenum pname) const
{
    VOGL_FUNC_TRACER

    GLenum light_enum = get_light_enum(light);

    const vogl_state_data *pData = m_lights[light].find(pname);
    if (!pData)
        return false;

    enum
    {
        cMaxElements = 4
    };
    if (pData->get_num_elements() > cMaxElements)
    {
        VOGL_ASSERT_ALWAYS;
        return false;
    }

    if ((pData->get_data_type() == cSTFloat) || (pData->get_data_type() == cSTDouble))
    {
        float fvals[cMaxElements];
        pData->get_float(fvals);
        if (pData->get_num_elements() == 1)
            GL_ENTRYPOINT(glLightf)(light_enum, pname, fvals[0]);
        else
            GL_ENTRYPOINT(glLightfv)(light_enum, pname, fvals);
    }
    else
    {
        int ivals[cMaxElements];
        pData->get_int(ivals);
        if (pData->get_num_elements() == 1)
            GL_ENTRYPOINT(glLighti)(light_enum, pname, ivals[0]);
        else
            GL_ENTRYPOINT(glLightiv)(light_enum, pname, ivals);
    }

    return !vogl_check_gl_error();
}

bool vogl_light_state::restore(const vogl_context_info &context_info) const
{
    VOGL_FUNC_TRACER

    if (!m_valid)
    {
        VOGL_ASSERT_ALWAYS;
    }

    const uint32_t num_lights = math::minimum<uint32_t>(m_lights.size(), context_info.get_max_lights());
    if (m_lights.size() > context_info.get_max_lights())
    {
        vogl_warning_printf("Object has %u lights, but the context only supports %u lights!\n", m_lights.size(), context_info.get_max_lights());
    }

    for (uint32_t light = 0; light < num_lights; light++)
    {
#define SET_FLOAT(light, pname) set_light_parameter(light, pname)
        SET_FLOAT(light, GL_CONSTANT_ATTENUATION);
        SET_FLOAT(light, GL_LINEAR_ATTENUATION);
        SET_FLOAT(light, GL_QUADRATIC_ATTENUATION);
        SET_FLOAT(light, GL_SPOT_EXPONENT);
        SET_FLOAT(light, GL_SPOT_CUTOFF);
        SET_FLOAT(light, GL_AMBIENT);
        SET_FLOAT(light, GL_DIFFUSE);
        SET_FLOAT(light, GL_SPECULAR);
        SET_FLOAT(light, GL_POSITION);
        SET_FLOAT(light, GL_SPOT_DIRECTION);
#undef SET_FLOAT
    }

    return !vogl_check_gl_error();
}

void vogl_light_state::clear()
{
    m_lights.clear();
    m_valid = false;
}

bool vogl_light_state::serialize(json_node &node, vogl_blob_manager &blob_manager) const
{
    VOGL_FUNC_TRACER

    if (!m_valid)
    {
        VOGL_ASSERT_ALWAYS;
        return false;
    }

    json_node &light_array_node = node.add_array("lights");
    for (uint32_t i = 0; i < m_lights.size(); i++)
        if (!m_lights[i].serialize(light_array_node.add_object(), blob_manager))
            return false;

    return true;
}

bool vogl_light_state::deserialize(const json_node &node, const vogl_blob_manager &blob_manager)
{
    VOGL_FUNC_TRACER

    clear();

    const json_node *pLight_array_node = node.find_child_array("lights");
    if (!pLight_array_node)
        return false;
    if (!pLight_array_node->are_all_children_objects())
        return false;

    m_lights.resize(pLight_array_node->size());

    for (uint32_t i = 0; i < m_lights.size(); i++)
    {
        if (!m_lights[i].deserialize(*pLight_array_node->get_child(i), blob_manager))
        {
            clear();
            return false;
        }
    }

    m_valid = true;

    return true;
}


text:
{% extends "account/base.html" %}

{% load i18n %}
{% load account socialaccount %}
{% load materializecss %}

{% block head_title %}{% trans "Sign In" %}{% endblock %}

{% block inner %}

{% trans "Sign In" %}

{% blocktrans %}If you have not created an account yet, then please sign up first.{% endblocktrans %}

      <form class="login" method="POST" action="{% url 'account_login' %}">
        {% csrf_token %}
        {{ form|materializecss }}
        {% if redirect_field_value %}
        <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
        {% endif %}

            <button class="primaryAction btn btn-primary" type="submit">{% trans "Sign In" %}</button>

            {% trans "Forgot Password?" %}

      </form>

{% endblock %}