text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set sw=2 ts=8 et tw=80 :
 */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsISupports.h"
#include "mozilla/net/ChannelEventQueue.h"

namespace mozilla {
namespace net {

void
ChannelEventQueue::FlushQueue()
{
  // Events flushed could include destruction of channel (and our own
  // destructor) unless we make sure its refcount doesn't drop to 0 while this
  // method is running.
  nsCOMPtr<nsISupports> kungFuDeathGrip(mOwner);

  // Prevent flushed events from flushing the queue recursively
  mFlushing = true;

  uint32_t i;
  for (i = 0; i < mEventQueue.Length(); i++) {
    mEventQueue[i]->Run();
    if (mSuspended)
      break;
  }

  // We will always want to remove at least one finished callback.
  if (i < mEventQueue.Length())
    i++;

  // It is possible for new callbacks to be enqueued as we are
  // flushing the queue, so the queue must not be cleared until
  // all callbacks have run.
  mEventQueue.RemoveElementsAt(0, i);

  mFlushing = false;
}

}
}


text:
class CreateChangesAgain < ActiveRecord::Migration
  def change
    create_table :changes do |t|
      t.references :document, index: true
      t.jsonb :content
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Heptapleurum productum Dunn

### Remarks
null


text:
#include <aws/kinesisvideo/model/NotificationConfiguration.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace KinesisVideo
{
namespace Model
{

NotificationConfiguration::NotificationConfiguration() :
    m_status(ConfigurationStatus::NOT_SET),
    m_statusHasBeenSet(false),
    m_destinationConfigHasBeenSet(false)
{
}

NotificationConfiguration::NotificationConfiguration(JsonView jsonValue) :
    m_status(ConfigurationStatus::NOT_SET),
    m_statusHasBeenSet(false),
    m_destinationConfigHasBeenSet(false)
{
  *this = jsonValue;
}

NotificationConfiguration& NotificationConfiguration::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Status"))
  {
    m_status = ConfigurationStatusMapper::GetConfigurationStatusForName(jsonValue.GetString("Status"));

    m_statusHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DestinationConfig"))
  {
    m_destinationConfig = jsonValue.GetObject("DestinationConfig");

    m_destinationConfigHasBeenSet = true;
  }

  return *this;
}

JsonValue NotificationConfiguration::Jsonize() const
{
  JsonValue payload;

  if(m_statusHasBeenSet)
  {
   payload.WithString("Status", ConfigurationStatusMapper::GetNameForConfigurationStatus(m_status));
  }

  if(m_destinationConfigHasBeenSet)
  {
   payload.WithObject("DestinationConfig", m_destinationConfig.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace KinesisVideo
} // namespace Aws


text:
"use strict";

import * as vscode from "vscode";
import {GetRuleRange, varFirstChar} from "./helpers";

export class YaraReferenceProvider implements vscode.ReferenceProvider {
    public provideReferences(doc: vscode.TextDocument, pos: vscode.Position): Thenable<vscode.Location[]> {
        return new Promise((resolve, reject) => {
            const fileUri: vscode.Uri = vscode.Uri.file(doc.fileName);
            const range: vscode.Range = doc.getWordRangeAtPosition(pos);
            const lines: string[] = doc.getText().split("\n");
            const references: vscode.Location[] = new Array<vscode.Location>();
            const symbol: string = doc.getText(range);
            // console.log(`Providing references for symbol '${symbol}'`);
            const possibleVarStart: vscode.Position = new vscode.Position(range.start.line, range.start.character - 1);
            const possibleVarRange: vscode.Range = new vscode.Range(possibleVarStart, range.end);
            const possibleVar: string = doc.getText(possibleVarRange);
            if (varFirstChar.has(possibleVar.charAt(0))) {
                let varRegexp: string;
                let startLine: number;
                let endLine: number;
                // console.log(`Identified symbol as a variable: ${symbol}`);
                const possibleWildcardEnd: vscode.Position = new vscode.Position(range.end.line, range.end.character + 1);
                const possibleWildcardRange: vscode.Range = new vscode.Range(possibleVarStart, possibleWildcardEnd);
                const possibleWildcard: string = doc.getText(possibleWildcardRange);
                if (possibleWildcard.slice(-1) == "*") {
                    // treat like a wildcard and search only the local rule
                    varRegexp = `[$#@!]${symbol}[a-zA-Z0-9_]+`;
                    const ruleRange = GetRuleRange(lines, pos);
                    startLine = ruleRange.start.line;
                    endLine = ruleRange.end.line;
                }
                else {
                    // treat like a normal variable reference and search the whole document
                    varRegexp = `[$#@!](${symbol}[^a-zA-Z0-9_]|${symbol}$)`;
                    startLine = 0;
                    endLine = lines.length;
                }
                for (let lineNo = startLine; lineNo < endLine; lineNo++) {
                    const character: number = lines[lineNo].search(varRegexp);
                    if (character != -1) {
                        // console.log(`Found ${symbol} on line ${lineNo} at character ${character}`);
                        // have to readjust the character index
                        const refPosition: vscode.Position = new vscode.Position(lineNo, character + 1);
                        references.push(new vscode.Location(fileUri, refPosition));
                    }

                }
            }
            else {
                let lineNo = 0;
                lines.forEach(line => {
                    const character: number = line.indexOf(symbol);
                    if (character != -1) {
                        // console.log(`Found ${symbol} on line ${lineNo} at character ${character}`);
                        const refPosition: vscode.Position = new vscode.Position(lineNo, character);
                        references.push(new vscode.Location(fileUri, refPosition));
                    }
                    lineNo++;
                });
            }
            if (references != null) {
                resolve(references);
            }
            else {
                reject();
            }
        });
    }
}


text:
testSpecular,

#elif TEXTURE_EXPOSE == TEXTURE_BUILDER_NAME

buildSpecularTest,

#elif TEXTURE_EXPOSE == TEXTURE_FILE

__FILE__,

#elif TEXTURE_EXPOSE == TEXTURE_BUILDER_BODY

//
// Test de speculaire
//
void buildSpecularTest()
{
  Channel t;
  t.Fade(0);

  Channel grid;
  grid.Fade(0); grid *= 8.f; grid.Mod();
  Channel tmp = grid;
  tmp.Rotate90();
  grid.MaximizeTo(tmp);
  grid.ClampAndScale(0.4f, 0.45f);

  t *= grid;

  queueTextureA(testSpecular, t,
		GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR,
		true, GL_REPEAT, false);
}

#endif // TEXTURE_EXPOSE


text:
import {Component, Output, EventEmitter, Input} from '@angular/core';
import {iButton} from "../iButton";

@Component({
  selector: 'li[selection-list]',
  templateUrl: './selection-list.component.html',
  styleUrls: ['./selection-list.component.css']
})
export class SelectionListComponent extends iButton {

}


text:
def differentSymbolsNaive(s):
    return len(set(s))


text:
namespace nuPickers.Caching
{
    using System;
    using System.Collections.Concurrent;
    using System.Linq;
    using System.Runtime.Caching;

    internal sealed class Cache
    {
        /// <summary>
        /// Singleton instance of the <see cref="Cache"/> class
        /// </summary>
        private static readonly Cache cache = new Cache();

        /// <summary>
        /// Internal instance of the <see cref="MemoryCache"/> class
        /// </summary>
        private MemoryCache memoryCache;

        /// <summary>
        /// Locker collection of all cache keys currently having their 'expensive functions' evaluated
        /// string = cacheKey, object = used as a locking object
        /// </summary>
        private ConcurrentDictionary<string, object> cacheKeysBeingHandled;

        static Cache()
        {
        }

        /// <summary>
        /// Private constructor
        /// </summary>
        private Cache()
        {
            this.memoryCache = new MemoryCache("nuPickers");

            this.cacheKeysBeingHandled = new ConcurrentDictionary<string, object>();
        }

        /// <summary>
        /// Get the instance of this cache
        /// </summary>
        internal static Cache Instance
        {
            get
            {
                return cache;
            }
        }

        /// <summary>
        /// Queries key in cache for object of type T
        /// </summary>
        /// <typeparam name="T">type of object expected</typeparam>
        /// <param name="cacheKey">key to the cache item to get</param>
        /// <returns>an object from cache of type T, else default(T)</returns>
        internal T Get<T>(string cacheKey)
        {
            bool found;

            return this.Get<T>(cacheKey, out found);
        }

        /// <summary>
        /// Queries key in cache for object of type T
        /// </summary>
        /// <typeparam name="T">type of object expected</typeparam>
        /// <param name="cacheKey">key to the cache item to get</param>
        /// <param name="found">output parameter, indicates whether the return value was found in the cache</param>
        /// <returns>an object from cache of type T, else default(T)</returns>
        internal T Get<T>(string cacheKey, out bool found)
        {
            object obj = this.memoryCache[cacheKey];

            if (obj is T)
            {
                found = true;
                return (T)obj;
            }

            found = false;
            return default(T);
        }

        /// <summary>
        /// Queries key in cache for object of type T, otherwise executes expensiveFunc and ensures cache is set
        /// </summary>
        /// <typeparam name="T">type of object expected</typeparam>
        /// <param name="cacheKey">key to the cache item to get (or set if not found)</param>
        /// <param name="expensiveFunc">function to execute if cache item not found</param>
        /// <param name="timeout">(optional) number of seconds before cache value should time out, default 0 = no timeout</param>
        /// <returns>an object from cache of type T, else the result of the expensiveFunc</returns>
        internal T GetSet<T>(string cacheKey, Func<T> expensiveFunc, int timeout = 0)
        {
            bool found;
            T cachedObject = this.Get<T>(cacheKey, out found);

            if (!found)
            {
                this.cacheKeysBeingHandled.TryAdd(cacheKey, new object()); // object used as a locker

                lock (this.cacheKeysBeingHandled[cacheKey])
                {
                    // re-check to see if another thread beat us to setting this value
                    cachedObject = this.Get<T>(cacheKey, out found);
                    if (!found)
                    {
                        cachedObject = expensiveFunc();

                        this.Set(cacheKey, cachedObject, timeout);
                    }
                }

                object obj;
                this.cacheKeysBeingHandled.TryRemove(cacheKey, out obj);
            }

            return cachedObject;
        }

        /// <summary>
        /// Populate the cache key with the supplied object
        /// </summary>
        /// <param name="cacheKey">key for the cache item to set</param>
        /// <param name="objectToCache">object to put into the cache item</param>
        /// <param name="timeout">(optional) number of seconds before cache value should time out, default 0 = no timeout</param>
        internal void Set(string cacheKey, object objectToCache, int timeout = 0)
        {
            if (objectToCache != null)
            {
                if (timeout > 0)
                {
                    this.memoryCache.Set(
                        cacheKey,
                        objectToCache,
                        new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.AddSeconds(timeout) });
                }
                else
                {
                    this.memoryCache[cacheKey] = objectToCache;
                }
            }
        }

        /// <summary>
        /// Remove an item from cache
        /// </summary>
        /// <param name="cacheKey">the key to the item to remove</param>
        internal void Remove(string cacheKey)
        {
            this.memoryCache.Remove(cacheKey);
        }

        /// <summary>
        /// Remove all items from cache for which the lambda returns true
        /// </summary>
        /// <param name="lambda">function to test a string cache key, and return true if it should be removed from cache</param>
        internal void Remove(Func<string, bool> lambda)
        {
            foreach (string key in this.memoryCache.Select(x => x.Key))
            {
                if (lambda(key))
                {
                    this.memoryCache.Remove(key);
                }
            }
        }
    }
}


text:
import { ENV } from 'ember-environment';
import { loc } from '../../../system/string';
import { setStrings, getStrings } from '../../../string_registry';
import { moduleFor, AbstractTestCase } from 'internal-test-helpers';

let oldString;

function test(assert, given, args, expected, description) {
  assert.equal(loc(given, args), expected, description);
  if (ENV.EXTEND_PROTOTYPES.String) {
    assert.deepEqual(given.loc(...args), expected, description);
  }
}

moduleFor(
  'EmberStringUtils.loc',
  class extends AbstractTestCase {
    beforeEach() {
      oldString = getStrings();
      setStrings({
        '_Hello World': 'Bonjour le monde',
        '_Hello %@': 'Bonjour %@',
        '_Hello %@ %@': 'Bonjour %@ %@',
        '_Hello %@# %@#': 'Bonjour %@2 %@1',
      });
    }

    afterEach() {
      setStrings(oldString);
    }

    ['@test String.prototype.loc is not available without EXTEND_PROTOTYPES'](assert) {
      if (!ENV.EXTEND_PROTOTYPES.String) {
        assert.ok('undefined' === typeof String.prototype.loc, 'String.prototype helper disabled');
      } else {
        assert.expect(0);
      }
    }

    ['@test String loc tests'](assert) {
      test(
        assert,
        '_Hello World',
        [],
        'Bonjour le monde',
        `loc('_Hello World') => 'Bonjour le monde'`
      );
      test(
        assert,
        '_Hello %@ %@',
        ['John', 'Doe'],
        'Bonjour John Doe',
        `loc('_Hello %@ %@', ['John', 'Doe']) => 'Bonjour John Doe'`
      );
      test(
        assert,
        '_Hello %@# %@#',
        ['John', 'Doe'],
        'Bonjour Doe John',
        `loc('_Hello %@# %@#', ['John', 'Doe']) => 'Bonjour Doe John'`
      );
      test(
        assert,
        '_Not In Strings',
        [],
        '_Not In Strings',
        `loc('_Not In Strings') => '_Not In Strings'`
      );
    }

    ['@test works with argument form'](assert) {
      assert.equal(loc('_Hello %@', 'John'), 'Bonjour John');
      assert.equal(loc('_Hello %@ %@', ['John'], 'Doe'), 'Bonjour [John] Doe');
    }
  }
);


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

// ==++==
//

//

//
// ==--==

/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX                                                                           XX
XX                          unordered_map<K,V,H,P,A>                         XX
XX  Derives from hashtable for most implementation. Inserted elements are    XX
XX  value pairs and the hash key is provided by the helper method that       XX
XX  extracts the key from the key value pair                                 XX
XX                                                                           XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/

#pragma once

#include "hashtable.h"

namespace jitstd
{

template <typename Key, typename Value>
struct pair_key
{
    Key& operator()(const jitstd::pair<Key, Value>& pair) const
    {
        return pair.first;
    }
};

template<typename Key,
         typename Value,
         typename Hash = jitstd::hash<Key>,
         typename Pred = jitstd::equal_to<Key>,
         typename Alloc = jitstd::allocator<jitstd::pair<const Key, Value> > >
class unordered_map
    : public hashtable<Key, pair<const Key, Value>, Hash, Pred, Alloc, pair_key<const Key, Value>>
{
public:

    typedef Key key_type;
    typedef Value mapped_type;
    typedef jitstd::pair<const Key, Value> value_type;
    typedef Hash hasher;
    typedef Pred key_equal;
    typedef Alloc allocator_type;
    typedef typename allocator_type::pointer pointer;
    typedef typename allocator_type::const_pointer const_pointer;
    typedef typename allocator_type::reference reference;
    typedef typename allocator_type::const_reference const_reference;
    typedef size_t size_type;
    typedef ptrdiff_t difference_type;

    explicit unordered_map(size_type size, const hasher& hasher, const key_equal& pred, const allocator_type& allocator);
    explicit unordered_map(size_type size, const allocator_type& allocator);
    template<typename InputIterator>
    unordered_map(InputIterator, InputIterator,
                  size_type size,
                  const hasher& hasher,
                  const key_equal& pred,
                  const allocator_type& allocator);

    unordered_map(const unordered_map& map);
    explicit unordered_map(const allocator_type& allocator);
    unordered_map(const unordered_map& map, const allocator_type& allocator);
    ~unordered_map();

    unordered_map& operator=(unordered_map const&);
    mapped_type& operator[](const Key& key);
    mapped_type& operator[](key_type&& key);

    typename unordered_map<Key, Value, Hash, Pred, Alloc>::iterator insert(const key_type& key, const mapped_type& value);

private:
    typedef hashtable<Key, pair<const Key, Value>, Hash, Pred, Alloc, pair_key<const Key, Value>> base_type;
};

}

namespace jitstd
{

template<typename Key, typename Value, typename Hash, typename Pred, typename Alloc>
unordered_map<Key, Value, Hash, Pred, Alloc>::unordered_map(size_type size, const hasher& hasher, const key_equal& pred, const allocator_type& allocator)
    : base_type(size, hasher, pred, allocator)
{
}

template<typename Key, typename Value, typename Hash, typename Pred, typename Alloc>
unordered_map<Key, Value, Hash, Pred, Alloc>::unordered_map(size_type size, const allocator_type& allocator)
    : base_type(size, allocator)
{
}

template<typename Key, typename Value, typename Hash, typename Pred, typename Alloc>
template<typename InputIterator>
unordered_map<Key, Value, Hash, Pred, Alloc>::unordered_map(InputIterator first, InputIterator last,
                size_type size,
                const hasher& hasher,
                const key_equal& pred,
                const allocator_type& allocator)
    : base_type(first, last, size, hasher, pred, allocator)
{
}

template<typename Key, typename Value, typename Hash, typename Pred, typename Alloc>
unordered_map<Key, Value, Hash, Pred, Alloc>::unordered_map(const unordered_map& map)
    : base_type(map)
{
}

template<typename Key, typename Value, typename Hash, typename Pred, typename Alloc>
unordered_map<Key, Value, Hash, Pred, Alloc>::unordered_map(const allocator_type& allocator)
    : base_type(allocator)
{
}

template<typename Key, typename Value, typename Hash, typename Pred, typename Alloc>
unordered_map<Key, Value, Hash, Pred, Alloc>::unordered_map(const unordered_map& map, const allocator_type& allocator)
    : base_type(map, allocator)
{
}

template<typename Key, typename Value, typename Hash, typename Pred, typename Alloc>
unordered_map<Key, Value, Hash, Pred, Alloc>::~unordered_map()
{
}

template<typename Key, typename Value, typename Hash, typename Pred, typename Alloc>
unordered_map<Key, Value, Hash, Pred, Alloc>& unordered_map<Key, Value, Hash, Pred, Alloc>::operator=(const unordered_map& map)
{
    base_type::operator=(map);
    return *this;
}

template<typename Key, typename Value, typename Hash, typename Pred, typename Alloc>
Value& unordered_map<Key, Value, Hash, Pred, Alloc>::operator[](const Key& key)
{
    iterator<Key, Value> iter = base_type::find(key, this->key_eq());
    if (iter == this->end())
    {
        iter = base_type::insert(jitstd::pair<const Key, mapped_type>(key, mapped_type())).first;
    }
    return (*iter).second;
}

template<typename Key, typename Value, typename Hash, typename Pred, typename Alloc>
Value& unordered_map<Key, Value, Hash, Pred, Alloc>::operator[](key_type&& key)
{
    iterator<Key, Value> iter = base_type::find(key, this->key_eq());
    if (iter == this->end())
    {
        iter = base_type::insert(jitstd::pair<const Key, mapped_type>(key, mapped_type())).first;
    }
    return (*iter).second;
}

template<typename Key, typename Value, typename Hash, typename Pred, typename Alloc>
typename unordered_map<Key, Value, Hash, Pred, Alloc>::iterator
unordered_map<Key, Value, Hash, Pred, Alloc>::insert(const key_type& key, const mapped_type& value)
{
    typename unordered_map<Key, Value, Hash, Pred, Alloc>::iterator iter = base_type::find(key, this->key_eq());
    iter = base_type::insert(jitstd::pair<const Key, mapped_type>(key, value)).first;
    return iter;
}

}


text:
package com.github.tomakehurst.wiremock;

import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.testsupport.Network;
import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.After;
import org.junit.Test;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.testsupport.TestFiles.sampleWarRootDir;
import static java.net.HttpURLConnection.HTTP_OK;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Tests that check if init parameters for servlets and the context of wiremock are passed on correctly
 */
public class WarDeploymentParameterAcceptanceTest {
    private Server jetty;
    private WireMockTestClient testClient;

    @After
    public void cleanup() throws Exception {
        jetty.stop();
        WireMock.configure();
    }

    @Test
    public void testCustomMapping() throws Exception {
        // Test war deployment using a different servlet mapping path (see webappCustomMapping).
        init(sampleWarRootDir() + "/src/main/webappCustomMapping", "/mapping");
        givenThat(get(urlEqualTo("/war/stub")).willReturn(
                aResponse().withStatus(HTTP_OK).withBody("War stub OK")));

        assertThat(testClient.get("/wiremock/mapping/war/stub").content(), is("War stub OK"));
    }

    @Test
    public void testLimitedRequestJournal() throws Exception {
        // Test war deployment usint a request journal restricted to two entries
        init(sampleWarRootDir() + "/src/main/webappLimitedRequestJournal", "");
        // We don't have to create a stub since failed requests are also recorded
        testClient.get("/wiremock/request1");
        testClient.get("/wiremock/request2");
        testClient.get("/wiremock/request3");

        // Only two requests are present since the oldest one is discarded
        verify(0, getRequestedFor(urlEqualTo("/request1")));
        verify(1, getRequestedFor(urlEqualTo("/request2")));
        verify(1, getRequestedFor(urlEqualTo("/request3")));
    }

    /**
     * Start jetty and wiremock. This is not an @Before method since we need to pass a parameter
     *
     * @param webInfPath  Path where the WEB-INF directory for jetty resides
     * @param mappingPath Path where wiremock is mapped
     */
    private void init(String webInfPath, String mappingPath) throws Exception {
        int port = Network.findFreePort();
        jetty = new Server(port);
        WebAppContext context = new WebAppContext(webInfPath, "/wiremock");
        jetty.setHandler(context);
        jetty.start();

        WireMock.configureFor("localhost", port, "/wiremock" + mappingPath);
        testClient = new WireMockTestClient(port);
    }
}


text:
<md-dialog aria-label="License" style="min-width:50%" >
    <md-toolbar>

Confirm

        <md-button class="md-icon-button" ng-click="closeDialog()">
          <md-icon md-svg-src="close" style="fill:white;" aria-label="Close dialog"></md-icon>
        </md-button>

    </md-toolbar>
    <md-dialog-content hide-xs show-gt-xs style="min-width: 470px;padding-bottom: 0px;" layout="column" class="md-padding">

                <md-card flex="100" style="margin-top: 0;">
                    <md-card-content>
                    Add or change tags (up to 5) so your story reaches more people:
                        <md-chips name="skills" md-separator-keys="customKeys" ng-model="tags" md-autocomplete-snap md-transform-chip="transformChip($chip)" md-max-chips="5" readonly="readonly" md-removable="removable" md-require-match="autocompleteDemoRequireMatch">
                            <md-autocomplete md-selected-item="selectedItem" md-search-text="searchText" md-items="item in querySearch(searchText)" md-item-text="item.name" placeholder="Add Tags..">
                                {{item.name}}
                            </md-autocomplete>
                            <md-chip-template custom-chip class="your-custom-chip">
                                {{$chip.name}}
                            </md-chip-template>
                        </md-chips>
                    </md-card-content>
                </md-card>

  <md-card flex="100" style="margin-top: 0;">
   <md-card-content>

Select an appropriate license

      <md-input-container>
        Licenses
        <md-select ng-model="selectedLicensces"
                   md-on-close="clearSearchTerm()"
                   data-md-container-class="selectdemoSelectHeader"
                   multiple>
          <md-select-header class="demo-select-header">
            <input ng-model="searchTerm"
                   type="search"
                   placeholder="Select a License"
                   class="demo-header-searchbox md-text">
          </md-select-header>
          <md-optgroup label="licenses">
            <md-option ng-value="license" ng-repeat="license in licenses |
              filter:searchTerm">{{license}}</md-option>
          </md-optgroup>
        </md-select>
      </md-input-container>

     </md-card-content>
                </md-card>

     <md-button class="md-secondary md-primary md-raised" ng-click="publish()" ng-hide="loading" type="button">Publish
     </md-button>

    </md-dialog-content>

</md-dialog>


text:
using System.Net;
using System.Threading;
using Netronics;
using Netronics.Channel;

namespace BroadcastServer
{
    class Program
    {
        private static readonly Handler Handler = new Handler();

        static void Main(string[] args)
        {
            // 본 설정은 EchoServer Example와 비슷합니다. 자세한 설명을 보고 싶으시면 EchoServer Example을 참고해주세요.
            var properties = Properties.CreateProperties(new IPEndPoint(IPAddress.Any, 7777),
                                             new ChannelPipe().SetCreateChannelAction(channel =>
                                             {
                                                 channel.SetConfig("encoder", PacketEncoder.Encoder);
                                                 channel.SetConfig("decoder", PacketEncoder.Encoder);
                                                 channel.SetConfig("handler", Handler);
                                             }));

            var netronics = new Netronics.Netronics(properties);
            netronics.Start();
        }
    }
}


text:
package main

import (
	"github.com/youtube/vitess/go/vt/discovery"
	"github.com/youtube/vitess/go/vt/servenv"
	_ "github.com/youtube/vitess/go/vt/status"
	"github.com/youtube/vitess/go/vt/vtgate"
	"github.com/youtube/vitess/go/vt/vtgate/gateway"
	"github.com/youtube/vitess/go/vt/vtgate/l2vtgate"
)

// For use by plugins which wish to avoid racing when registering status page parts.
var onStatusRegistered func()

func addStatusParts(l2vtgate *l2vtgate.L2VTGate) {
	servenv.AddStatusPart("Topology Cache", vtgate.TopoTemplate, func() interface{} {
		return resilientSrvTopoServer.CacheStatus()
	})
	servenv.AddStatusPart("Gateway Status", gateway.StatusTemplate, func() interface{} {
		return l2vtgate.GetGatewayCacheStatus()
	})
	servenv.AddStatusPart("Health Check Cache", discovery.HealthCheckTemplate, func() interface{} {
		return healthCheck.CacheStatus()
	})
	if onStatusRegistered != nil {
		onStatusRegistered()
	}
}


text:
#include "test.h"

#include "testutil.h"
#include "warnless.h"
#include "memdebug.h"

#define TEST_HANG_TIMEOUT 60 * 1000
#define WAKEUP_NUM 10

int test(char *URL)
{
  CURLM *multi = NULL;
  int numfds;
  int i;
  int res = 0;
  struct timeval time_before_wait, time_after_wait;

  (void)URL;

  start_test_timing();

  global_init(CURL_GLOBAL_ALL);

  multi_init(multi);

  /* no wakeup */

  time_before_wait = tutil_tvnow();
  multi_poll(multi, NULL, 0, 1000, &numfds);
  time_after_wait = tutil_tvnow();

  if(tutil_tvdiff(time_after_wait, time_before_wait) < 500) {
    fprintf(stderr, "%s:%d curl_multi_poll returned too early\n",
            __FILE__, __LINE__);
    res = TEST_ERR_MAJOR_BAD;
    goto test_cleanup;
  }

  abort_on_test_timeout();

  /* try a single wakeup */

  res_multi_wakeup(multi);

  time_before_wait = tutil_tvnow();
  multi_poll(multi, NULL, 0, 1000, &numfds);
  time_after_wait = tutil_tvnow();

  if(tutil_tvdiff(time_after_wait, time_before_wait) > 500) {
    fprintf(stderr, "%s:%d curl_multi_poll returned too late\n",
            __FILE__, __LINE__);
    res = TEST_ERR_MAJOR_BAD;
    goto test_cleanup;
  }

  abort_on_test_timeout();

  /* previous wakeup should not wake up this */

  time_before_wait = tutil_tvnow();
  multi_poll(multi, NULL, 0, 1000, &numfds);
  time_after_wait = tutil_tvnow();

  if(tutil_tvdiff(time_after_wait, time_before_wait) < 500) {
    fprintf(stderr, "%s:%d curl_multi_poll returned too early\n",
            __FILE__, __LINE__);
    res = TEST_ERR_MAJOR_BAD;
    goto test_cleanup;
  }

  abort_on_test_timeout();

  /* try lots of wakeup */

  for(i = 0; i < WAKEUP_NUM; ++i)
    res_multi_wakeup(multi);

  time_before_wait = tutil_tvnow();
  multi_poll(multi, NULL, 0, 1000, &numfds);
  time_after_wait = tutil_tvnow();

  if(tutil_tvdiff(time_after_wait, time_before_wait) > 500) {
    fprintf(stderr, "%s:%d curl_multi_poll returned too late\n",
            __FILE__, __LINE__);
    res = TEST_ERR_MAJOR_BAD;
    goto test_cleanup;
  }

  abort_on_test_timeout();

  /* Even lots of previous wakeups should not wake up this. */

  time_before_wait = tutil_tvnow();
  multi_poll(multi, NULL, 0, 1000, &numfds);
  time_after_wait = tutil_tvnow();

  if(tutil_tvdiff(time_after_wait, time_before_wait) < 500) {
    fprintf(stderr, "%s:%d curl_multi_poll returned too early\n",
            __FILE__, __LINE__);
    res = TEST_ERR_MAJOR_BAD;
    goto test_cleanup;
  }

  abort_on_test_timeout();

test_cleanup:

  curl_multi_cleanup(multi);
  curl_global_cleanup();

  return res;
}


text:
package de.dominikmuench.twintowns;

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

import processing.core.PApplet;
import processing.core.PFont;
import processing.data.TableRow;
import controlP5.CheckBox;
import controlP5.ControlFont;
import controlP5.ControlP5;
import controlP5.Range;
import de.dominikmuench.twintowns.markers.PartnershipMarker;
import de.dominikmuench.twintowns.model.GermanMunicipality;
import de.dominikmuench.twintowns.model.Municipality;
import de.dominikmuench.twintowns.utility.Style;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.events.MapEvent;
import de.fhpotsdam.unfolding.events.MapEventListener;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.Marker;
import de.fhpotsdam.unfolding.providers.EsriProvider;

@SuppressWarnings("serial")
public class TwinTownsApp extends PApplet implements MapEventListener {

	private TwinTownTable table;
	private UnfoldingMap map;
	private Rectangle controlArea;
	private ControlP5 cp5;
	private Range numOfPartnersRange;
	private CheckBox averageDirectionCheckBox;
	private CheckBox formCheckBox;

	/*
	 * (non-Javadoc)
	 *
	 * @see processing.core.PApplet#setup()
	 */
	@Override
	public void setup() {
		// General
//		size(800, 600, OPENGL);
		size(displayWidth, displayHeight, JAVA2D);
		smooth();

		// Map
		map = new UnfoldingMap(this, new EsriProvider.WorldGrayCanvas());
		MapState.getInstance().setMap(map);
		map.setTweening(true);
		map.zoomAndPanTo(6, new Location(51.164181f, 10.454150f));
		map.setZoomRange(3, 9);

		// Font
		PFont openSans12 = createFont("OpenSans", 12, true);
		PFont openSans18 = createFont("OpenSans", 18, true);
		MapState.getInstance().openSans12 = openSans12;
		MapState.getInstance().openSans18 = openSans18;
		ControlFont font = new ControlFont(openSans12, 12);

		// UI
		controlArea = new Rectangle(0, 0, 210, 200);
		cursor(CROSS);
		cp5 = new ControlP5(this);
		MapState.getInstance().setCp5(cp5);
		cp5.addTextfield("municipalityFilter")
//				.setText("München")
				.setPosition(10, 10)
				.setSize(200, 20)
				.setCaptionLabel("Gemeinde")
				.setFont(font)
				.setColorCaptionLabel(0);

		cp5.addTextfield("stateFilter")
//				.setText("Bayern")
				.setPosition(10, 50)
				.setSize(200, 20)
				.setCaptionLabel("Bundesland")
				.setFont(font)
				.setColorCaptionLabel(0);

		formCheckBox = cp5.addCheckBox("form")
			.setPosition(10, 95)
			.setColorLabel(0)
			.setSize(10, 10)
			.setItemsPerRow(3)
			.setSpacingColumn(70)
			.addItem("Partnerschaft", 0)
			.addItem("Freundschaft", 1)
			.addItem("Kontakt", 2);
		formCheckBox.activateAll();

		cp5.addRange("yearRange")
				.setBroadcast(false)
				.setPosition(10, 120)
				.setSize(200, 10)
				.setHandleSize(10)
				.setRange(1913, 2015)
				.setDecimalPrecision(0)
				.setRangeValues(1913, 2015)
				.setBroadcast(true)
				.setCaptionLabel("seit")
				.setColorCaptionLabel(0);

		cp5.addCheckBox("numOfPartners")
				.setPosition(10, 150)
				.setColorLabel(0)
                .setSize(20, 20)
                .setItemsPerRow(1)
                .setSpacingRow(20)
                .addItem("Anzahl Partnerschaften", 0);

		numOfPartnersRange = cp5.addRange("numOfPartnersRange")
				.setBroadcast(false)
				.setPosition(10, 180)
				.setSize(200, 10)
				.setHandleSize(10)
				.setRange(1, 73)
				.setDecimalPrecision(0)
				.setRangeValues(1, 73)
				.setBroadcast(true)
				.setCaptionLabel("Filter")
				.setColorCaptionLabel(0)
				.hide();

		averageDirectionCheckBox = cp5.addCheckBox("averageDirection")
				.setPosition(10, 180)
				.setColorLabel(0)
                .setSize(20, 20)
                .setItemsPerRow(1)
                .setSpacingRow(20)
                .addItem("Durchschnittliche Richtung", 0);

		new RestrictedEventDispatcher(this, map, controlArea);

		// Data & Markers
		table = new TwinTownTable(this);

		List<PartnershipMarker> markers = new ArrayList<>();
		PartnershipMarker lastMarker = null;
		for (TableRow row : table.rows()) {
			if (table.getMunicipality(row).contains("Kreis") || table.getMunicipality(row).contains("Bezirk")) {
				continue;
			}

			GermanMunicipality germanMunicipality = new GermanMunicipality(
					table.getMunicipality(row), new Location(
							table.getLatitude(row), table.getLongitude(row)),
					table.getState(row));

			Municipality partnerMunicipality = new Municipality(
					table.getPartnerMunicipality(row), new Location(
							table.getPartnerLatitude(row),
							table.getPartnerLongitude(row)),
					table.getPartnerCountry(row),
					table.getPartnerContinent(row),
					table.getForm(row),
					table.getYear(row));

			if (lastMarker == null
					|| !lastMarker.getGermanMunicipality().getName()
							.equals(table.getMunicipality(row))) {
				PartnershipMarker connMarker = new PartnershipMarker(
						germanMunicipality, partnerMunicipality);
				markers.add(connMarker);
				lastMarker = connMarker;
			} else {
				lastMarker.addPartnerMunicipality(partnerMunicipality);
			}
		}
		for (PartnershipMarker marker : markers) {
			map.addMarker(marker);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see processing.core.PApplet#draw()
	 */
	@Override
	public void draw() {
		map.draw();
		// Legend
		if (cp5.get(CheckBox.class, "numOfPartners").getArrayValue()[0] == 1.0) {
			pushStyle();
			noStroke();
			fill(Style.YELLOW_LOW);
			float radius = (float) (Math.log(map.getZoom()) / Math.log(2) * Math.sqrt(1 / Math.PI));
			ellipse(width - 70, height - 100, radius, radius);
			radius = (float) (Math.log(map.getZoom()) / Math.log(2) * Math.sqrt(5 / Math.PI));
			ellipse(width - 70, height - 67, radius, radius);
			radius = (float) (Math.log(map.getZoom()) / Math.log(2) * Math.sqrt(50 / Math.PI));
			ellipse(width - 70, height - 30, radius, radius);
			textAlign(CENTER, CENTER);
			fill(0);
			text("1", width - 30, height - 100);
			text("5", width - 30, height - 67);
			text("50", width - 30, height - 30);
			popStyle();
		}
	}

	@Override
	public boolean sketchFullScreen() {
		return true;
	}

	@Override
	public void mouseMoved() {

		for (Marker marker : map.getMarkers()) {
			if (!marker.equals(MapState.getInstance().getClickedMarker())) {
				marker.setSelected(false);
				MapState.getInstance().setSelectedMarker(null);
			}
		}

		Marker hitMarker = map.getFirstHitMarker(mouseX, mouseY);
		if (hitMarker != null) {
			map.getMarkers().remove(hitMarker);
			map.getMarkers().add(hitMarker);
			hitMarker.setSelected(true);
			MapState.getInstance().setSelectedMarker((PartnershipMarker) hitMarker);
		}
	}

	@Override
	public void mouseClicked() {

		// Ignore clicks inside control area
		if (controlArea.contains(mouseX, mouseY)) {
			return;
		}

		for (Marker marker : map.getMarkers()) {
			marker.setSelected(false);
		}
		PartnershipMarker hitMarker = MapState.getInstance().getSelectedMarker();
		if (hitMarker != null) {
			hitMarker.setSelected(true);
			MapState.getInstance().setClickedMarker(hitMarker);
		} else if (map.getFirstHitMarker(mouseX, mouseY) == null) {
			MapState.getInstance().setClickedMarker(null);
		}
	}

	@Override
	public String getId() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onManipulation(MapEvent event) {
		// TODO Auto-generated method stub
		System.err.println(event.toString());
	}

	public void numOfPartners(float[] a) {
		if (a[0] == 1.0) {
			numOfPartnersRange.show();
			averageDirectionCheckBox.setPosition(10, averageDirectionCheckBox.getPosition().y + 25);
			controlArea.y += 25;
		} else {
			numOfPartnersRange.hide();
			averageDirectionCheckBox.setPosition(10, averageDirectionCheckBox.getPosition().y - 25);
			controlArea.y -= 25;
		}
	}

	public static void main(String[] args) {
		PApplet.main(new String[] { "de.dominikmuench.twintowns.TwinTownsApp" });
	}

}


text:
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.utils import translation
from django.contrib.sites.models import Site
from django.core.mail import send_mail

TOPIC_SUBSCRIPTION_TEXT_TEMPLATE = lambda: _(u"""New reply from %(username)s to topic that you have subscribed on.
---
%(message)s
---
See topic: %(post_url)s
Unsubscribe %(unsubscribe_url)s""")

def notify_topic_subscribers(post):
    from pybb.models import Post

    topic = post.topic
    if post != topic.head:
        for user in topic.subscribers.all():
            if user != post.user:
                old_lang = translation.get_language()
                lang = user.pybb_profile.language or 'en'
                translation.activate(lang)

                subject = u'RE: %s' % topic.name
                to_email = user.email
                hostname = Site.objects.get_current().domain
                delete_url = reverse('pybb_subscription_delete', args=[post.topic.id])

                content = TOPIC_SUBSCRIPTION_TEXT_TEMPLATE() % {
                    'username': post.user.username,
                    'message': post.body_text,
                    'post_url': 'http://%s%s' % (hostname, post.get_absolute_url()),
                    'unsubscribe_url': 'http://%s%s' % (hostname, delete_url),
                }

                send_mail(subject, content, settings.DEFAULT_FROM_EMAIL,
                          [to_email], fail_silently=True)
                translation.activate(old_lang)


text:
#include <gtest/gtest.h>
#include <boost/signals2.hpp>

#include <functional>

#include "Ecs.hh"

namespace test
{

	typedef struct Position
	{
		Position() {}
		Position(int x, int y) : x(x), y(y) {}
		bool operator==(const Position & other) const
		{
			return x == other.x && y == other.y;
		}

		int x;
		int y;
	} Position;

	struct Character
	{
		Character(int health) : health(health) {}
		int health;
	};

	struct Weapon
	{
		Weapon(int damage) : damage(damage) {}
		int damage;
	};

	// An event
	struct Hit
	{
		Hit(ecs::Handle<Weapon> wep) : weapon(wep) {}
		ecs::Handle<Weapon> weapon;
	};

	class Gravedigger
	{
	public:
		void operator()(ecs::Entity e, const ecs::EntityDestruction &d)
		{
			gravesDug += 1;
		}

		int gravesDug = 0;
	};

	class HitReceiver
	{
	public:
		void operator()(ecs::Entity e, const Hit &hit)
		{
			e.Get<Character>()->health -= hit.weapon->damage;
			totalDamage += hit.weapon->damage;
			totalDamageSq = totalDamage * totalDamage;
		}

		int totalDamage = 0;
		int totalDamageSq = 0;
		double a;
		double b;
		double c;
		double d;
		double e;
	};

	class EcsEvents : public ::testing::Test
	{
	protected:
		ecs::EntityManager em;
		ecs::Entity player1;
		ecs::Entity player2;

		virtual void SetUp()
		{
			player1 = em.NewEntity();
			player1.Assign<Character>(10);
			player1.Assign<Weapon>(1);

			player2 = em.NewEntity();
			player2.Assign<Character>(10);
			player2.Assign<Weapon>(2);
		}
	};

	class EcsNonEntityEvents : public ::testing::Test
	{
	protected:
		ecs::EntityManager em;

		virtual void SetUp() {}
	};

	TEST_F(EcsEvents, ReceiveEventForSingleEntity)
	{
		HitReceiver hitReceiver;
		player1.Subscribe<Hit>(hitReceiver);
		player1.Emit(Hit(player2.Get<Weapon>()));

		ASSERT_EQ(8, player1.Get<Character>()->health)
			<< "subscriber was never triggered";
	}

	TEST_F(EcsEvents, ReceiveEventForSingleEntityWithLambda)
	{
		struct T {
			bool rekt;
		};

		bool rekt = false;
		player1.Subscribe<T>([&rekt](ecs::Entity e, const T &t) {
			rekt = t.rekt;
		});

		ASSERT_FALSE(rekt)
			<< "premature subscriber triggered";

		player1.Emit((struct T){.rekt = true});

		ASSERT_TRUE(rekt)
			<< "lambda subscriber was never triggered";
	}

	TEST_F(EcsEvents, ReceiveEventForAllEntities)
	{
		HitReceiver hitReceiver;
		em.Subscribe<Hit>(hitReceiver);

		player1.Emit(Hit(player2.Get<Weapon>()));
		player2.Emit(Hit(player1.Get<Weapon>()));

		ASSERT_EQ(8, player1.Get<Character>()->health)
			<< "subscriber was never triggered";

		ASSERT_EQ(9, player2.Get<Character>()->health)
			<< "subscriber was not triggered for all entities";
	}

	TEST_F(EcsEvents, ReceiveEventForAllEntitiesWithLambdasAndFunctors)
	{
		HitReceiver hitReceiver;
		em.Subscribe<Hit>(hitReceiver);

		bool rekt = false;
		em.Subscribe<Hit>([&rekt](ecs::Entity, const Hit &h) {
			rekt = true;
		});

		player1.Emit(Hit(player2.Get<Weapon>()));

		EXPECT_EQ(8, player1.Get<Character>()->health)
			<< "functor was not triggered";

		EXPECT_TRUE(rekt) << "lambda was not triggered";
	}

	/**
	 * Test that multiple large functors can be stored and called properly
	 * without any of their values overwritten. More of a sanity test
	 * casting between signal2::signal types doesn't do anything strange
	 * (this is done internally).
	 */
	TEST_F(EcsEvents, ReceiveEventForAllEntitiesWithLargeFunctors)
	{
		class Functor1 {
		public:
			void operator()(ecs::Entity e, const Hit &unused) {
				for (int64 &x : nums) {
					x += 1;
				}
			}
			std::array<int64, 32> nums = {0};
		};

		class Functor2 {
		public:
			void operator()(ecs::Entity e, const Hit &unused) {
				for (int64 &x : nums) {
					x += 2;
				}
			}
			std::array<int64, 16> nums = {0};
		};

		auto f1a = Functor1();
		auto f2  = Functor2();
		auto f1b = Functor1();

		em.Subscribe<Hit>(std::ref(f1a));
		em.Subscribe<Hit>(std::ref(f2));
		em.Subscribe<Hit>(std::ref(f1b));

		player1.Emit(Hit(player2.Get<Weapon>()));

		for (auto x : f1a.nums) {
			EXPECT_EQ(1, x);
		}
		for (auto x : f2.nums) {
			EXPECT_EQ(2, x);
		}
		for (auto x : f1b.nums) {
			EXPECT_EQ(1, x);
		}
	}

	TEST_F(EcsEvents, MultiReceiveEventForSingleEntity)
	{
		// player1 gets hit twice per Hit event
		HitReceiver hitReceiver1;
		HitReceiver hitReceiver2;
		player1.Subscribe<Hit>(hitReceiver1);
		player1.Subscribe<Hit>(hitReceiver2);

		player1.Emit(Hit(player2.Get<Weapon>()));

		ASSERT_EQ(6, player1.Get<Character>()->health)
			<< "not all subscribers were triggered";
	}

	TEST_F(EcsEvents, MultiReceiveEventForAllEntities)
	{
		// everyone gets hit twice per Hit event
		HitReceiver hitReceiver1;
		HitReceiver hitReceiver2;
		em.Subscribe<Hit>(hitReceiver1);
		em.Subscribe<Hit>(hitReceiver2);

		player1.Emit(Hit(player2.Get<Weapon>()));
		player2.Emit(Hit(player1.Get<Weapon>()));

		ASSERT_EQ(6, player1.Get<Character>()->health)
			<< "not all subscribers were triggered";

		ASSERT_EQ(8, player2.Get<Character>()->health)
			<< "not all subscribers were triggered";
	}

	TEST_F(EcsEvents, MultiReceiveEventForAllSingleEntitiesAndAllEntities)
	{
		// everyone gets hit 4 times per Hit event
		HitReceiver hitReceiver;
		em.Subscribe<Hit>(hitReceiver);
		em.Subscribe<Hit>(hitReceiver);

		player1.Subscribe<Hit>(hitReceiver);
		player1.Subscribe<Hit>(hitReceiver);

		player2.Subscribe<Hit>(hitReceiver);
		player2.Subscribe<Hit>(hitReceiver);

		player1.Emit(Hit(player2.Get<Weapon>()));
		player2.Emit(Hit(player1.Get<Weapon>()));

		ASSERT_EQ(2, player1.Get<Character>()->health)
			<< "not all subscribers were triggered";

		ASSERT_EQ(6, player2.Get<Character>()->health)
			<< "not all subscribers were triggered";
	}

	TEST_F(EcsEvents, MultiReceiveEventForSingleEntityWithSingleReceiver)
	{
		// player1 gets hit twice per Hit event (same receiver subscribed twice)
		HitReceiver hitReceiver;
		player1.Subscribe<Hit>(hitReceiver);
		player1.Subscribe<Hit>(hitReceiver);

		player1.Emit(Hit(player2.Get<Weapon>()));

		ASSERT_EQ(6, player1.Get<Character>()->health)
			<< "not all subscribers were triggered";
	}

	TEST_F(EcsEvents, ReceiveSingleEntityDestructionEvent)
	{
		Gravedigger gravedigger;
		player1.Subscribe<ecs::EntityDestruction>(std::ref(gravedigger));

		ASSERT_EQ(0, gravedigger.gravesDug);

		player1.Destroy();
		ASSERT_EQ(1, gravedigger.gravesDug)
			<< "Entity destruction event not seen by subscriber";

		player2.Destroy();
		ASSERT_EQ(1, gravedigger.gravesDug)
			<< "subscriber saw an event it wasn't subscribed to";
	}

	TEST_F(EcsEvents, ReceiveAllEntityDestructionyedEvents)
	{
		Gravedigger gravedigger;
		em.Subscribe<ecs::EntityDestruction>(std::ref(gravedigger));

		ASSERT_EQ(0, gravedigger.gravesDug);
		player1.Destroy();
		ASSERT_EQ(1, gravedigger.gravesDug)
			<< "Entity destruction event not seen by subscriber";
	}

	TEST_F(EcsEvents, UnsubscribeFromSingleEntityEvent)
	{
		HitReceiver hitReceiver;
		ecs::Subscription sub = player1.Subscribe<Hit>(hitReceiver);
		sub.Unsubscribe();

		EXPECT_FALSE(sub.IsActive());

		player1.Emit(Hit(player2.Get<Weapon>()));

		ASSERT_EQ(10, player1.Get<Character>()->health)
			<< "subscriber was triggered after it unsubscribed";
	}

	TEST_F(EcsEvents, UnsubscribeFromAllEntitiesEvent)
	{
		HitReceiver hitReceiver;
		ecs::Subscription sub = em.Subscribe<Hit>(hitReceiver);
		sub.Unsubscribe();
		EXPECT_FALSE(sub.IsActive());

		player1.Emit(Hit(player2.Get<Weapon>()));

		ASSERT_EQ(10, player1.Get<Character>()->health)
			<< "subscriber was triggered after it unsubscribed";
	}

	/**
	 * Context: There are 2 subscribers for an event which has just been
	 * triggered.
	 *
	 * If the 1st subscriber unsubscribes we need to ensure the 2nd one is still
	 * called. This might not happen when we just do a "swap-to-back and delete"
	 * approach to removing a subscriber. This should be handled similar to
	 * deleting components while iterating over them where they are flagged for
	 * deletion and then only do the swap-delete after we are done iterating
	 * over subscribers.
	 */
	TEST_F(EcsEvents, UnsubscribeFromAllEntitiesEventDoesNotCauseOtherSubscribersToMissAnEvent)
	{
		bool triggered1 = false;
		bool triggered2 = false;

		ecs::Subscription sub = em.Subscribe<bool>([&](ecs::Entity e, bool _){
			triggered1 = true;
			sub.Unsubscribe();
			EXPECT_FALSE(sub.IsActive());
		});

		em.Subscribe<bool>([&](ecs::Entity e, bool unused){
			triggered2 = true;
		});

		player1.Emit(true);

		EXPECT_TRUE(triggered1);
		EXPECT_TRUE(triggered2);
	}

	TEST_F(EcsNonEntityEvents, SingleReceive)
	{
		bool called = false;
		em.Subscribe<bool>([&](bool arg) {
			called = arg;
		});

		em.Emit(true);
		ASSERT_TRUE(called);
	}

	TEST_F(EcsNonEntityEvents, MultiReceive)
	{
		int timesCalled = 0;
		auto callback = [&](bool arg) {
			timesCalled += 1;
		};

		em.Subscribe<bool>(callback);
		em.Subscribe<bool>(callback);

		em.Emit(true);
		ASSERT_EQ(2, timesCalled);
	}

	TEST_F(EcsNonEntityEvents, Unsubscribe)
	{
		int timesCalled = 0;
		auto callback = [&](bool arg) {
			timesCalled += 1;
		};

		ecs::Subscription sub = em.Subscribe<bool>(callback);
		em.Emit(true);
		sub.Unsubscribe();

		EXPECT_EQ(1, timesCalled);
		EXPECT_FALSE(sub.IsActive());
	}
}


text:
<?php

namespace Acme\MainBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController;

class ServiceAdminController extends CRUDController
{

}


text: <button  ng-click="logout()">Logout</button>


text:
using namespace ofp;

TEST(protocolversions, defaultConstructor) {
  ProtocolVersions versions{ProtocolVersions::All};

  EXPECT_EQ(OFP_VERSION_6, versions.highestVersion());
  EXPECT_EQ(0x7E, versions.bitmap());

  std::vector<UInt8> v{1, 2, 3, 4, 5, 6};
  EXPECT_EQ(v, versions.versions());

  EXPECT_FALSE(versions.empty());

  EXPECT_EQ(0x7E, ProtocolVersions::VersionBitmapAll);
  EXPECT_EQ(0x00, ProtocolVersions::VersionBitmapNone);
}

TEST(protocolversions, versionConstructor) {
  ProtocolVersions versions{0x04};

  EXPECT_EQ(0x04, versions.highestVersion());
  EXPECT_EQ(0x10, versions.bitmap());
  EXPECT_FALSE(versions.empty());

  ProtocolVersions b{1, 3, 4};

  EXPECT_TRUE(b.containsVersion(1));
  EXPECT_FALSE(b.containsVersion(2));
}

TEST(protocolversions, fromBitmap) {
  ProtocolVersions versions = ProtocolVersions::fromBitmap(0x04);

  EXPECT_EQ(0x02, versions.highestVersion());
  EXPECT_EQ(0x04, versions.bitmap());
  EXPECT_FALSE(versions.empty());

  ProtocolVersions nothing = ProtocolVersions::fromBitmap(0);

  EXPECT_EQ(0, nothing.highestVersion());
  EXPECT_EQ(0, nothing.bitmap());
  EXPECT_TRUE(nothing.empty());
}

TEST(protocolversions, fromBitmapAll) {
  ProtocolVersions versions = ProtocolVersions::All;

  EXPECT_EQ(OFP_VERSION_6, versions.highestVersion());
  EXPECT_EQ(0x7E, versions.bitmap());
  EXPECT_FALSE(versions.empty());

  ProtocolVersions other = ProtocolVersions::All;

  other = other.intersection(versions);
  EXPECT_EQ(0x7E, other.bitmap());
}

TEST(protocolversions, negotiateVersion) {
  {
    ProtocolVersions vers{1};

    EXPECT_EQ(1, vers.negotiateVersion(4, {1, 2, 3, 4}));
    EXPECT_EQ(0, vers.negotiateVersion(4, {2, 3, 4}));
    EXPECT_EQ(1, vers.negotiateVersion(3, ProtocolVersions::None));
    EXPECT_EQ(1, vers.negotiateVersion(2, ProtocolVersions::None));
    EXPECT_EQ(1, vers.negotiateVersion(1, ProtocolVersions::None));

    EXPECT_EQ(0, vers.negotiateVersion(4, {4}));
  }

  {
    ProtocolVersions vers{4};
    EXPECT_EQ(4, vers.negotiateVersion(4, {1, 2, 3, 4}));
    EXPECT_EQ(4, vers.negotiateVersion(4, ProtocolVersions::None));

    EXPECT_EQ(0, vers.negotiateVersion(3, ProtocolVersions::None));
    EXPECT_EQ(0, vers.negotiateVersion(2, ProtocolVersions::None));
    EXPECT_EQ(0, vers.negotiateVersion(1, ProtocolVersions::None));

    EXPECT_EQ(4, vers.negotiateVersion(4, {4}));
  }

  {
    ProtocolVersions vers{1, 4};
    EXPECT_EQ(4, vers.negotiateVersion(4, {1, 2, 3, 4}));
    EXPECT_EQ(4, vers.negotiateVersion(4, ProtocolVersions::None));

    EXPECT_EQ(0, vers.negotiateVersion(3, ProtocolVersions::None));
    EXPECT_EQ(0, vers.negotiateVersion(2, ProtocolVersions::None));
    EXPECT_EQ(1, vers.negotiateVersion(1, ProtocolVersions::None));

    EXPECT_EQ(4, vers.negotiateVersion(4, {4}));
  }

  {
    ProtocolVersions vers{2, 3, 4};
    EXPECT_EQ(4, vers.negotiateVersion(4, {1, 2, 3, 4}));
    EXPECT_EQ(4, vers.negotiateVersion(4, ProtocolVersions::None));

    EXPECT_EQ(3, vers.negotiateVersion(3, ProtocolVersions::None));
    EXPECT_EQ(2, vers.negotiateVersion(2, ProtocolVersions::None));
    EXPECT_EQ(0, vers.negotiateVersion(1, ProtocolVersions::None));

    EXPECT_EQ(4, vers.negotiateVersion(4, {4}));
  }

  {
    ProtocolVersions vers{2, 3};
    EXPECT_EQ(3, vers.negotiateVersion(4, {1, 2, 3, 4}));
    EXPECT_EQ(3, vers.negotiateVersion(4, ProtocolVersions::None));

    EXPECT_EQ(3, vers.negotiateVersion(3, ProtocolVersions::None));
    EXPECT_EQ(2, vers.negotiateVersion(2, ProtocolVersions::None));
    EXPECT_EQ(0, vers.negotiateVersion(1, ProtocolVersions::None));

    EXPECT_EQ(0, vers.negotiateVersion(4, {4}));
  }
}

TEST(protocolversions, toString) {
  ProtocolVersions v1 = {1, 3, 4};
  EXPECT_EQ("[1, 3, 4]", v1.toString());

  ProtocolVersions v2 = {};
  EXPECT_EQ("[]", v2.toString());

  ProtocolVersions v3 = {3};
  EXPECT_EQ("[3]", v3.toString());
}

TEST(protocolversions, includeInHelloMsg) {
  ProtocolVersions v1 = {4};
  EXPECT_FALSE(v1.includeInHelloMsg(4));

  ProtocolVersions v2 = {1, 2, 3, 4};
  EXPECT_FALSE(v2.includeInHelloMsg(4));
  EXPECT_TRUE(v2.includeInHelloMsg(5));

  ProtocolVersions v3 = {1, 3, 4};
  EXPECT_TRUE(v3.includeInHelloMsg(4));
  EXPECT_FALSE(v3.includeInHelloMsg(3));
}


text:
/**
 * THIS FILE IS AUTO-GENERATED
 * DON'T MAKE CHANGES HERE
 */
import { conjDependencies } from './dependenciesConj.generated'
import { transposeDependencies } from './dependenciesTranspose.generated'
import { typedDependencies } from './dependenciesTyped.generated'
import { createCtranspose } from '../../factoriesAny.js'

export const ctransposeDependencies = {
  conjDependencies,
  transposeDependencies,
  typedDependencies,
  createCtranspose
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.ocpsoft.rewrite</groupId>
      <artifactId>rewrite-parent</artifactId>
      <version>3.0.0-SNAPSHOT</version>
      <relativePath>../</relativePath>
   </parent>

   <artifactId>rewrite-impl-servlet-2.5</artifactId>

   <dependencies>
      <dependency>
         <groupId>org.ocpsoft.rewrite</groupId>
         <artifactId>rewrite-api</artifactId>
      </dependency>
      <dependency>
         <groupId>org.ocpsoft.rewrite</groupId>
         <artifactId>rewrite-api-servlet</artifactId>
      </dependency>
      <dependency>
         <groupId>org.jboss.spec.javax.servlet</groupId>
         <artifactId>jboss-servlet-api_2.5_spec</artifactId>
         <scope>provided</scope>
      </dependency>
      <dependency>
         <groupId>org.ocpsoft.rewrite</groupId>
         <artifactId>rewrite-test-base</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.mockito</groupId>
         <artifactId>mockito-all</artifactId>
         <version>1.9.0-rc1</version>
         <scope>test</scope>
      </dependency>
   </dependencies>
</project>


text:
<?php

namespace Antsfree\Mxusearch\Console;

use Antsfree\Mxusearch\Mxusearch;
use Illuminate\Console\Command;

class CheckService extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'search:check-server';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check Mxusearch server status.';

    /**
     * CheckService constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            $count = Mxusearch::getIndexCount();
            if (isset($count)) {
                return $this->line("搜索服务正常,当前共有 $count 条索引\n");
            }
        } catch (\Exception $e) {
            return $this->error("讯搜服务异常\n");
        }
    }
}


text:
using System;

namespace Task_2
{
    /// <summary>
    /// Hash table on linked list
    /// </summary>
    public class HashTable
    {
        /// <summary>
        /// Size of hash table
        /// </summary>
        private const int size = 100;

        /// <summary>
        /// Function for hashing
        /// </summary>
        private IHashFunction hashFunction;

        /// <summary>
        /// Hash table
        /// </summary>
        private List[] table;

        /// <summary>
        /// Constructor for hash table
        /// </summary>
        /// <param name="hashFunction">Function for hashing</param>
        public HashTable(IHashFunction hashFunction)
        {
            this.hashFunction = hashFunction;
            table = new List[size];

            for (var i = 0; i < size; ++i)
            {
                table[i] = new List();
            }
        }

        /// <summary>
        /// Adding new word to hash table
        /// </summary>
        /// <param name="word">Word for adding</param>
        public void Add(string word) => table[hashFunction.GetHash(word) % size].Add(word);

        /// <summary>
        /// Removing word from hash table
        /// </summary>
        /// <param name="word">Word for removing</param>
        public void Remove(string word) => table[hashFunction.GetHash(word) % size].RemoveElement(word);

        /// <summary>
        /// Checking if the word is contained
        /// </summary>
        /// <param name="word">Word for checking</param>
        /// <returns>True if belongs otherwise false</returns>
        public bool IsContained(string word) => table[hashFunction.GetHash(word) % size].IsContained(word);
    }
}


text:
from __future__ import print_function

import aerospike
import sys

from optparse import OptionParser

##########################################################################
# Options Parsing
##########################################################################

usage = "usage: %prog [options] key"

optparser = OptionParser(usage=usage, add_help_option=False)

optparser.add_option(
    "--help", dest="help", action="store_true",
    help="Displays this message.")

optparser.add_option(
    "-U", "--username", dest="username", type="string", metavar="<USERNAME>",
    help="Username to connect to database.")

optparser.add_option(
    "-P", "--password", dest="password", type="string", metavar="<PASSWORD>",
    help="Password to connect to database.")

optparser.add_option(
    "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="<ADDRESS>",
    help="Address of Aerospike server.")

optparser.add_option(
    "-p", "--port", dest="port", type="int", default=3000, metavar="<PORT>",
    help="Port of the Aerospike server.")

optparser.add_option(
    "-n", "--namespace", dest="namespace", type="string", default="test", metavar="<NS>",
    help="Port of the Aerospike server.")

optparser.add_option(
    "-s", "--set", dest="set", type="string", default="demo", metavar="<SET>",
    help="Port of the Aerospike server.")

(options, args) = optparser.parse_args()

if options.help:
    optparser.print_help()
    print()
    sys.exit(1)

if len(args) != 1:
    optparser.print_help()
    print()
    sys.exit(1)

###############################################################################
# Client Configuration
###############################################################################

config = {
    'hosts': [(options.host, options.port)]
}

###############################################################################
# Application
###############################################################################

exitCode = 0

try:

    # ----------------------------------------------------------------------------
    # Connect to Cluster
    # ----------------------------------------------------------------------------

    client = aerospike.client(config).connect(
        options.username, options.password)

    # ----------------------------------------------------------------------------
    # Perform Operation
    # ----------------------------------------------------------------------------

    try:
        namespace = options.namespace if options.namespace and options.namespace != 'None' else None
        set = options.set if options.set and options.set != 'None' else None
        key = args.pop()

        client.remove((namespace, set, key))

        print("OK, 1 record removed.")

    except Exception as eargs:
        (code, msg, file, line) = eargs
        if code == 602:
            print("error: Record not found")
        else:
            print(
                "error: {0}".format((code, msg, file, line)), file=sys.stderr)
            rc = 1

    # ----------------------------------------------------------------------------
    # Close Connection to Cluster
    # ----------------------------------------------------------------------------

    client.close()

except Exception as eargs:
    print("error: {0}".format(eargs), file=sys.stderr)
    exitCode = 3

##########################################################################
# Exit
##########################################################################

sys.exit(exitCode)


text:
using Extensions;
using Unianio;
using UnityEngine;
using UnityFunctions;

namespace Main
{
    public class CapsuleCapsuleResolution : BaseMainScript
    {
//        private const float CapsuleRadius1 = 0.12f;
//        private const float CapsuleRadius2 = 0.2f;
//        private const float CapsuleHeight1 = 0.8f;
//        private const float CapsuleHeight2 = 0.6f;

        private const float StaticHeight = 0.4f;
        private const float StaticRadius = 0.14f;

        private const float DynamicHeight = 0.8f;
        private const float DynamicRadius = 0.06f;
        private Transform _static,_dynamicPrev,_dynamicNext;
        private GameObject _dynPrev;
        private GameObject _dynNext;

        void Start ()
        {
            var statCap = fun.meshes.CreateCapsule(
                    new DtCapsule {radius = StaticRadius, height = StaticHeight, name = "static_cap"});
            _dynPrev = fun.meshes.CreateCapsule(
                    new DtCapsule {radius = DynamicRadius, height = DynamicHeight, name = "dynamic_prev_raw"});
            _dynNext = fun.meshes.CreateCapsule(
                    new DtCapsule {radius = DynamicRadius, height = DynamicHeight, name = "dynamic_next_raw"});
            _dynPrev.hideFlags = HideFlags.HideInHierarchy;
            _dynNext.hideFlags = HideFlags.HideInHierarchy;

            var dynPrevWrapper = new GameObject("dynamic_prev");
            dynPrevWrapper.transform.position = _dynPrev.transform.position + (-_dynPrev.transform.up)*(DynamicHeight/2+DynamicRadius);
            dynPrevWrapper.transform.rotation = Quaternion.LookRotation(_dynPrev.transform.up, _dynPrev.transform.forward);
            dynPrevWrapper.hideFlags = HideFlags.HideInHierarchy;
            _dynPrev.transform.SetParent(dynPrevWrapper.transform);

            var dynNextWrapper = new GameObject("dynamic_next");
            dynNextWrapper.transform.position = _dynNext.transform.position + (-_dynNext.transform.up)*(DynamicHeight/2+DynamicRadius);
            dynNextWrapper.transform.rotation = Quaternion.LookRotation(_dynNext.transform.up, _dynNext.transform.forward);
            _dynNext.transform.SetParent(dynNextWrapper.transform);

            _static = statCap.transform;
            _dynamicPrev = dynPrevWrapper.transform;
            _dynamicPrev.position += Vector3.forward*-0.5f + Vector3.up*0.5f + Vector3.right*0.3f;
            _dynamicPrev.rotation = Quaternion.Euler(0,0,180);
            _dynamicNext = dynNextWrapper.transform;
            _dynamicNext.position = _dynamicPrev.position;
            _dynamicNext.rotation = _dynamicPrev.rotation;

        }
        void Update()
        {
            var statP0 = _static.position - _static.up*(StaticHeight/2);
            var statP1 = _static.position + _static.up*(StaticHeight/2);

            var prevP0 = _dynamicPrev.position + _dynamicPrev.forward*(DynamicRadius);
            var prevP1 = _dynamicPrev.position + _dynamicPrev.forward*(DynamicRadius + DynamicHeight);

            var nextP0 = _dynamicNext.position + _dynamicNext.forward*(DynamicRadius);
            var nextP1 = _dynamicNext.position + _dynamicNext.forward*(DynamicRadius + DynamicHeight);
            var nextUp = _dynamicNext.up;

            // test code STARTS here -----------------------------------------------
            Vector3 resolvedPos;
            Quaternion resolvedRot;
            var hasResolution =
                fun.resolution.BetweenCapsules(
                    in statP0, in statP1, StaticRadius,
                    in prevP0, in prevP1, in nextP0, in nextP1, in nextUp, DynamicRadius,
                    out resolvedPos, out resolvedRot);
            // test code ENDS here -------------------------------------------------

            _dynamicPrev.position = resolvedPos;
            _dynamicPrev.rotation = resolvedRot;

            SetColorOnChanged(hasResolution, rgba(1, 0, 0, 0.5), rgba(0.5,0.0,0.0,0.2), _static);
            SetColorOnChanged(hasResolution, rgba(0, 1, 0, 0.5), rgba(0.0,0.5,0.0,0.2), _dynPrev.transform);
            SetColorOnChanged(hasResolution, rgba(0, 0, 1, 0.5), rgba(0.0,0.0,0.5,0.2), _dynNext.transform);
        }

    }
}


text:
package org.carlspring.strongbox.xml;

import org.carlspring.strongbox.storage.routing.RuleSet;

import javax.xml.bind.annotation.XmlElement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author mtodorov
 */
public class RuleSetMap
{

    @XmlElement(name = "rule-set")
    private List<RuleSet> entries = new ArrayList<>();

    public List<RuleSet> getEntries()
    {
        return entries;
    }

    public void add(RuleSet routingRule)
    {
        entries.add(routingRule);
    }

}


text:
package edu.icom4029.cool.lexer;

// This is a project skeleton file for PA5, but a regular support code
// for other assignments.

import java.io.PrintStream;

import edu.icom4029.cool.cgen.CgenSupport;
import edu.icom4029.cool.core.TreeConstants;

/** String table entry for string constants. */
public class StringSymbol extends AbstractSymbol {
	/* Creates a new symbol.
	 *
	 * @see AbstractSymbol
	 * */
	public StringSymbol(String str, int len, int index) {
		super(str, len, index);
	}

	/** Generates code for the string constant definition.  This method
	 * is incomplete; you get to finish it up in programming assignment
	 * 5.
	 * @param stringclasstag the class tag for string object
	 * @param s the output stream
	 *
	 * */
	public void codeDef(int stringclasstag, PrintStream s) {
		IntSymbol lensym = (IntSymbol)AbstractTable.inttable.addInt(str.length());

		// Add -1 eye catcher
		s.println(CgenSupport.WORD + "-1");
		codeRef(s); s.print(CgenSupport.LABEL); // label
		s.println(CgenSupport.WORD + stringclasstag); // tag
		s.println(CgenSupport.WORD + (CgenSupport.DEFAULT_OBJFIELDS +
				CgenSupport.STRING_SLOTS +
				(str.length() + 4) / 4)); // object size
		s.print(CgenSupport.WORD);

		/* Add code to reference the dispatch table for class String here */
		CgenSupport.emitDispTableRef(TreeConstants.Str, s);

		s.println("");		// dispatch table
		s.print(CgenSupport.WORD); lensym.codeRef(s); s.println(""); // length
		CgenSupport.emitStringConstant(str, s); // ascii string
		s.print(CgenSupport.ALIGN); // align to word
	}

	/** Emits a reference to this string constant.
	 * @param s the output stream
	 * */
	public void codeRef(PrintStream s) {
		s.print(CgenSupport.STRCONST_PREFIX + index);
	}

	/** Returns a copy of this symbol */
	public Object clone() {
		return new StringSymbol(str, str.length(), index);
	}
}


text:
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;
using IToken = Antlr4.Runtime.IToken;

/// <summary>
/// This interface defines a complete generic visitor for a parse tree produced
/// by <see cref="GrammarV1Parser"/>.
/// </summary>
/// <typeparam name="Result">The return type of the visit operation.</typeparam>
[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.7")]
[System.CLSCompliant(false)]
public interface IGrammarV1Visitor<Result> : IParseTreeVisitor<Result> {
	/// <summary>
	/// Visit a parse tree produced by <see cref="GrammarV1Parser.method"/>.
	/// </summary>
	/// <param name="context">The parse tree.</param>
	/// <return>The visitor result.</return>
	Result VisitMethod([NotNull] GrammarV1Parser.MethodContext context);
	/// <summary>
	/// Visit a parse tree produced by <see cref="GrammarV1Parser.statement"/>.
	/// </summary>
	/// <param name="context">The parse tree.</param>
	/// <return>The visitor result.</return>
	Result VisitStatement([NotNull] GrammarV1Parser.StatementContext context);
	/// <summary>
	/// Visit a parse tree produced by <see cref="GrammarV1Parser.statementIf"/>.
	/// </summary>
	/// <param name="context">The parse tree.</param>
	/// <return>The visitor result.</return>
	Result VisitStatementIf([NotNull] GrammarV1Parser.StatementIfContext context);
	/// <summary>
	/// Visit a parse tree produced by <see cref="GrammarV1Parser.type"/>.
	/// </summary>
	/// <param name="context">The parse tree.</param>
	/// <return>The visitor result.</return>
	Result VisitType([NotNull] GrammarV1Parser.TypeContext context);
}


text:
const noop = require('./noop');

const finallyMixin = (prototype) =>
  Object.assign(prototype, {
    finally(onFinally) {
      return this.then().finally(onFinally);
    },
  });

// FYI: Support for `Promise.prototype.finally` was not introduced until Node 9.
//      Therefore, Knex will need to conditionally inject support for `.finally(..)`
//      until support for Node 8 is officially dropped.
module.exports = Promise.prototype.finally ? finallyMixin : noop;


text:
go get
GOOS=linux GOARCH=386 CGO_ENABLED=0 go build
docker build -t stevelacy/quartermaster .


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class RestartGame : MonoBehaviour {

    public void ReloadScene()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}


text:
/*
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2011, Open Source Geospatial Foundation (OSGeo)
 *    (C) 2008-2011 TOPP - www.openplans.org.
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 */
package mil.nga.giat.geowave.analytics;

import com.vividsolutions.jts.geom.Envelope;

/**
 * Computes a Heat Map surface from a set of irregular data points, each
 * containing a positive height value. The nature of the surface is determined
 * by a kernelRadius value, which indicates how far out each data points
 * "spreads".
 *

 * The Heatmap surface is computed as a grid (raster) of values representing the
 * surface. For stability, the compute grid is expanded by the kernel radius on
 * all four sides. This avoids "edge effects" from distorting the surface within
 * the requested envelope.
 *

 * The values in the output surface are normalized to lie in the range [0, 1].
 *
 * @author Martin Davis, OpenGeo
 *
 */
public class HeatmapSurface
{
	/**
	 * Number of iterations of box blur to approximate a Gaussian blur
	 */
	private static final int GAUSSIAN_APPROX_ITER = 4;

	private Envelope srcEnv;

	private int xSize;

	private int ySize;

	private float[][] grid;

	double dx;
	double dy;

	/**
	 * Creates a new heatmap surface.
	 *
	 * @param kernelRadius
	 *            the kernel radius, in grid units
	 * @param srcEnv
	 *            the envelope defining the data space
	 * @param xSize
	 *            the width of the output grid
	 * @param ySize
	 *            the height of the output grid
	 */
	public HeatmapSurface(
			int kernelRadius,
			Envelope srcEnv,
			int xSize,
			int ySize ) {
		this.srcEnv = srcEnv;
		this.xSize = xSize;
		this.ySize = ySize;
		dx = srcEnv.getWidth() / (xSize - 1);
		dy = srcEnv.getHeight() / (ySize - 1);
		init();
	}

	private void init() {

		grid = new float[xSize][ySize];
	}

	/**
	 * Adds a new data point to the surface. Data points can be coincident.
	 *
	 * @param x
	 *            the X ordinate of the point
	 * @param y
	 *            the Y ordinate of the point
	 * @param value
	 *            the data value of the point
	 */
	public void addPoint(
			double x,
			double y,
			double value ) {
		/**
		 * Input points are converted to grid space, and offset by the grid
		 * expansion offset
		 */
		int gi = i(x);
		int gj = j(y);

		// check if point falls outside grid - skip it if so
		if (gi < 0 || gi > grid.length || gj < 0 || gj > grid[0].length) return;

		grid[gi][gj] = (float) value;
		// System.out.println("data[" + gi + ", " + gj + "] <- " + value);
	}

	public void addPoints(
			double minx,
			double miny,
			double maxx,
			double maxy,
			double value ) {
		/**
		 * Input points are converted to grid space, and offset by the grid
		 * expansion offset
		 */
		int gmini = i(minx);
		int gminj = j(miny);
		int gmaxi = i(maxx);
		int gmaxj = j(maxy);
		for (int gi = gmini; gi <= gmaxi; gi++) {
			for (int gj = gminj; gj <= gmaxj; gj++) {
				// check if point falls outside grid - skip it if so
				if (gi < 0 || gi > grid.length || gj < 0 || gj > grid[0].length) continue;

				grid[gi][gj] = (float) value;
			}
		}
		// System.out.println("data[" + gi + ", " + gj + "] <- " + value);
	}

	/**
	 * Computes the column index of an X ordinate.
	 *
	 * @param x
	 *            the X ordinate
	 * @return the column index
	 */
	public int i(
			double x ) {
		if (x > srcEnv.getMaxX()) return xSize;
		if (x < srcEnv.getMinX()) return -1;
		int i = (int) ((x - srcEnv.getMinX()) / dx + 0.5);
		// have already check x is in bounds, so ensure returning a valid value
		if (i >= xSize) i = xSize - 1;
		return i;
	}

	/**
	 * Computes the column index of an Y ordinate.
	 *
	 * @param y
	 *            the Y ordinate
	 * @return the column index
	 */
	public int j(
			double y ) {
		if (y > srcEnv.getMaxY()) return ySize;
		if (y < srcEnv.getMinY()) return -1;
		int j = (int) ((y - srcEnv.getMinY()) / dy + 0.5);
		// have already check x is in bounds, so ensure returning a valid value
		if (j >= ySize) j = ySize - 1;
		return j;
	}

	/**
	 * Computes a grid representing the heatmap surface. The grid is structured
	 * as an XY matrix, with (0,0) being the bottom left corner of the data
	 * space
	 *
	 * @return a grid representing the surface
	 */
	public float[][] computeSurface() {

		// computeHeatmap(grid, kernelRadiusGrid);
		//
		// float[][] gridOut = extractGrid(grid, kernelRadiusGrid,
		// kernelRadiusGrid, xSize, ySize);
		// normalize(grid);
		return grid;
	}

	private float[][] extractGrid(
			float[][] grid,
			int xBase,
			int yBase,
			int xSize,
			int ySize ) {
		float[][] gridExtract = new float[xSize][ySize];
		for (int i = 0; i < xSize; i++) {
			for (int j = 0; j < ySize; j++) {
				gridExtract[i][j] = grid[xBase + i][yBase + j];
			}
		}
		return gridExtract;
	}

	private float[][] computeHeatmap(
			float[][] grid,
			int kernelRadius ) {
		int xSize = grid.length;
		int ySize = grid[0].length;

		int baseBoxKernelRadius = kernelRadius / GAUSSIAN_APPROX_ITER;
		int radiusIncBreak = kernelRadius - baseBoxKernelRadius * GAUSSIAN_APPROX_ITER;

		/**
		 * Since Box Blur is linearly separable, can implement it by doing 2 1-D
		 * box blurs in different directions. Using a flipped buffer grid allows
		 * the same code to compute each direction, as well as preserving input
		 * grid values.
		 */
		// holds flipped copy of first box blur pass
		float[][] grid2 = new float[ySize][xSize];
		for (int count = 0; count < GAUSSIAN_APPROX_ITER; count++) {
			int boxKernelRadius = baseBoxKernelRadius;
			/**
			 * If required, increment radius to ensure sum of radii equals total
			 * kernel radius
			 */
			if (count < radiusIncBreak) boxKernelRadius++;
			// System.out.println(boxKernelRadius);

			boxBlur(
					boxKernelRadius,
					grid,
					grid2);
			boxBlur(
					boxKernelRadius,
					grid2,
					grid);
		}

		// testNormalizeFactor(baseBoxKernelRadius, radiusIncBreak);
		normalize(grid);
		return grid;
	}

	/**
	 * DON'T USE This method is too simplistic to determine normalization
	 * factor. Would need to use a full 2D grid and smooth it to get correct
	 * value
	 *
	 * @param baseBoxKernelRadius
	 * @param radiusIncBreak
	 */
	private void testNormalizeFactor(
			int baseBoxKernelRadius,
			int radiusIncBreak ) {
		double val = 1.0;
		for (int count = 0; count < GAUSSIAN_APPROX_ITER; count++) {
			int boxKernelRadius = baseBoxKernelRadius;
			/**
			 * If required, increment radius to ensure sum of radii equals total
			 * kernel radius
			 */
			if (count < radiusIncBreak) boxKernelRadius++;

			int dia = 2 * boxKernelRadius + 1;
			float kernelVal = kernelVal(boxKernelRadius);
			System.out.println(boxKernelRadius + " kernel val = " + kernelVal);

			if (count == 0) {
				val = val * 1 * kernelVal;
			}
			else {
				val = val * dia * kernelVal;
			}
			System.out.println("norm val = " + val);
			if (count == 0) {
				val = val * 1 * kernelVal;
			}
			else {
				val = val * dia * kernelVal;
			}
		}
		System.out.println("norm factor = " + val);
	}

	/**
	 * Normalizes grid values to range [0,1]
	 *
	 * @param grid
	 */
	private void normalize(
			float[][] grid ) {
		float max = Float.NEGATIVE_INFINITY;
		for (int i = 0; i < grid.length; i++) {
			for (int j = 0; j < grid[0].length; j++) {
				if (grid[i][j] > max) max = grid[i][j];
			}
		}

		float normFactor = 1.0f / max;

		for (int i = 0; i < grid.length; i++) {
			for (int j = 0; j < grid[0].length; j++) {
				grid[i][j] *= normFactor;
			}
		}
	}

	private float kernelVal(
			int kernelRadius ) {
		// This kernel function has been confirmed to integrate to 1 over the
		// full radius
		float val = (float) (1.0f / (2 * kernelRadius + 1));
		return val;
	}

	private void boxBlur(
			int kernelRadius,
			float[][] input,
			float[][] output ) {
		int width = input.length;
		int height = input[0].length;

		// init moving average total
		float kernelVal = kernelVal(kernelRadius);
		// System.out.println("boxblur: radius = " + kernelRadius +
		// " kernel val = " + kernelVal);

		for (int j = 0; j < height; j++) {

			double tot = 0.0;

			for (int i = -kernelRadius; i <= kernelRadius; i++) {
				if (i < 0 || i >= width) continue;
				tot += kernelVal * input[i][j];
			}

			// System.out.println(tot);

			output[j][0] = (float) tot;

			for (int i = 1; i < width; i++) {

				// update box running total
				int iprev = i - 1 - kernelRadius;
				if (iprev >= 0) tot -= kernelVal * input[iprev][j];

				int inext = i + kernelRadius;
				if (inext < width) tot += kernelVal * input[inext][j];

				output[j][i] = (float) tot;
				// if (i==49 && j==147) System.out.println("val[ " + i + ", " +
				// j + "] = " + tot);

			}
		}
	}
}


text:
.class Landroid/text/style/URLSpan$2;
.super Ljava/lang/Object;
.source "URLSpan.java"

# interfaces
.implements Landroid/content/DialogInterface$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/text/style/URLSpan;->onClick(Landroid/view/View;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/text/style/URLSpan;

# direct methods
.method constructor <init>(Landroid/text/style/URLSpan;)V
    .locals 0
    .parameter

    .prologue
    .line 91
    iput-object p1, p0, Landroid/text/style/URLSpan$2;->this$0:Landroid/text/style/URLSpan;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public final onClick(Landroid/content/DialogInterface;I)V
    .locals 0
    .parameter "dialog"
    .parameter "which"

    .prologue
    .line 93
    invoke-interface {p1}, Landroid/content/DialogInterface;->dismiss()V

    .line 94
    return-void
.end method