text:
var error = require('../error');
var _ = require('underscore');

var valueToRow = function (msg) {
  var row = {
    media_value: null,
    media_type: null
  };
  if (msg.isBinary) {
    row.value_type = 'bin';
    row.media_type = msg.mediaType;
    // TODO: need to parse base64, blah, blah
  } else if (msg.mediaType) {
    row.value_type = 'txt';
    row.media_type = msg.mediaType;
    row.media_value = msg.value;
  } else if (typeof msg.value === 'string') {
    row.value_type = 'str';
    row.media_value = msg.value;
  } else if (typeof msg.value === 'number') {
    row.value_type = 'num';
    row.media_value = JSON.stringify(msg.value);
  } else if (typeof msg.value === 'boolean') {
    row.value_type = 'bool';
    row.media_value = JSON.stringify(msg.value);
  } else if (typeof msg.value === 'undefined' || msg.value === 'null') {
    row.value_type = 'null';
  } else {
    row.value_type = 'json';
    row.media_value = JSON.stringify(msg.value);
  }
  return row;
};

var rowToObject = function (row) {
  var obj = {value: null};
  if (row.value_type === 'bin') {
    obj.isBinary = true;
    obj.mediaType = row.media_type;
    // TODO: convert to base64, blah, blah
  } else if (row.value_type === 'txt') {
    obj.mediaType = row.media_type;
    obj.value = row.media_value.toString();
  } else if (row.value_type === 'str') {
    obj.value = row.media_value.toString();
  } else if (row.value_type === 'num') {
    obj.value = JSON.parse(row.media_value.toString());
  } else if (row.value_type === 'bool') {
    obj.value = JSON.parse(row.media_value.toString());
  } else if (row.value_type === 'null') {
    obj.value = null;
  } else if (row.value_type === 'json') {
    // cross fingers
    obj.value = JSON.parse(row.media_value.toString());
  } else {
    obj.value = null;
  }
  return obj;
};

var createTableSource = function (next, options) {

  options = options || {};
  options = _.extend({}, options);
  options.tables = options.tables || {};

  var ops = {
    set: function (msg, op) {
      var tableMsg = {};
      tableMsg.op = op || 'upsert';
      if (msg.table) {
        if (options.tables[msg.table]) {
          tableMsg.table = msg.table;
          tableMsg.attributes = _.extend({}, msg.value);
          tableMsg.attributes[options.tables[msg.table].primaryKey] = msg.key;
          if (op !== 'create') {
            tableMsg.filters = {};
            tableMsg.filters[options.tables[msg.table].primaryKey] = msg.key;
          }
        } else {
          throw new error.TableSchemaNotFound({table: msg.table});
        }
      } else {
        tableMsg.table = 'item';
        tableMsg.attributes = valueToRow(msg);
        tableMsg.attributes.item_key = msg.key;
        tableMsg.attributes.version = msg.version;
        if (op !== 'create') {
          tableMsg.filters = {
            item_key: msg.key
          };
        }
      }
      return next(tableMsg);
    },
    create: function (msg) {
      return ops.set(msg, 'create');
    },
    update: function (msg) {
      return ops.set(msg, 'update');
    },
    get: function (msg) {
      var tableMsg = {};
      tableMsg.op = 'query';
      if (msg.table) {
        if (options.tables[msg.table]) {
          tableMsg.table = msg.table;
          tableMsg.filters = {};
          tableMsg.filters[options.tables[msg.table].primaryKey] = msg.key;
        } else {
          throw new error.TableSchemaNotFound({table: msg.table});
        }
      } else {
        tableMsg.table = 'item';
        tableMsg.filters = {
          item_key: msg.key
        };
      }
      return next(tableMsg)
        .then(function (result) {
          if (result.items.length === 0) {
            throw new error.NotFound({key: msg.key});
          } else {
            var obj;
            if (msg.table) {
              obj = {};
              obj.key = msg.key;
              obj.table = msg.table;
              obj.value = _.extend({}, result.items[0]);
              if (obj.value[options.tables[msg.table].primaryKey]) {
                delete obj.value[options.tables[msg.table].primaryKey];
              }
            } else {
              obj = rowToObject(result.items[0]);
              obj.key = msg.key;
              obj.version = result.items[0].version;
            }
            return obj;
          }
        });
    },
    delete: function (msg) {
      return next({
        op: 'delete',
        table: 'item',
        filters: {
          item_key: msg.key
        }
      });
    }
  };

  var source = function (msg) {
    var result;
    if (ops[msg.op]) {
      result = ops[msg.op](msg);
    } else {
      result = next(msg);
    }
    return result;
  };

  return source;
};

module.exports = createTableSource;


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

package com.google.gerrit.server.patch;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.util.concurrent.ExecutorService;

/** Marker on {@link ExecutorService} used by {@link IntraLineLoader}. */
@Retention(RUNTIME)
@BindingAnnotation
public @interface DiffExecutor {}

redpajama_set_name: RedPajamaGithub


text:
from os import mkdir
from os.path import exists, basename, join
from random import choice
from json import load, dump
from sys import version_info
from time import asctime

if version_info.minor < 3:
    FileNotFoundError = IOError

class Plugin:

    def __init__(self, bot, handler):
        self.bot = bot
        self.conn = bot.conn
        self.handler = handler
        self.name = basename(__file__).rstrip('.py')
        self.data_file = self.get_data_file()
        self.hooks = [
                {'type': 'other_part', 'key': None, 'func': self.add_seen},
                {'type': 'command', 'key': '!seen', 'func': self.get_seen},
                {'type': 'privmsg', 'key': None, 'func': self.add_seen},
                {'type': 'action', 'key': None, 'func': self.add_seen},
                {'type': 'other_join', 'key': None, 'func': self.add_seen}
                ]

    def _load_data(self):
        try:
            with open(self.data_file) as f:
                data = load(f)
        except FileNotFoundError:
            data = {}
        except ValueError:
            data = {'error': 'Error loading seen file. '
                        'Operation could not complete.'}
        return data

    def _save_data(self, data):
        with open(self.data_file, 'w') as f:
            dump(data, f)

    def get_data_file(self):
        plugin_dir = self.handler.plugin_dir
        serv = self.bot.ident.host
        name = self.name

        data_dir = join(plugin_dir, 'data')
        if not exists(data_dir):
            mkdir(data_dir)
        serv_dir = join(data_dir, serv)
        if not exists(serv_dir):
            mkdir(serv_dir)
        name_dir = join(serv_dir, name)
        if not exists(name_dir):
            mkdir(name_dir)
        data_file = join(name_dir, 'seen.json')
        if not exists(data_file):
            with open(data_file, 'w') as f:
                dump({}, f)
        return data_file

    def add_seen(self, data):
        seens = self._load_data()
        chan = data.to
        if chan not in seens:
            seens[chan] = {}
        seens[chan][data.from_nick] = asctime()
        self._save_data(seens)

    def get_seen(self, data):
        if not data.trailing:
            self.conn.say('Specify a username.', data.to)
            return
        seens = self._load_data()
        nick = data.trailing[0]
        try:
            time = seens[data.to][nick]
        except KeyError:
            time = None
        if not time:
            self.conn.say('Sorry, I haven\'t seen {} lately.'.format(nick), data.to)
        else:
            self.conn.say('{} was last seen at {}'.format(nick, time), data.to)


text:
package hu.szigyi.references;

import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.junit.Test;

public class TestReferences {

	public class RefClass {

	}

	public List<String> occupyMemory() {
		List<String> strings = new ArrayList<>();
		for (int i = 0; i < 100; i++) {
			String string = "";
			for (int j = 0; j < 1000; j++) {
				char[] alpha = "abcdefghijklmnopqrstuvwxyz".toCharArray();
				Random r = new Random();
				int index = r.nextInt(26);
				char c = alpha[index];
				string += c;
			}
			strings.add(string);
		}
		return strings;
	}

	@Test
	public void whenStrongReference_thenGCLeaves() {
		RefClass strongRef = new RefClass();

		System.gc();

		assertThat(strongRef, notNullValue());
	}

	@Test
	public void softReference_whenThereIsEnoughMemory_thenGCLeaves() {
		SoftReference<RefClass> softRef = new SoftReference<TestReferences.RefClass>(new RefClass());

		System.gc();

		assertThat(softRef.get(), notNullValue());
	}

	@Test
	public void softReference_whenThereIsNotEnoughMemory_thenGCReclaims() {
		SoftReference<RefClass> softRef = new SoftReference<TestReferences.RefClass>(new RefClass());

		occupyMemory();
		System.gc();

		assertThat(softRef.get(), nullValue());
	}

	@Test
	public void whenWeakReference_thenGCReclaims() {
		WeakReference<RefClass> weakRef = new WeakReference<>(new RefClass());

		System.gc();

		// to reclaims the instance it takes some GC cycle based on the example. But why?
//		int counter = 0;
//		while (true) {
//			counter++;
//			System.gc();
//			if (null == weakRef.get()) {
//				System.out.println("GC cycle: " + counter);
//				break;
//			}
//		}

		assertThat(weakRef.get(), nullValue());
	}

	@Test
	public void whenPhantomReference_thenGCReclaims() {
		ReferenceQueue<RefClass> queue = new ReferenceQueue<>();
		PhantomReference<RefClass> phantomRef = new PhantomReference<>(new RefClass(), queue);

		System.gc();

		assertThat(queue.poll(), nullValue());
		assertThat(phantomRef.get(), nullValue());
	}
}


text:
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Newtonsoft.Json.Schema;
using System.IO;
using Newtonsoft.Json.Linq;

namespace Newtonsoft.Json.Tests.Schema
{
    [TestFixture]
    public class JsonSchemaBuilderTests : TestFixtureBase
    {
        [Test]
        public void Simple()
        {
            string json = @"
{
  ""description"": ""A person"",
  ""type"": ""object"",
  ""properties"":
  {
    ""name"": {""type"":""string""},
    ""hobbies"": {
      ""type"": ""array"",
      ""items"": {""type"":""string""}
    }
  }
}
";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("A person", schema.Description);
            Assert.AreEqual(JsonSchemaType.Object, schema.Type);

            Assert.AreEqual(2, schema.Properties.Count);

            Assert.AreEqual(JsonSchemaType.String, schema.Properties["name"].Type);
            Assert.AreEqual(JsonSchemaType.Array, schema.Properties["hobbies"].Type);
            Assert.AreEqual(JsonSchemaType.String, schema.Properties["hobbies"].Items[0].Type);
        }

        [Test]
        public void MultipleTypes()
        {
            string json = @"{
  ""description"":""Age"",
  ""type"":[""string"", ""integer""]
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("Age", schema.Description);
            Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Integer, schema.Type);
        }

        [Test]
        public void MultipleItems()
        {
            string json = @"{
  ""description"":""MultipleItems"",
  ""type"":""array"",
  ""items"": [{""type"":""string""},{""type"":""array""}]
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("MultipleItems", schema.Description);
            Assert.AreEqual(JsonSchemaType.String, schema.Items[0].Type);
            Assert.AreEqual(JsonSchemaType.Array, schema.Items[1].Type);
        }

        [Test]
        public void AdditionalProperties()
        {
            string json = @"{
  ""description"":""AdditionalProperties"",
  ""type"":[""string"", ""integer""],
  ""additionalProperties"":{""type"":[""object"", ""boolean""]}
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("AdditionalProperties", schema.Description);
            Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Boolean, schema.AdditionalProperties.Type);
        }

        [Test]
        public void Required()
        {
            string json = @"{
  ""description"":""Required"",
  ""required"":true
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("Required", schema.Description);
            Assert.AreEqual(true, schema.Required);
        }

        [Test]
        public void ExclusiveMinimum_ExclusiveMaximum()
        {
            string json = @"{
  ""exclusiveMinimum"":true,
  ""exclusiveMaximum"":true
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual(true, schema.ExclusiveMinimum);
            Assert.AreEqual(true, schema.ExclusiveMaximum);
        }

        [Test]
        public void ReadOnly()
        {
            string json = @"{
  ""description"":""ReadOnly"",
  ""readonly"":true
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("ReadOnly", schema.Description);
            Assert.AreEqual(true, schema.ReadOnly);
        }

        [Test]
        public void Hidden()
        {
            string json = @"{
  ""description"":""Hidden"",
  ""hidden"":true
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("Hidden", schema.Description);
            Assert.AreEqual(true, schema.Hidden);
        }

        [Test]
        public void Id()
        {
            string json = @"{
  ""description"":""Id"",
  ""id"":""testid""
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("Id", schema.Description);
            Assert.AreEqual("testid", schema.Id);
        }

        [Test]
        public void Title()
        {
            string json = @"{
  ""description"":""Title"",
  ""title"":""testtitle""
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("Title", schema.Description);
            Assert.AreEqual("testtitle", schema.Title);
        }

        [Test]
        public void Pattern()
        {
            string json = @"{
  ""description"":""Pattern"",
  ""pattern"":""testpattern""
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("Pattern", schema.Description);
            Assert.AreEqual("testpattern", schema.Pattern);
        }

        [Test]
        public void Format()
        {
            string json = @"{
  ""description"":""Format"",
  ""format"":""testformat""
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("Format", schema.Description);
            Assert.AreEqual("testformat", schema.Format);
        }

        [Test]
        public void Requires()
        {
            string json = @"{
  ""description"":""Requires"",
  ""requires"":""PurpleMonkeyDishwasher""
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("Requires", schema.Description);
            Assert.AreEqual("PurpleMonkeyDishwasher", schema.Requires);
        }

        [Test]
        public void MinimumMaximum()
        {
            string json = @"{
  ""description"":""MinimumMaximum"",
  ""minimum"":1.1,
  ""maximum"":1.2,
  ""minItems"":1,
  ""maxItems"":2,
  ""minLength"":5,
  ""maxLength"":50,
  ""divisibleBy"":3,
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("MinimumMaximum", schema.Description);
            Assert.AreEqual(1.1, schema.Minimum);
            Assert.AreEqual(1.2, schema.Maximum);
            Assert.AreEqual(1, schema.MinimumItems);
            Assert.AreEqual(2, schema.MaximumItems);
            Assert.AreEqual(5, schema.MinimumLength);
            Assert.AreEqual(50, schema.MaximumLength);
            Assert.AreEqual(3, schema.DivisibleBy);
        }

        [Test]
        public void DisallowSingleType()
        {
            string json = @"{
  ""description"":""DisallowSingleType"",
  ""disallow"":""string""
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("DisallowSingleType", schema.Description);
            Assert.AreEqual(JsonSchemaType.String, schema.Disallow);
        }

        [Test]
        public void DisallowMultipleTypes()
        {
            string json = @"{
  ""description"":""DisallowMultipleTypes"",
  ""disallow"":[""string"",""number""]
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("DisallowMultipleTypes", schema.Description);
            Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Float, schema.Disallow);
        }

        [Test]
        public void DefaultPrimitiveType()
        {
            string json = @"{
  ""description"":""DefaultPrimitiveType"",
  ""default"":1.1
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("DefaultPrimitiveType", schema.Description);
            Assert.AreEqual(1.1, (double)schema.Default);
        }

        [Test]
        public void DefaultComplexType()
        {
            string json = @"{
  ""description"":""DefaultComplexType"",
  ""default"":{""pie"":true}
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("DefaultComplexType", schema.Description);
            Assert.IsTrue(JToken.DeepEquals(JObject.Parse(@"{""pie"":true}"), schema.Default));
        }

        [Test]
        public void Enum()
        {
            string json = @"{
  ""description"":""Type"",
  ""type"":[""string"",""array""],
  ""enum"":[""string"",""object"",""array"",""boolean"",""number"",""integer"",""null"",""any""]
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("Type", schema.Description);
            Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Array, schema.Type);

            Assert.AreEqual(8, schema.Enum.Count);
            Assert.AreEqual("string", (string)schema.Enum[0]);
            Assert.AreEqual("any", (string)schema.Enum[schema.Enum.Count - 1]);
        }

        [Test]
        public void CircularReference()
        {
            string json = @"{
  ""id"":""CircularReferenceArray"",
  ""description"":""CircularReference"",
  ""type"":[""array""],
  ""items"":{""$ref"":""CircularReferenceArray""}
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("CircularReference", schema.Description);
            Assert.AreEqual("CircularReferenceArray", schema.Id);
            Assert.AreEqual(JsonSchemaType.Array, schema.Type);

            Assert.AreEqual(schema, schema.Items[0]);
        }

        [Test]
        public void UnresolvedReference()
        {
            ExceptionAssert.Throws<Exception>(@"Could not resolve schema reference 'MyUnresolvedReference'.",
                () =>
                {
                    string json = @"{
  ""id"":""CircularReferenceArray"",
  ""description"":""CircularReference"",
  ""type"":[""array""],
  ""items"":{""$ref"":""MyUnresolvedReference""}
}";

                    JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
                    JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
                });
        }

        [Test]
        public void PatternProperties()
        {
            string json = @"{
  ""patternProperties"": {
    ""[abc]"": { ""id"":""Blah"" }
  }
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.IsNotNull(schema.PatternProperties);
            Assert.AreEqual(1, schema.PatternProperties.Count);
            Assert.AreEqual("Blah", schema.PatternProperties["[abc]"].Id);
        }

        [Test]
        public void AdditionalItems()
        {
            string json = @"{
    ""items"": [],
    ""additionalItems"": {""type"": ""integer""}
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.IsNotNull(schema.AdditionalItems);
            Assert.AreEqual(JsonSchemaType.Integer, schema.AdditionalItems.Type);
            Assert.AreEqual(true, schema.AllowAdditionalItems);
        }

        [Test]
        public void DisallowAdditionalItems()
        {
            string json = @"{
    ""items"": [],
    ""additionalItems"": false
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.IsNull(schema.AdditionalItems);
            Assert.AreEqual(false, schema.AllowAdditionalItems);
        }

        [Test]
        public void AllowAdditionalItems()
        {
            string json = @"{
    ""items"": {},
    ""additionalItems"": false
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.IsNull(schema.AdditionalItems);
            Assert.AreEqual(false, schema.AllowAdditionalItems);
        }

        [Test]
        public void Location()
        {
            string json = @"{
  ""properties"":{
    ""foo"":{
      ""type"":""array"",
      ""items"":[
        {
          ""type"":""integer""
        },
        {
          ""properties"":{
            ""foo"":{
              ""type"":""integer""
            }
          }
        }
      ]
    }
  }
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual("#", schema.Location);
            Assert.AreEqual("#/properties/foo", schema.Properties["foo"].Location);
            Assert.AreEqual("#/properties/foo/items/1/properties/foo", schema.Properties["foo"].Items[1].Properties["foo"].Location);
        }

        [Test]
        public void Reference_BackwardsLocation()
        {
            string json = @"{
  ""properties"": {
    ""foo"": {""type"": ""integer""},
    ""bar"": {""$ref"": ""#/properties/foo""}
  }
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual(schema.Properties["foo"], schema.Properties["bar"]);
        }

        [Test]
        public void Reference_ForwardsLocation()
        {
            string json = @"{
  ""properties"": {
    ""bar"": {""$ref"": ""#/properties/foo""},
    ""foo"": {""type"": ""integer""}
  }
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual(schema.Properties["foo"], schema.Properties["bar"]);
        }

        [Test]
        public void Reference_NonStandardLocation()
        {
            string json = @"{
  ""properties"": {
    ""bar"": {""$ref"": ""#/common/foo""},
    ""foo"": {""$ref"": ""#/common/foo""}
  },
  ""common"": {
    ""foo"": {""type"": ""integer""}
  }
}";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual(schema.Properties["foo"], schema.Properties["bar"]);
        }

        [Test]
        public void EscapedReferences()
        {
            string json = @"{
            ""tilda~field"": {""type"": ""integer""},
            ""slash/field"": {""type"": ""object""},
            ""percent%field"": {""type"": ""array""},
            ""properties"": {
                ""tilda"": {""$ref"": ""#/tilda~0field""},
                ""slash"": {""$ref"": ""#/slash~1field""},
                ""percent"": {""$ref"": ""#/percent%25field""}
            }
        }";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual(JsonSchemaType.Integer, schema.Properties["tilda"].Type);
            Assert.AreEqual(JsonSchemaType.Object, schema.Properties["slash"].Type);
            Assert.AreEqual(JsonSchemaType.Array, schema.Properties["percent"].Type);
        }

        [Test]
        public void References_Array()
        {
            string json = @"{
            ""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}],
            ""properties"": {
                ""array"": {""$ref"": ""#/array/0""},
                ""arrayprop"": {""$ref"": ""#/array/1/prop""}
            }
        }";

            JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
            JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));

            Assert.AreEqual(JsonSchemaType.Integer, schema.Properties["array"].Type);
            Assert.AreEqual(JsonSchemaType.Object, schema.Properties["arrayprop"].Type);
        }

        [Test]
        public void References_IndexTooBig()
        {
            // JsonException : Could not resolve schema reference '#/array/10'.

            string json = @"{
            ""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}],
            ""properties"": {
                ""array"": {""$ref"": ""#/array/0""},
                ""arrayprop"": {""$ref"": ""#/array/10""}
            }
        }";

            ExceptionAssert.Throws<JsonException>(
                "Could not resolve schema reference '#/array/10'.",
                () =>
                {
                    JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
                    builder.Read(new JsonTextReader(new StringReader(json)));
                });
        }

        [Test]
        public void References_IndexNegative()
        {
            string json = @"{
            ""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}],
            ""properties"": {
                ""array"": {""$ref"": ""#/array/0""},
                ""arrayprop"": {""$ref"": ""#/array/-1""}
            }
        }";

            ExceptionAssert.Throws<JsonException>(
                "Could not resolve schema reference '#/array/-1'.",
                () =>
                {
                    JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
                    builder.Read(new JsonTextReader(new StringReader(json)));
                });
        }

        [Test]
        public void References_IndexNotInteger()
        {
            string json = @"{
            ""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}],
            ""properties"": {
                ""array"": {""$ref"": ""#/array/0""},
                ""arrayprop"": {""$ref"": ""#/array/one""}
            }
        }";

            ExceptionAssert.Throws<JsonException>(
                "Could not resolve schema reference '#/array/one'.",
                () =>
                {
                    JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
                    builder.Read(new JsonTextReader(new StringReader(json)));
                });
        }
    }
}


text:
package net.sourceforge.stripes.mock;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;

/**
 * Mock implementation of a RequesetDispatcher used for testing purposes. Note that the mock
 * implementation does not support actually forwarding the request, or including other resources.
 * The methods are implemented to record that a forward/include took place and then simply
 * return.
 *
 * @author Tim Fennell
 * @since Stripes 1.1.1
 */
public class MockRequestDispatcher implements RequestDispatcher {
    private String url;

    /** Constructs a request dispatcher, giving it a handle to the creating request. */
    public MockRequestDispatcher(String url) {
        this.url = url;
    }

    /** Simply stores the URL that was requested for forward, and returns. */
    public void forward(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        getMockRequest(req).setForwardUrl(this.url);
    }

    /** Simply stores that the URL was included an then returns. */
    public void include(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        getMockRequest(req).addIncludedUrl(this.url);
    }

    /** Locates the MockHttpServletRequest in case it is wrapped. */
    public MockHttpServletRequest getMockRequest(ServletRequest request) {
        while (request != null & !(request instanceof MockHttpServletRequest)) {
            request = ((HttpServletRequestWrapper) request).getRequest();
        }

        return (MockHttpServletRequest) request;
    }
}


text:
static inline int crypto_verify_16(const unsigned char *,const unsigned char *);
static inline int crypto_verify_32(const unsigned char *,const unsigned char *);

#endif


text:
package com.photon.phresco.commons.model;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class WebServiceTest {

	WebService webService = new WebService();
	WebService webService2 = new WebService("testId", "testName", "testVersion", "testDescription");

	@Test
	public void testGetVersion() {
		webService.setVersion("testVersion");
		String test = webService.getVersion();
		assertNotNull(test);
	}

	@Test
	public void testGetAppliesToTech() {
		List<String> appliesToTech = new ArrayList<String>();
		appliesToTech.add("testTech");
		webService.setAppliesToTechs(appliesToTech);
		List<String> test = webService.getAppliesToTechs();
		assertNotNull(test);
	}

	@Test
	public void testToString() {
		String test = webService.toString();
		assertNotNull(test);
	}
}


text:
class A(object):
  def __init__<caret>


text:
	© 2013 GmodLive private project do not share
	without permission of its author (Andrew Mensky vk.com/men232).
--]]
if SERVER then return end;

local gc = gc;
local math = math;
local surface = surface;

local PLUGIN = PLUGIN or greenCode.plugin:Loader();

local SCREEN_DAMAGE_OVERLAY = Material("greencode/vgui/screendamagev2.png");
local VIGNETTE_OVERLAY = Material("greencode/vgui/vignette.png");
local SCREEN_DAMAGE_OVERLAY_EXIST = SCREEN_DAMAGE_OVERLAY_EXIST or false;
local VIGNETTE_OVERLAY_EXIST = VIGNETTE_OVERLAY_EXIST or false;

CREEN_DAMAG_ALPHA = 0;

function PLUGIN:DrawPlayerScreenDamage(damageFraction)
	if ( SCREEN_DAMAGE_OVERLAY_EXISTS ) then
		local scrW, scrH = ScrW(), ScrH();
		surface.SetDrawColor(255, 255, 255, math.Clamp(255 * damageFraction, 0, 255));
		surface.SetMaterial(SCREEN_DAMAGE_OVERLAY);
		surface.DrawTexturedRect(0, 0, scrW, scrH);
	end;
end;

function PLUGIN:DrawPlayerVignette()
	if ( VIGNETTE_OVERLAY_EXIST ) then
		if (!gc.gcVignetteAlpha) then
			gc.gcVignetteAlpha = 150;
			gc.gcVignetteAlphaDelta = gc.gcVignetteAlpha;
		end;

		local data = {};
			data.start = gc.Client:GetShootPos();
			data.endpos = data.start + (gc.Client:GetUp() * 512);
			data.filder = gc.Client;
		local trace = util.TraceLine(data);

		gc.gcVignetteAlpha = (!trace.HitWorld and !trace.HitNonWorld) and 150 or 255;
		gc.gcVignetteAlphaDelta = math.Approach(gc.gcVignetteAlphaDelta, gc.gcVignetteAlpha, FrameTime() * 70);

		local scrW, scrH = ScrW(), ScrH();

		surface.SetDrawColor(0, 0, 0, gc.gcVignetteAlphaDelta);
		surface.SetMaterial(VIGNETTE_OVERLAY);
		surface.DrawTexturedRect(0, 0, scrW, scrH);
	end;
end;

function PLUGIN:PostHUDPaint()
	//if (gc.Client:Alive()) then
		if (CREEN_DAMAG_ALPHA > 0) then
			CREEN_DAMAG_ALPHA = math.Approach(CREEN_DAMAG_ALPHA, 0, FrameTime() * 70);
			gc.plugin:Call("DrawPlayerScreenDamage", CREEN_DAMAG_ALPHA/255);
		end;
	//end;

	if (gc.config:Get("enable_vignette"):Get()) then
		gc.plugin:Call("DrawPlayerVignette");
	end;
end;

-- Called when an entity takes damage.
function PLUGIN:Think()
	local curHealth = gc.Client:Health();

	if ( !self.hp ) then
		self.hp = gc.Client:Health();
	end;

	local amount = curHealth - self.hp;

	if ( amount < 0 ) then
		CREEN_DAMAG_ALPHA = math.Clamp( CREEN_DAMAG_ALPHA + amount*-10, 0, 255 );
		self.hp = curHealth;
	else
		self.hp = curHealth;
	end;
end;

function PLUGIN:InitPostEntity()
	timer.Simple(1, function()
		SCREEN_DAMAGE_OVERLAY_EXIST = file.Exists( "materials/greencode/vgui/screendamagev2.png", "GAME" ) ;
		VIGNETTE_OVERLAY_EXIST = file.Exists( "materials/greencode/vgui/vignette.png", "GAME" ) ;
	end);
end;


text:
package com.datamaio.scd4j.conf;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;

import org.hamcrest.CoreMatchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class EnvTest {
	private static final String PRODUCTION_IP2 = "3.3.3.2";
	private static final String PRODUCTION_IP1 = "3.3.3.1";
	private static final String STAGING_IP2 = "2.2.2.2";
	private static final String STAGING_IP1 = "2.2.2.1";
	private static final String TESTING_IP = "1.1.1.0";
	private static final String DESENV_IP = "0.0.0.0";

	private static String[] productionIps = new String[]{PRODUCTION_IP1, PRODUCTION_IP2};
	private static String[] stagingIps = new String[]{STAGING_IP1, STAGING_IP2};
	private static String[] testingIps = new String[]{TESTING_IP};

	@Spy
	private Env env = new Env(productionIps, stagingIps, testingIps);
	@Spy
	private Env env2 = new Env();

	@Before
	public void setup(){

	}

	@After
	public void teardown() throws Exception {
		reset(env);
		reset(env2);
	}

	@Test
	public void notSettingConfiguredEnvironment(){
		try {
			env.isDevelopment(DESENV_IP);
			fail("It should be failled because ConfiguredEnvironment is not set!");
		} catch (IllegalStateException e){
			// ok
		}

		try {
			env.isTesting(TESTING_IP);
			fail("It should be failled because ConfiguredEnvironment is not set!");
		} catch (IllegalStateException e){
			// ok
		}

		try {
			env.isStaging(STAGING_IP1);
			fail("It should be failled because ConfiguredEnvironment is not set!");
		} catch (IllegalStateException e){
			// ok
		}

		try {
			env.isProduction(PRODUCTION_IP1);
			fail("It should be failled because ConfiguredEnvironment is not set!");
		} catch (IllegalStateException e){
			// ok
		}
	}

	@Test(expected=IllegalStateException.class)
	public void tryToRunAProductionConfigAgainstANonProductionEnvironment(){
		when(env.whatIsMyIp()).thenReturn(STAGING_IP1);

		env.setConfiguredEnvironment("production");
	}

	@Test(expected=IllegalStateException.class)
	public void tryToRunAStagingConfigAgainstANonStatingEnvironment(){
		when(env.whatIsMyIp()).thenReturn(DESENV_IP);

		env.setConfiguredEnvironment("staging");
	}

	@Test(expected=IllegalStateException.class)
	public void tryToRunATestingConfigAgainstANonTestingEnvironment(){
		when(env.whatIsMyIp()).thenReturn(DESENV_IP);

		env.setConfiguredEnvironment("testing");
	}

	@Test
	public void noEnvValidationBecauseListOfIpsIsEmpty(){
		when(env2.whatIsMyIp()).thenReturn(DESENV_IP);

		env2.setConfiguredEnvironment("development");
		env2.setConfiguredEnvironment("testing");
		env2.setConfiguredEnvironment("staging");
		env2.setConfiguredEnvironment("production");
	}

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

	@Test(expected=IllegalArgumentException.class)
	public void newEnvWithProductionIpIntersection(){
		new Env(productionIps, new String[]{STAGING_IP1, PRODUCTION_IP1}, new String[]{});
	}

	@Test(expected=IllegalArgumentException.class)
	public void newEnvWithProductionIpIntersection2(){
		new Env(productionIps, new String[]{}, new String[]{PRODUCTION_IP1});
	}

	@Test
	public void newEnvOk(){
		new Env(productionIps, new String[]{}, new String[]{});
	}

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

	@Test
	public void isTestingYes(){
		when(env.whatIsMyIp()).thenReturn(TESTING_IP);
		env.setConfiguredEnvironment("testing");
		assertThat(env.isTesting(TESTING_IP), is(equalTo(true)));

		when(env2.whatIsMyIp()).thenReturn(DESENV_IP);
		env2.setConfiguredEnvironment("testing");
		assertThat(env2.isTesting(TESTING_IP), is(equalTo(true)));
	}

	@Test
	public void isTestingNo(){
		when(env.whatIsMyIp()).thenReturn(PRODUCTION_IP1);
		env.setConfiguredEnvironment("production");
		assertThat(env.isTesting(PRODUCTION_IP1), is(equalTo(false)));

		when(env2.whatIsMyIp()).thenReturn(DESENV_IP);
		env2.setConfiguredEnvironment("production");
		assertThat(env2.isTesting(PRODUCTION_IP1), is(equalTo(false)));
	}

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

	@Test
	public void isStagingYes(){
		when(env.whatIsMyIp()).thenReturn(STAGING_IP1);
		env.setConfiguredEnvironment("staging");
		assertThat(env.isStaging(STAGING_IP1), is(equalTo(true)));

		when(env2.whatIsMyIp()).thenReturn(DESENV_IP);
		env2.setConfiguredEnvironment("staging");
		assertThat(env2.isStaging(STAGING_IP1), is(equalTo(true)));
	}

	@Test
	public void isStagingNo(){
		when(env.whatIsMyIp()).thenReturn(PRODUCTION_IP1);
		env.setConfiguredEnvironment("production");
		assertThat(env.isStaging(PRODUCTION_IP1), is(equalTo(false)));

		when(env2.whatIsMyIp()).thenReturn(DESENV_IP);
		env2.setConfiguredEnvironment("production");
		assertThat(env2.isStaging(PRODUCTION_IP1), is(equalTo(false)));
	}

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

	@Test
	public void isProductionYes(){
		when(env.whatIsMyIp()).thenReturn(PRODUCTION_IP1);
		env.setConfiguredEnvironment("production");
		assertThat(env.isProduction(PRODUCTION_IP1), is(equalTo(true)));

		when(env2.whatIsMyIp()).thenReturn(DESENV_IP);
		env2.setConfiguredEnvironment("production");
		assertThat(env2.isProduction(PRODUCTION_IP1), is(equalTo(true)));
	}

	@Test
	public void isProductionNo(){
		when(env.whatIsMyIp()).thenReturn(STAGING_IP1);
		env.setConfiguredEnvironment("staging");
		assertThat(env.isProduction(STAGING_IP1), is(equalTo(false)));

		when(env2.whatIsMyIp()).thenReturn(DESENV_IP);
		env2.setConfiguredEnvironment("staging");
		assertThat(env2.isProduction(STAGING_IP1), is(equalTo(false)));
	}

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

	@Test
	public void isDevelopmentYes(){
		when(env.whatIsMyIp()).thenReturn(DESENV_IP);
		env.setConfiguredEnvironment("development");
		assertThat(env.isDevelopment(DESENV_IP), is(equalTo(true)));

		when(env2.whatIsMyIp()).thenReturn(DESENV_IP);
		env2.setConfiguredEnvironment("development");
		assertThat(env2.isDevelopment(DESENV_IP), is(equalTo(true)));
	}

	@Test
	public void isDevelopmentNo(){
		when(env.whatIsMyIp()).thenReturn(STAGING_IP1);
		env.setConfiguredEnvironment("staging");
		assertThat(env.isDevelopment(STAGING_IP1), is(equalTo(false)));

		when(env2.whatIsMyIp()).thenReturn(STAGING_IP1);
		env2.setConfiguredEnvironment("staging");
		assertThat(env2.isDevelopment(STAGING_IP1), is(equalTo(false)));
	}

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

	@Test
	public void settingNullToConfiguredEnvironmentMustBeDevelopment(){
		when(env.whatIsMyIp()).thenReturn(DESENV_IP);
		env.setConfiguredEnvironment(null);
		assertThat(env.isDevelopment(DESENV_IP), is(equalTo(true)));
	}

	@Test
	public void settingInvalidArgumentToConfiguredEnvironment(){
		try {
			env2.setConfiguredEnvironment("dev");
			fail("Should be thrown an Illegal argument exception!");
		} catch (IllegalArgumentException e) {
			assertThat(e.getMessage(), CoreMatchers.containsString("Check your config file!"));
		}
	}

}


text:
"""Place and route utilities.
"""
from __future__ import absolute_import

import pickle

from six import iteritems

from collections import defaultdict

from rig.netlist import Net

from rig.place_and_route.constraints import (LocationConstraint,
                                             RouteEndpointConstraint,
                                             SameChipConstraint)

from nengo_spinnaker.builder import Model
from nengo_spinnaker.node_io import Ethernet

def create_network_netlist(network, n_steps, fp, dt=0.001):
    """Create a netlist of a network running for a number of steps, dump that
    netlist to file.
    """
    # Build the network, assuming EthernetIO
    model = Model(dt)
    node_io = Ethernet()
    model.build(network, **node_io.builder_kwargs)

    # Build the netlist
    netlist = model.make_netlist(n_steps).as_rig_arguments()
    pickle_netlist(netlist, fp)

def pickle_netlist(netlist_dict, fp, **kwargs):
    """Dump a pickle of a netlist to a file.

    This function replaces all vertices with `object` instances so that
    nengo-specific or project-specific dependencies are not included.
    """
    # {old_vertex: new_vertex, ...}
    new_vertices = defaultdict(object)

    netlist_dict["vertices_resources"] = {
        new_vertices[vertex]: resources
        for (vertex, resources)
        in iteritems(netlist_dict["vertices_resources"])
    }

    netlist_dict["nets"] = [
        Net(new_vertices[net.source],
            [new_vertices[sink] for sink in net.sinks],
            net.weight)
        for net in netlist_dict["nets"]
    ]

    old_constraints = netlist_dict["constraints"]
    netlist_dict["constraints"] = []
    for constraint in old_constraints:
        if isinstance(constraint, LocationConstraint):
            netlist_dict["constraints"].append(
                LocationConstraint(new_vertices[constraint.vertex],
                                   constraint.location))
        elif isinstance(constraint, RouteEndpointConstraint):
            netlist_dict["constraints"].append(
                RouteEndpointConstraint(new_vertices[constraint.vertex],
                                        constraint.route))
        elif isinstance(constraint, SameChipConstraint):
            # Get the new vertices
            vs = [new_vertices[v] for v in constraint.vertices]
            netlist_dict["constraints"].append(SameChipConstraint(vs))
        else:
            netlist_dict["constraints"].append(constraint)

    pickle.dump(netlist_dict, fp, **kwargs)


text:
/**
 * @file
 *   This file includes definitions for non-volatile storage of settings.
 */

#define WPP_NAME "settings.tmh"

#include "settings.hpp"

#include <openthread/platform/settings.h>

#include "common/code_utils.hpp"
#include "common/instance.hpp"
#include "common/logging.hpp"
#include "meshcop/dataset.hpp"
#include "thread/mle.hpp"

namespace ot {

#if (OPENTHREAD_CONFIG_LOG_UTIL != 0)
#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO)

void SettingsBase::LogNetworkInfo(const char *aAction, const NetworkInfo &aNetworkInfo) const
{
    otLogInfoCore("Non-volatile: %s NetworkInfo {rloc:0x%04x, extaddr:%s, role:%s, mode:0x%02x, keyseq:0x%x, ...",
                  aAction, aNetworkInfo.mRloc16, aNetworkInfo.mExtAddress.ToString().AsCString(),
                  Mle::Mle::RoleToString(static_cast<otDeviceRole>(aNetworkInfo.mRole)), aNetworkInfo.mDeviceMode,
                  aNetworkInfo.mKeySequence);

    otLogInfoCore("Non-volatile: ... pid:0x%x, mlecntr:0x%x, maccntr:0x%x, mliid:%02x%02x%02x%02x%02x%02x%02x%02x}",
                  aNetworkInfo.mPreviousPartitionId, aNetworkInfo.mMleFrameCounter, aNetworkInfo.mMacFrameCounter,
                  aNetworkInfo.mMlIid[0], aNetworkInfo.mMlIid[1], aNetworkInfo.mMlIid[2], aNetworkInfo.mMlIid[3],
                  aNetworkInfo.mMlIid[4], aNetworkInfo.mMlIid[5], aNetworkInfo.mMlIid[6], aNetworkInfo.mMlIid[7]);
}

void SettingsBase::LogParentInfo(const char *aAction, const ParentInfo &aParentInfo) const
{
    otLogInfoCore("Non-volatile: %s ParentInfo {extaddr:%s}", aAction, aParentInfo.mExtAddress.ToString().AsCString());
}

void SettingsBase::LogChildInfo(const char *aAction, const ChildInfo &aChildInfo) const
{
    otLogInfoCore("Non-volatile: %s ChildInfo {rloc:0x%04x, extaddr:%s, timeout:%u, mode:0x%02x}", aAction,
                  aChildInfo.mRloc16, aChildInfo.mExtAddress.ToString().AsCString(), aChildInfo.mTimeout,
                  aChildInfo.mMode);
}

#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO)

#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN)

void SettingsBase::LogFailure(otError error, const char *aText, bool aIsDelete) const
{
    if ((error != OT_ERROR_NONE) && (!aIsDelete || (error != OT_ERROR_NOT_FOUND)))
    {
        otLogWarnCore("Non-volatile: Error %s %s", otThreadErrorToString(error), aText);
    }
}

#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN)
#endif // #if (OPENTHREAD_CONFIG_LOG_UTIL != 0)

void Settings::Init(void)
{
    otPlatSettingsInit(&GetInstance());
}

void Settings::Wipe(void)
{
    otPlatSettingsWipe(&GetInstance());
    otLogInfoCore("Non-volatile: Wiped all info");
}

otError Settings::SaveOperationalDataset(bool aIsActive, const MeshCoP::Dataset &aDataset)
{
    otError error = Save(aIsActive ? kKeyActiveDataset : kKeyPendingDataset, aDataset.GetBytes(), aDataset.GetSize());

    LogFailure(error, "saving OperationalDataset", false);
    return error;
}

otError Settings::ReadOperationalDataset(bool aIsActive, MeshCoP::Dataset &aDataset) const
{
    otError  error = OT_ERROR_NONE;
    uint16_t length;

    SuccessOrExit(error = Read(aIsActive ? kKeyActiveDataset : kKeyPendingDataset, aDataset.GetBytes(),
                               MeshCoP::Dataset::kMaxSize, length));
    aDataset.SetSize(length);

exit:
    return error;
}

otError Settings::DeleteOperationalDataset(bool aIsActive)
{
    otError error = Delete(aIsActive ? kKeyActiveDataset : kKeyPendingDataset);

    LogFailure(error, "deleting OperationalDataset", true);

    return error;
}

otError Settings::ReadNetworkInfo(NetworkInfo &aNetworkInfo) const
{
    otError error;

    SuccessOrExit(error = ReadFixedSize(kKeyNetworkInfo, &aNetworkInfo, sizeof(NetworkInfo)));
    LogNetworkInfo("Read", aNetworkInfo);

exit:
    return error;
}

otError Settings::SaveNetworkInfo(const NetworkInfo &aNetworkInfo)
{
    otError error;

    SuccessOrExit(error = Save(kKeyNetworkInfo, &aNetworkInfo, sizeof(NetworkInfo)));
    LogNetworkInfo("Saved", aNetworkInfo);

exit:
    LogFailure(error, "saving NetworkInfo", false);
    return error;
}

otError Settings::DeleteNetworkInfo(void)
{
    otError error;

    SuccessOrExit(error = Delete(kKeyNetworkInfo));
    otLogInfoCore("Non-volatile: Deleted NetworkInfo");

exit:
    LogFailure(error, "deleting NetworkInfo", true);
    return error;
}

otError Settings::ReadParentInfo(ParentInfo &aParentInfo) const
{
    otError error;

    SuccessOrExit(error = ReadFixedSize(kKeyParentInfo, &aParentInfo, sizeof(ParentInfo)));
    LogParentInfo("Read", aParentInfo);

exit:
    return error;
}

otError Settings::SaveParentInfo(const ParentInfo &aParentInfo)
{
    otError error;

    SuccessOrExit(error = Save(kKeyParentInfo, &aParentInfo, sizeof(ParentInfo)));
    LogParentInfo("Saved", aParentInfo);

exit:
    LogFailure(error, "saving ParentInfo", false);
    return error;
}

otError Settings::DeleteParentInfo(void)
{
    otError error;

    SuccessOrExit(error = Delete(kKeyParentInfo));
    otLogInfoCore("Non-volatile: Deleted ParentInfo");

exit:
    LogFailure(error, "deleting ParentInfo", true);
    return error;
}

otError Settings::AddChildInfo(const ChildInfo &aChildInfo)
{
    otError error;

    SuccessOrExit(error = Add(kKeyChildInfo, &aChildInfo, sizeof(aChildInfo)));
    LogChildInfo("Added", aChildInfo);

exit:
    LogFailure(error, "adding ChildInfo", false);
    return error;
}

otError Settings::DeleteChildInfo(void)
{
    otError error;

    SuccessOrExit(error = Delete(kKeyChildInfo));
    otLogInfoCore("Non-volatile: Deleted all ChildInfo");

exit:
    LogFailure(error, "deleting all ChildInfo", true);
    return error;
}

Settings::ChildInfoIterator::ChildInfoIterator(Instance &aInstance)
    : SettingsBase(aInstance)
    , mIndex(0)
    , mIsDone(false)
{
    Reset();
}

void Settings::ChildInfoIterator::Reset(void)
{
    mIndex  = 0;
    mIsDone = false;
    Read();
}

void Settings::ChildInfoIterator::Advance(void)
{
    if (!mIsDone)
    {
        mIndex++;
        Read();
    }
}

otError Settings::ChildInfoIterator::Delete(void)
{
    otError error = OT_ERROR_NONE;

    VerifyOrExit(!mIsDone, error = OT_ERROR_INVALID_STATE);
    SuccessOrExit(error = otPlatSettingsDelete(&GetInstance(), kKeyChildInfo, mIndex));
    LogChildInfo("Removed", mChildInfo);

exit:
    LogFailure(error, "removing ChildInfo entry", true);
    return error;
}

void Settings::ChildInfoIterator::Read(void)
{
    uint16_t size = sizeof(ChildInfo);
    otError  error;

    SuccessOrExit(error = otPlatSettingsGet(&GetInstance(), kKeyChildInfo, mIndex,
                                            reinterpret_cast<uint8_t *>(&mChildInfo), &size));
    VerifyOrExit(size >= sizeof(ChildInfo), error = OT_ERROR_NOT_FOUND);
    LogChildInfo("Read", mChildInfo);

exit:
    mIsDone = (error != OT_ERROR_NONE);
}

otError Settings::ReadFixedSize(Key aKey, void *aBuffer, uint16_t aExpectedSize) const
{
    uint16_t size = aExpectedSize;
    otError  error;

    SuccessOrExit(error = otPlatSettingsGet(&GetInstance(), aKey, 0, reinterpret_cast<uint8_t *>(aBuffer), &size));
    VerifyOrExit(size >= aExpectedSize, error = OT_ERROR_NOT_FOUND);

exit:
    return error;
}

otError Settings::Read(Key aKey, void *aBuffer, uint16_t aMaxBufferSize, uint16_t &aReadSize) const
{
    uint16_t size = aMaxBufferSize;
    otError  error;

    SuccessOrExit(error = otPlatSettingsGet(&GetInstance(), aKey, 0, reinterpret_cast<uint8_t *>(aBuffer), &size));
    aReadSize = (size <= aMaxBufferSize) ? size : aMaxBufferSize;

exit:
    return error;
}

otError Settings::Save(Key aKey, const void *aBuffer, uint16_t aSize)
{
    return otPlatSettingsSet(&GetInstance(), aKey, reinterpret_cast<const uint8_t *>(aBuffer), aSize);
}

otError Settings::Add(Key aKey, const void *aBuffer, uint16_t aSize)
{
    return otPlatSettingsAdd(&GetInstance(), aKey, reinterpret_cast<const uint8_t *>(aBuffer), aSize);
}

otError Settings::Delete(Key aKey)
{
    return otPlatSettingsDelete(&GetInstance(), aKey, -1);
}

} // namespace ot


text:
namespace athena {
namespace test {

AthenaBrowserTest::AthenaBrowserTest() {
}

AthenaBrowserTest::~AthenaBrowserTest() {
}

content::BrowserContext* AthenaBrowserTest::GetBrowserContext() {
  return extensions::ShellContentBrowserClient::Get()->GetBrowserContext();
}

void AthenaBrowserTest::SetUpCommandLine(base::CommandLine* command_line) {
  command_line->AppendSwitchASCII(switches::kTestType, "athena");
  // The NaCl sandbox won't work in our browser tests.
  command_line->AppendSwitch(switches::kNoSandbox);
  content::BrowserTestBase::SetUpCommandLine(command_line);
}

void AthenaBrowserTest::SetUpOnMainThread() {
  content::BrowserContext* context = GetBrowserContext();
  athena::StartAthenaEnv(content::BrowserThread::GetBlockingPool()
                             ->GetTaskRunnerWithShutdownBehavior(
                                 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
  athena::CreateVirtualKeyboardWithContext(context);
  athena::StartAthenaSessionWithContext(context);

  // Set the memory pressure to low and turning off undeterministic resource
  // observer events.
  test_util::SendTestMemoryPressureEvent(ResourceManager::MEMORY_PRESSURE_LOW);
}

void AthenaBrowserTest::RunTestOnMainThreadLoop() {
  base::MessageLoopForUI::current()->RunUntilIdle();
  SetUpOnMainThread();
  RunTestOnMainThread();
  TearDownOnMainThread();
}

}  // namespace test
}  // namespace athena


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.ohd.pophealth.ccr.importer;

/**
 * Simple exception for when a measure category is not supported
 *
 * @author Steven Waldren <swaldren at openhealthdata.com>
 */
public class NonSupportedCategoryException extends Exception {

    public NonSupportedCategoryException(String s){
        super(s);
    }

    public NonSupportedCategoryException(){
        super();
    }

}


text:
namespace SimpleFactory
{
    public class Program
    {
        static void Main(string[] args)
        {
            var cofeeFactory = new CofeeFactory();
            var capuchinno = cofeeFactory.GetCofee(CofeeType.Capuchinno);
            var doubleCofee = cofeeFactory.GetCofee(CofeeType.Double);
            System.Console.WriteLine(capuchinno);
            System.Console.WriteLine(doubleCofee);
        }
    }
}


text:
<?php

namespace Reliv\RcmApiLib\Api\ApiResponse;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * @author James Jervis - https://github.com/jerv13
 */
class NewZfResponseWithTranslatedMessagesFactory
{
    /**
     * __invoke
     *
     * @param $container ContainerInterface|ServiceLocatorInterface
     *
     * @return NewZfResponseWithTranslatedMessages
     */
    public function __invoke($container)
    {
        return new NewZfResponseWithTranslatedMessages(
            $container->get(WithApiMessage::class),
            $container->get(WithTranslatedApiMessages::class)
        );
    }
}


text:
import React from 'react'
import styled from 'styled-components'

import Box from './Box'
import { mobileOnlyStyles } from '../helpers'

const Img = styled.img`
  width: ${props => (props.resizeByHeight ? 'auto' : '200px')};
  height: ${props => (props.resizeByHeight ? '72px' : 'auto')};

  ${props =>
    props.resizeByHeight &&
    mobileOnlyStyles(`
    height: 50px;
  `)}
`

const Media = ({ logo, name, link, resizeByHeight, showName, ...props }) => (
  <Box
    css={`
      ${mobileOnlyStyles('flex: 1 1 80%;')}
    `}
    column
    margin="32px 0"
    {...props}
  >
    <Img src={logo} alt={name} title={name} resizeByHeight={resizeByHeight} />
    {showName && name}
  </Box>
)

export default Media


text:
/*

Print all Nodes at a given distance from a starting Node in a binary tree

*/

#include<iostream>
#include<vector>
#include<unordered_set>
#include<queue>
using namespace std;

//The binary tree has parent link.

/*

solution:  print nodes in the subtree of the start node is easy. For those nodes as the start node's ancestor,
use parent link to move up to print nodes, for those nodes as the start node's neighbor and those nodes in another
subtree of the full tree, call the print down function with proper node and update distance.

O(n) time, O(1) space

*/

struct TNode {
    int val;
    TNode* plft;
    TNode* prgt;
    TNode* parent;

    TNode(int v) : val(v), plft(NULL), prgt(NULL), parent(NULL)  {}
};

//print node below given node
void PrintDown(TNode * node, int k) {

    if (node == NULL || k < 0) return;

    if (k == 0) {
        cout<<node->val<<endl;
    } else {
        PrintDown(node->plft, k -1);
        PrintDown(node->prgt, k -1);
    }
}
//print above node from given node
void PrintAbove(TNode* node, int k) {

    if(node == NULL || k < 0) return;

    TNode *parent = NULL;
    parent = node->parent;
    while (parent != NULL) {
        k--;
		if(k == 0) {
            cout<<parent->val<<endl;
        } else if(node == parent->plft) {
			PrintDown(parent->prgt, k-1);
        } else {
            PrintDown(parent->plft,k-1);
        }

        node = parent;
        parent  = parent->parent;
    }
}

void PrintDistancekNodeP(TNode *start, int k) {

	if (start == NULL || k < 0) return;

	if (start->parent != NULL) {
        PrintAbove(start, k);
	}
    PrintDown(start, k);

}

//The binary tree does not have parent link.

/*

solution:

*/

struct Node {
    int val;
    Node* plft;
    Node* prgt;

	Node(int v) : val(v), plft(NULL), prgt(NULL) {}
};

//need finish this version

int main() {

	/*
	Node *root = new Node(1);
	root->plft = new Node(2);
	root->prgt = new Node(3);
	root->plft->plft = new Node(4);
	root->plft->prgt = new Node(5);
	root->prgt->plft = new Node(6);
	root->prgt->prgt = new Node(7);
	Node *start = root->prgt->prgt;
	*/

	TNode *root1 = new TNode(1);
	root1->plft = new TNode(2);
	root1->prgt = new TNode(3);
	root1->plft->parent = root1;
	root1->prgt->parent = root1;

	root1->plft->plft = new TNode(4);
	root1->plft->plft->parent = root1->plft;
	root1->plft->prgt = new TNode(5);
	root1->plft->prgt->parent = root1->plft;
	root1->prgt->plft = new TNode(6);
	root1->prgt->prgt = new TNode(7);
	root1->prgt->plft->parent = root1->prgt;
	root1->prgt->prgt->parent = root1->prgt;

	TNode *start1 = root1->prgt->prgt;
	TNode *start2 = root1->prgt;

	PrintDistancekNodeP(root1, 1);
	cout<<endl;
	PrintDistancekNodeP(root1, 2);
	cout<<endl;
	PrintDistancekNodeP(start1, 1);
	cout<<endl;
	PrintDistancekNodeP(start1, 2);
	cout<<endl;
	PrintDistancekNodeP(start1, 3);
	cout<<endl;
	PrintDistancekNodeP(start2, 1);
	cout<<endl;
	PrintDistancekNodeP(start2, 2);
	cout<<endl;
	PrintDistancekNodeP(start2, 3);
	cout<<endl;
	return 0;

}


text:
/**
 * Model usage example - Interfaces
 *
 * This example demonstrates model creation using 1 concrete class and 2 interfaces.
 * The interfaces provides the structure for both the static and instance shape, the concrete class
 * provides implementation and it is exposed.
 *
 * Pros:
 *   - Design fits I in SOLID
 *   - single concrete implementation
 *   - Exporting a native class and not const + type
 *   - Should support angular DI
 *
 * Cons:
 *   - Double the work, a lot of boilerplate
 *   - Writing interfaces for instance & static, cumbersome
 *   - Members defined ONLY IN the concrete implementation (i.e. not part of the interface) will
 *     appear as member on the return type of INSTANCE methods that return "this" but WILL NOT
 *     appear on the return type of STATIC methods that return "this" - CONFUSING.
 */

import { Identity, ExtendAction, ExecuteContext, Constructor, ARInterface } from '@tdm/data';
import { ActiveRecord, HttpResource, HttpActionOptions, HttpAction, HttpActionMethodType } from '@tdm/ngx-http-client';
import './init-tdm';

export interface IUserInterfaceStatic extends Constructor<IUserInterface> {
  num: number;
  // find: (id: 'CatA' | 'CatB', options?: HttpActionOptions) => ActiveRecord<IUserInterface>;
}

export interface IUserInterface extends ARInterface<IUserInterface, HttpActionOptions> {
  id: number;
  username: string;

  method(value: number): string;
  getSomething: (fromSomeWhere: string, options?: HttpActionOptions) => this;
}

@HttpResource({
  endpoint: '/path'
})
export class UsersInterface extends ActiveRecord<IUserInterface, IUserInterfaceStatic>() implements IUserInterface {
  @Identity()
  id: number;
  username: string;
  static num: number;

  method(value: number): string {
    return '';
  }

  @HttpAction({
    method: HttpActionMethodType.Delete,
    endpoint: '/path/:somewhere',
    pre(ctx: ExecuteContext<any>, fromSomeWhere: string, options?: HttpActionOptions) {
      if (!options) {
        options = {} as any;
      }
      if (!options.urlParams) {
        options.urlParams = {};
      }
      options.urlParams.somewhere = fromSomeWhere;
      return options;
    }
  })
  getSomething: (fromSomeWhere: string, options?: HttpActionOptions) => this;

  // @ExtendAction({
  //   pre: (ctx: ExecuteContext<any>, category: 'CatA' | 'CatB', options?: HttpActionOptions) => {
  //     return options;
  //   }
  // })
  // static find: (id: 'CatA' | 'CatB', options?: HttpActionOptions) => ActiveRecord<UsersInterface>;
}

UsersInterface.findById(2).username;
UsersInterface.num;

/**
 * @tssert keep property type information.
 * @tsError 2352
 * @loc 1
 */
UsersInterface.findById(2).username as number;

/**
 * @tssert keep property type information.
 * @tsError 2352
 * @loc 1
 */
UsersInterface.num as string;

/**
 * @tssert not cast to any
 * @tsError 2551
 * @loc 28
 */
UsersInterface.findById(2).usernam23e;

new UsersInterface().$get().parent.username;

const user: UsersInterface = new UsersInterface();

user.$get().parent.username;

/**
 * @tssert not cast to any
 * @tsError 2339
 * @loc 20
 */
user.$get().parent.abcd;

/**
 * Keep type information in promise chain - property
 */
user.$rc.next().then( u => u.id );

/**
 * Keep type information in promise chain - non existing property
 * @tssert
 * @tsError 2339
 * @loc 30
 */
user.$rc.next().then( u => u.f34 );

/**
 * Keep type information in promise chain - method
 */
user.$rc.next().then( u => u.method(15) );

/**
 * @tssert
 * @tsError 2345
 * @loc 37
 */
user.$rc.next().then( u => u.method('dd') );

/**
 * Keep type information in promise chain - active record method
 * @tssert
 * @tsType Promise<ResourceControl<IUserInterface>>
 * @loc 16
 */
user.$rc.next().then( u => u.$remove() );

/**
 * Keep type information in promise chain - active record method
 * @tssert
 * @tsType Promise<TDMModel<UsersInterface & IUserInterface> & UsersInterface & IUserInterface>
 * @loc 37
 */
user.getSomething('value').$rc.next();

UsersInterface.query().$rc.next().then(coll => coll.push );

/**
 * Keep type information in promise chain - collection - non existing property
 * @tssert
 * @tsError 2339
 * @loc 53
 */
UsersInterface.query().$rc.next().then(coll => coll.sdfd );

UsersInterface.query().query().findById(15);
UsersInterface.query().query();

/**
 * @tssert
 * @tsError 2554
 * @loc 1
 */
UsersInterface.query().find();

/**
 * @tssert
 * @tsError 2322
 * @loc 2:23
 */
UsersInterface.findOne(null).$rc.next()
  .then( u => { const x: UsersInterface = ''; });

/**
 * @tssert
 * @tsError 2339
 * @loc 24
 */
UsersInterface.query().erer();

UsersInterface.findAll().findOne(null);
UsersInterface.findOne(null)
  .$remove()
  .parent
  .$get()
  .next()
  .then( u => u.$remove().parent.$get() )
  .then( u => u.parent.method(15));

/**
 * @tssert
 * @tsError 2345
 * @loc 7:31
 */
UsersInterface.findOne(null)
  .$remove()
  .parent
  .$get()
  .next()
  .then( u => u.$remove().parent.$get() )
  .then( u => u.parent.method('XX'));

// UsersInterface.find('CatA');
UsersInterface.find({ urlParams: { } });

/**
 * @tssert
 * @tsError 2353
 * @loc 23
 */
UsersInterface.find({ urlParams123: { } });

/**
 * @tssert extend action
 * @tsError 2559
 * @tsErrorMsg Type '"dfdf"' has no properties in common with type 'HttpActionOptions'.
 * @loc 21
 */
UsersInterface.find('dfdf');

// inheritance

@HttpResource({
  endpoint: '/ext-path'
})
export class UsersInterfaceExt extends UsersInterface {
  valueOnDerived: number;

  extMmethod(value: number): string {
    return '';
  }

}

UsersInterfaceExt.findById(2).username;

/**
 * This shows the limitation of not being able to reflect instance members of classes deriving from ActiveRecord<Base...>
 * when the type is returned from a static member.
 *
 * @tssert keep property type information.
 * @tsError 2339
 * @tsErrorMsg Property 'valueOnDerived' does not exist on type 'IUserInterface & TDMModel<IUserInterface> & HttpActiveRecord'.
 * @loc 31
 */
UsersInterfaceExt.findById(2).valueOnDerived;

UsersInterfaceExt.num;

/**
 * @tssert keep property type information.
 * @tsError 2352
 * @loc 1
 */
UsersInterfaceExt.findById(2).username as number;

/**
 * @tssert keep property type information.
 * @tsError 2352
 * @loc 1
 */
UsersInterfaceExt.num as string;

/**
 * @tssert not cast to any
 * @tsError 2551
 * @loc 31
 */
UsersInterfaceExt.findById(2).usernam23e;

new UsersInterfaceExt().$get().parent.username;

const userExt: UsersInterfaceExt = new UsersInterfaceExt();

userExt.$get().parent.username;

/**
 * @tssert not cast to any
 * @tsError 2339
 * @loc 23
 */
userExt.$get().parent.abcd;

/**
 * Keep type information in promise chain - property
 */
userExt.$rc.next().then( u => u.id );

/**
 * Keep type information in promise chain - non existing property
 * @tssert
 * @tsError 2339
 * @loc 33
 */
userExt.$rc.next().then( u => u.f34 );

/**
 * Keep type information in promise chain - method
 */
userExt.$rc.next().then( u => u.method(15) );

/**
 * @tssert
 * @tsError 2345
 * @loc 40
 */
userExt.$rc.next().then( u => u.method('dd') );

/**
 * Keep type information in promise chain - active record method
 * @tssert
 * @tsType Promise<ResourceControl<IUserInterface>>
 * @loc 19
 */
userExt.$rc.next().then( u => u.$remove() );

/**
 * Keep type information in promise chain - active record method
 * @tssert
 * @tsType Promise<TDMModel<UsersInterfaceExt & IUserInterface> & UsersInterfaceExt & IUserInterface>
 * @loc 40
 */
userExt.getSomething('value').$rc.next();

UsersInterfaceExt.query().$rc.next().then(coll => coll.push );

/**
 * Keep type information in promise chain - collection - non existing property
 * @tssert
 * @tsError 2339
 * @loc 56
 */
UsersInterfaceExt.query().$rc.next().then(coll => coll.sdfd );

UsersInterfaceExt.query().query().findById(15);
UsersInterfaceExt.query().query();

/**
 * @tssert
 * @tsError 2554
 * @loc 1
 */
UsersInterfaceExt.query().find();

/**
 * @tssert
 * @tsError 2322
 * @loc 2:23
 */
UsersInterfaceExt.findOne(null).$rc.next()
  .then( u => { const x: UsersInterfaceExt = ''; });

/**
 * @tssert
 * @tsError 2339
 * @loc 27
 */
UsersInterfaceExt.query().erer();

UsersInterfaceExt.findAll().findOne(null);
UsersInterfaceExt.findOne(null)
  .$remove()
  .parent
  .$get()
  .next()
  .then( u => u.$remove().parent.$get() )
  .then( u => u.parent.method(15));

/**
 * @tssert
 * @tsError 2345
 * @loc 7:31
 */
UsersInterfaceExt.findOne(null)
  .$remove()
  .parent
  .$get()
  .next()
  .then( u => u.$remove().parent.$get() )
  .then( u => u.parent.method('XX'));

// UsersInterfaceExt.find('CatA');
UsersInterfaceExt.find({ urlParams: { } });

/**
 * @tssert
 * @tsError 2353
 * @loc 26
 */
UsersInterfaceExt.find({ urlParams123: { } });

/**
 * @tssert extend action
 * @tsError 2559
 * @tsErrorMsg Type '"dfdf"' has no properties in common with type 'HttpActionOptions'.
 * @loc 24
 */
UsersInterfaceExt.find('dfdf');


text:
package org.apache.shardingsphere.proxy.backend.text.distsql.ral.common.updatable;

import org.apache.shardingsphere.distsql.parser.statement.ral.common.updatable.AlterTransactionRuleStatement;
import org.apache.shardingsphere.infra.config.RuleConfiguration;
import org.apache.shardingsphere.infra.metadata.rule.ShardingSphereRuleMetaData;
import org.apache.shardingsphere.mode.manager.ContextManager;
import org.apache.shardingsphere.mode.metadata.MetaDataContexts;
import org.apache.shardingsphere.mode.metadata.persist.MetaDataPersistService;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import org.apache.shardingsphere.proxy.backend.text.distsql.ral.UpdatableRALBackendHandler;
import org.apache.shardingsphere.transaction.config.TransactionRuleConfiguration;

import java.util.Collection;
import java.util.Optional;

/**
 * Alter transaction rule statement handler.
 */
public final class AlterTransactionRuleHandler extends UpdatableRALBackendHandler<AlterTransactionRuleStatement, AlterTrafficRuleHandler> {

    @Override
    protected void update(final ContextManager contextManager, final AlterTransactionRuleStatement sqlStatement) {
        updateTransactionRule();
    }

    private void updateTransactionRule() {
        MetaDataContexts metaDataContexts = ProxyContext.getInstance().getContextManager().getMetaDataContexts();
        ShardingSphereRuleMetaData globalRuleMetaData = metaDataContexts.getGlobalRuleMetaData();
        Collection<RuleConfiguration> globalRuleConfigurations = globalRuleMetaData.getConfigurations();
        globalRuleConfigurations.removeIf(each -> each instanceof TransactionRuleConfiguration);
        TransactionRuleConfiguration toBeAlteredRuleConfig = buildTransactionRuleConfiguration();
        globalRuleConfigurations.add(toBeAlteredRuleConfig);
        Optional<MetaDataPersistService> metaDataPersistService = metaDataContexts.getMetaDataPersistService();
        if (metaDataPersistService.isPresent() && null != metaDataPersistService.get().getGlobalRuleService()) {
            metaDataPersistService.get().getGlobalRuleService().persist(globalRuleConfigurations, true);
        }
    }

    private TransactionRuleConfiguration buildTransactionRuleConfiguration() {
        return new TransactionRuleConfiguration(sqlStatement.getDefaultType(), sqlStatement.getProvider().getProviderType(), sqlStatement.getProvider().getProps());
    }
}


text:
package madgik.exareme.master.queryProcessor.graph;

import madgik.exareme.utils.statistics.Zipf;

import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.util.Properties;

/**
 * @author Herald Kllapi <br>
 *         University of Athens /
 *         Department of Informatics and Telecommunications.
 * @since 1.0
 */
public class RandomParameters implements Serializable {
    public double z;
    public double operatorType;
    public double[] runTime = null;
    public double[] cpuUtil = null;
    public int[] memory = null;
    public double[] dataout = null;
    public Zipf runTimeDist = null;
    public Zipf cpuUtilDist = null;
    public Zipf memoryDist = null;
    public Zipf dataoutDist = null;

    public RandomParameters(double z, double operatorType, double[] runTime, double[] cpuUtil,
        int[] memory, double[] dataout) {
        this.z = z;
        this.operatorType = operatorType;

        this.runTime = runTime;
        this.cpuUtil = cpuUtil;
        this.memory = memory;
        this.dataout = dataout;

        this.runTimeDist = new Zipf(this.runTime.length, z);
        this.cpuUtilDist = new Zipf(this.cpuUtil.length, z);
        this.memoryDist = new Zipf(this.memory.length, z);
        this.dataoutDist = new Zipf(this.dataout.length, z);
    }

    @SuppressWarnings("static-access") public static RandomParameters parseFile(String url)
        throws IOException {
        Properties properties = new Properties();
        properties.load(new URL(url).openStream());

        double z = Double.parseDouble(properties.getProperty("z"));
        double operatorType = Double.parseDouble(properties.getProperty("type"));

        String[] runtimeStr = properties.getProperty("time").split(",");
        double[] runTime = new double[runtimeStr.length];
        for (int i = 0; i < runTime.length; i++) {
            runTime[i] = Double.parseDouble(runtimeStr[i]);
        }

        String[] cpuUtilStr = properties.getProperty("cpu").split(",");
        double[] cpuUtil = new double[cpuUtilStr.length];
        for (int i = 0; i < cpuUtil.length; i++) {
            cpuUtil[i] = Double.parseDouble(cpuUtilStr[i]);
        }

        String[] memoryStr = properties.getProperty("mem").split(",");
        int[] memory = new int[memoryStr.length];
        for (int i = 0; i < memory.length; i++) {
            memory[i] = Integer.parseInt(memoryStr[i]);
        }

        String[] dataoutStr = properties.getProperty("data").split(",");
        double[] dataout = new double[dataoutStr.length];
        for (int i = 0; i < dataout.length; i++) {
            dataout[i] = Double.parseDouble(dataoutStr[i]);
        }

        RandomParameters parameters =
            new RandomParameters(z, operatorType, runTime, cpuUtil, memory, dataout);

        return parameters;
    }

    public void resetRandom(long seed) {
        this.runTimeDist = new Zipf(this.runTime.length, z, seed);
        this.cpuUtilDist = new Zipf(this.cpuUtil.length, z, seed);
        this.memoryDist = new Zipf(this.memory.length, z, seed);
        this.dataoutDist = new Zipf(this.dataout.length, z, seed);
    }
}


text:
Spree::CreditCard.class_eval do
  attr_accessor :name_on_card, :openpay_response

  unless Rails::VERSION::MAJOR == 4
    attr_accessible :name_on_card, :installments_number, :openpay_response
  end

  def name?
    !!name_on_card | (first_name? & last_name?)
  end

  def name
    name_on_card || "#{first_name} #{last_name}"
  end
end


text:
import { useSelector, useDispatch } from 'react-redux'
import Photo from "./Photo";

const PhotoGrid = () => {

  const posts = useSelector((state) => state.posts)
  const comments = useSelector((state) => state.comments)

  return (
    <div className="photo-grid">
      {
        posts.map((post, i) => <Photo key={i} i={i} post={post} comments={comments} />)
      }
    </div>
  )
}

export default PhotoGrid


text:
package com.buynsell.utils;

import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Mailer {
	String from = null;
	String host = null;

	public Mailer(String from, String host) {
		if (from == null)
			this.from = "aneesh@labs.ecommit.com";
		if (host == null)
			this.host = "mail.labs.ecommit.com";
	}

	public void sendMail(String to, String subject, String contentBeforeImage, String image, String contentAfterImage) {
		Properties props = new Properties();
		props.put("mail.smtp.host", host);
		Session session = Session.getDefaultInstance(props, null);
		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(from));
			InternetAddress[] address = { new InternetAddress(to) };
			msg.setRecipients(Message.RecipientType.TO, address);
			msg.setSubject(subject);

			MimeMultipart mp = new MimeMultipart();
			mp.setSubType("related");

			MimeBodyPart mbp1 = new MimeBodyPart();
			String html = contentBeforeImage + "<IMG SRC=cid:23abc@pc27>" + contentAfterImage;
			mbp1.setContent(html, "text/html");

			MimeBodyPart mbp2 = new MimeBodyPart();
			FileDataSource fds = new FileDataSource(image);
			mbp2.setFileName(fds.getName());
			mbp2.setText("com.buynsell Mailer Reminds you !");
			mbp2.setDataHandler(new DataHandler(fds));
			mbp2.setHeader("Content-ID", "<23abc@pc27>");

			mp.addBodyPart(mbp1);
			mp.addBodyPart(mbp2);
			msg.setContent(mp);

			msg.setSentDate(new Date());
			Transport.send(msg);
			System.out.println(mp.getCount());
			System.out.println("\nMail was sent successfully.");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


text:
import { ActionReducer, State } from '@ngrx/store';
import * as WorkItemLinkActions from './../actions/work-item-link.actions';
import { initialState, WorkItemLinkState } from './../states/work-item-link.state';

export type Action = WorkItemLinkActions.All;

export const WorkItemLinkReducer: ActionReducer<WorkItemLinkState> =
  (state = initialState, action: Action) => {
    switch (action.type) {
      case WorkItemLinkActions.GET_SUCCESS: {
        return action.payload;
      }

      case WorkItemLinkActions.GET_ERROR: {
        return state;
      }

      case WorkItemLinkActions.ADD_SUCCESS: {
        return [action.payload, ...state];
      }

      case WorkItemLinkActions.ADD_ERROR: {
        return [...state];
      }

      case WorkItemLinkActions.DELETE_SUCCESS: {
        let linkIndex = state.findIndex(l => l.id === action.payload.id);
        if (linkIndex > -1) {
          state.splice(linkIndex, 1);
        }
        return [...state];
      }

      case WorkItemLinkActions.DELETE_ERROR: {
        return [...state];
      }

      case WorkItemLinkActions.RESET_LINKS: {
        return null;
      }

      case WorkItemLinkActions.TRIVIALIZE_ALL: {
        if (state) {
          return state.map(s => s.newlyAdded ? {...s, ...{newlyAdded: false}} : s);
        } else {
          return null;
        }
      }

      default: {
        return state;
      }
    }
  };


text:
import { list as List, textbox } from 'blessed';
import { stringToPrimitive } from '../runtime/helpers';
import SchemaParser from '../runtime/schemaParser';
import { screen } from '../widgets/';

export function arrayOfBooleanAndPrimitiveField(parser: SchemaParser, key: string): void {

    const list = List({
        border: 'line',
        height: '50%',
        items: [
            'false',
            'true',
            'unset',
        ],
        keys: true,
        label: key,
        left: 'center',
        parent: screen,
        shrink: true,
        style: {
            selected: {
                bg: 'green',
                bold: true,
                fg: 'black',
            },
        },
        tags: true,
        vi: true,
        width: '50%',
    });

    const input = textbox({
        border: 'line',
        height: 'shrink',
        label: 'key',
        left: 'center',
        parent: screen,
        shrink: true,
        style: {
            focus: {
                bg: 'green',
                fg: 'black',
            },
        },
        top: '40%',
        width: '50%',
    });

    list.once('select', value => {
        const selection = value.getText();

        switch (selection) {
            case 'true':
                input.readInput();
                screen.emit('repaint');
                return;
            case 'false':
                parser.setConfigValue(key, [false]);
                break;
            default:
                parser.setConfigValue(key);
                break;
        }

        screen.remove(list);
        screen.remove(input);

        list.free();
        input.free();

        screen.emit('repaint');
    });

    input.once('submit', value => {
        parser.setConfigValue(key, value ? stringToPrimitive(value) : undefined);

        screen.remove(list);
        screen.remove(input);

        list.free();
        input.free();

        screen.emit('repaint');
    });

    input.onceKey('escape', () => input.emit('submit'));

    list.focus();
    screen.render();
}


text:
<!doctype html>

<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,400italic,600,600italic,700,700italic,300italic" rel="stylesheet" type="text/css">
<meta charset="utf-8">
<title>Mapping Syrian Refugee Border Crossings | Ahmed</title>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="animate.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="js/woothemes-FlexSlider-06b12f8/flexslider.css" type="text/css" media="screen">
<link rel="stylesheet" href="js/prettyPhoto_3.1.5/prettyPhoto.css" type="text/css" media="screen">
<link href="style.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="fonts/font-awesome/css/font-awesome.min.css" media="screen">

 Meghan Kelly University of Kansas - Geography   menu

Home

 Stories

Adiba

Ahmed

Eva

Hannah

Mohammed

Fateh and Baraq

Ahmed

my heart and soul remain attached

Home

Ahmed

Ahmed is a Syrian

physician specially trained in pathology. He taught at the Aleppo School of Medicine before the revolution began. His wife is also a physician, and together they have a young daughter. Ahmad played an important role as a physician throughout the revolution, often working for one or both sides of the conflict. He currently works for a US-based NGO in Turkey. Ahmad provided the written narrative of his story through email. His story centers on safety, family, mobility and his experiences as a physician during the crisis.

Personal Story

 Copyright ©2015 all rights reserved, Meghan Kelly.

  hmkelly22@wisc.edu


text:
'use strict';

/**
 * @class
 * Initializes a new instance of the AdlsRemoteException class.
 * @constructor
 * Data Lake Store filesystem exception based on the WebHDFS definition for
 * RemoteExceptions.
 *
 * @member {string} [javaClassName] the full class package name for the
 * exception thrown, such as 'java.lang.IllegalArgumentException'.
 *
 * @member {string} [message] the message associated with the exception that
 * was thrown, such as 'Invalid value for webhdfs parameter "permission":...'.
 *
 * @member {string} exception Polymorhpic Discriminator
 *
 */
function AdlsRemoteException() {
}

/**
 * Defines the metadata of AdlsRemoteException
 *
 * @returns {object} metadata of AdlsRemoteException
 *
 */
AdlsRemoteException.prototype.mapper = function () {
  return {
    required: false,
    serializedName: 'AdlsRemoteException',
    type: {
      name: 'Composite',
      polymorphicDiscriminator: 'exception',
      uberParent: 'AdlsRemoteException',
      className: 'AdlsRemoteException',
      modelProperties: {
        javaClassName: {
          required: false,
          readOnly: true,
          serializedName: 'javaClassName',
          type: {
            name: 'String'
          }
        },
        message: {
          required: false,
          readOnly: true,
          serializedName: 'message',
          type: {
            name: 'String'
          }
        },
        exception: {
          required: true,
          serializedName: 'exception',
          type: {
            name: 'String'
          }
        }
      }
    }
  };
};

module.exports = AdlsRemoteException;


text:
'use strict';

var util = require('util');

var models = require('./index');

/**
 * @class
 * Initializes a new instance of the StringWrapper class.
 * @constructor
 */
function StringWrapper() { }

/**
 * Validate the payload against the StringWrapper schema
 *
 * @param {JSON} payload
 *
 */
StringWrapper.prototype.validate = function (payload) {
  if (!payload) {
    throw new Error('StringWrapper cannot be null.');
  }
  if (payload['field'] !== null && payload['field'] !== undefined && typeof payload['field'] !== 'string') {
    throw new Error('payload[\'field\'] must be of type string.');
  }

  if (payload['empty'] !== null && payload['empty'] !== undefined && typeof payload['empty'] !== 'string') {
    throw new Error('payload[\'empty\'] must be of type string.');
  }

  if (payload['null'] !== null && payload['null'] !== undefined && typeof payload['null'] !== 'string') {
    throw new Error('payload[\'null\'] must be of type string.');
  }

};

/**
 * Deserialize the instance to StringWrapper schema
 *
 * @param {JSON} instance
 *
 */
StringWrapper.prototype.deserialize = function (instance) {
  return instance;
};

module.exports = new StringWrapper();


text:
from datetime import datetime
import logging
import os

import webapp2

from google.appengine.ext.webapp import template

from livecount import counter
from livecount.counter import LivecountCounter
from livecount.counter import PeriodType

class CounterHandler(webapp2.RequestHandler):
    """
    Handles displaying the values of the counters
    and requests to increment/decrement counters.
    """

    def get(self):
        namespace = self.request.get('namespace')
        period_type = self.request.get('period_type')
        period_types = self.request.get('period_types').replace(" ", "")
        period = self.request.get('period')
        name = self.request.get('counter_name')
        delta = self.request.get('delta')
        fetch_limit = self.request.get('fetch_limit')

        if not namespace:
            namespace = "default"
        if not period_type:
            period_type = PeriodType.DAY
        if not period_types:
            period_types = PeriodType.DAY + "," + PeriodType.WEEK
        if not period:
            period = str(datetime.now()).split(".")[0]
        if not delta:
            delta = 1
        if not fetch_limit:
            fetch_limit = "20"

        modified_counter = None
        if name:
            full_key = LivecountCounter.KeyName(namespace, period_type, period, name)
            modified_counter = LivecountCounter.get_by_key_name(full_key)

        counter_entities_query = LivecountCounter.all().order('-count')
        if namespace:
            counter_entities_query.filter("namespace = ", namespace)
        if period_type:
            counter_entities_query.filter("period_type = ", period_type)
        scoped_period = PeriodType.find_scope(period_type, period)
        if period:
            counter_entities_query.filter("period = ", scoped_period)
        counter_entities = counter_entities_query.fetch(int(fetch_limit))
        logging.info("counter_entities: " + str(counter_entities))

        stats = counter.GetMemcacheStats()

        template_values = {
                           'namespace': namespace,
                           'period_type': period_type,
                           'period_types': period_types,
                           'period': period,
                           'counter_name': name,
                           'delta': delta,
                           'modified_counter': modified_counter,
                           'counters': counter_entities,
                           'stats': stats
                           }
        logging.info("template_values: " + str(template_values))
        template_file = os.path.join(os.path.dirname(__file__), 'counter_admin.html')
        self.response.out.write(template.render(template_file, template_values))

    def post(self):
        namespace = self.request.get('namespace')
        period_type = self.request.get('period_type')
        period_types = self.request.get('period_types').replace(" ", "")
        period = self.request.get('period')
        name = self.request.get('counter_name')
        delta = self.request.get('delta')
        type = self.request.get('type')

        if type == "Increment Counter":
            counter.load_and_increment_counter(name=name, period=period, period_types=period_types.split(","), namespace=namespace, delta=long(delta))
        elif type == "Decrement Counter":
            counter.load_and_decrement_counter(name=name, period=period, period_types=period_types.split(","), namespace=namespace, delta=long(delta))

        logging.info("Redirecting to: /livecount/counter_admin?namespace=" + namespace + "&period_type=" + period_type + "&period_types=" + period_types + "&period=" + period + "&counter_name=" + name + "&delta=" + delta)
        self.redirect("/livecount/counter_admin?namespace=" + namespace + "&period_type=" + period_type + "&period_types=" + period_types + "&period=" + period + "&counter_name=" + name + "&delta=" + delta)

application = webapp2.WSGIApplication([
         ('/livecount/counter_admin', CounterHandler),
    ], debug=False)


text:
@class CEDateIndexedTable;

@interface CEDateColumn ()

@property (nonatomic, weak, setter=_setTable:) CEDateIndexedTable *_table;

@end