text:
from django.core.management.base import BaseCommand
from optparse import make_option

from test.test_runner import JumoTestSuiteRunner

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--addrport', action='store', dest='addrport',
            type='string', default='',
            help='port number or ipaddr:port to run the server on'),
    )
    help = 'Runs a development server with data from the given fixture(s).'
    args = '[fixture ...]'

    requires_model_validation = False

    def handle(self, *fixture_labels, **options):
        from django.core.management import call_command
        #from django.db import connection
        from django.db import connections

        verbosity = int(options.get('verbosity', 1))
        addrport = options.get('addrport')

        #Not sure why django devs do this different than the test command
        #but using the same technique works for us.
        jtsr = JumoTestSuiteRunner()
        (old_names, mirrors) = jtsr.setup_databases()
        for db_data in old_names:
            print "Loading Fixture Data Into %s" % db_data[0].settings_dict["NAME"]
            call_command('loaddata', *fixture_labels, **{'verbosity': verbosity, "database":db_data[0].alias})

        # Create a test database.
        #db_name = connection.creation.create_test_db(verbosity=verbosity)

        # Import the fixture data into the test database.
        #call_command('loaddata', *fixture_labels, **{'verbosity': verbosity})

        # Run the development server. Turn off auto-reloading because it causes
        # a strange error -- it causes this handle() method to be called
        # multiple times.
        #shutdown_message = '\nServer stopped.\nNote that the test database, %r, has not been deleted. You can explore it on your own.' % db_name
        shutdown_message = '\nServer stopped.\nNote that the test databases have not been deleted. You can explore it on your own.'
        call_command('runserver', addrport=addrport, shutdown_message=shutdown_message, use_reloader=False)


text:
import * as React from 'react';

declare module 'primereact/cascadeselect' {

    type ItemTemplateType = React.ReactNode | ((option: any) => React.ReactNode);

    type AppendToType = 'self' | HTMLElement | undefined | null;

    interface ChangeParams {
        originalEvent: React.SyntheticEvent;
        value: any;
    }

    interface GroupChangeParams extends ChangeParams { }

    export interface CascadeSelectProps {
        id?: string;
        inputRef?: React.Ref<HTMLInputElement>;
        style?: object;
        className?: string;
        value?: any;
        name?: string;
        options?: any[];
        optionLabel?: string;
        optionValue?: string;
        optionGroupLabel?: string;
        optionGroupChildren?: string[];
        placeholder?: string;
        itemTemplate?: ItemTemplateType;
        disabled?: boolean;
        dataKey?: string;
        inputId?: string;
        tabIndex?: number;
        ariaLabelledBy?: string;
        appendTo?: AppendToType;
        transitionOptions?: object;
        onChange?(e: ChangeParams): void;
        onGroupChange?(e: GroupChangeParams): void;
        onBeforeShow?(): void;
        onBeforeHide?(): void;
        onShow?(): void;
        onHide?(): void;
    }

    export class CascadeSelect extends React.Component<CascadeSelectProps, any> { }
}

redpajama_set_name: RedPajamaGithub


text:
require "bundler_deps/version"

module BundlerDeps
  # Your code goes here...
end


text:
<ion-modal-view>
    <ion-header-bar  class="bar-balanced">

Add Expense

		<button class="button button-clear button-primary" ng-click="modal.hide()">Cancel</button>
    </ion-header-bar>
    <ion-content>

                <input type="text" ng-model="newExpense.detail" placeholder="Expense">

                <input type="number" ng-model="newExpense.amount" placeholder="Amount">

            <button ng-click="addNewExpense()" class="button button-full button-positive">
                Add Expense
            </button>

    </ion-content>
</ion-modal-view>


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)

require 'fieldbook'
require 'pry'
require 'dotenv'

Dotenv.load


text:
using System;
using System.Xml.Serialization;

namespace Aop.Api.Domain
{
    /// <summary>
    /// ExtBrand Data Structure.
    /// </summary>
    [Serializable]
    public class ExtBrand : AopObject
    {
        /// <summary>
        /// 品牌编码
        /// </summary>
        [XmlElement("brand_code")]
        public string BrandCode { get; set; }

        /// <summary>
        /// 品牌名称
        /// </summary>
        [XmlElement("name")]
        public string Name { get; set; }
    }
}


text:
from __future__ import unicode_literals, division

from flask import Flask, request, redirect
from flask.ext.sqlalchemy import SQLAlchemy
import os
from raven import Client
from raven.middleware import Sentry

from yoi.account.user import bp as account
from yoi.config import (secret,
                        database_url,
                        in_production,
                        canonical_domain,
                        always_secure)
from yoi import dweeb
from yoi.flask_genshi import Genshi, render_response
from yoi import middleware
from yoi.resources import static_url

app = Flask(__name__)
app.request_class = dweeb.Request

app.genshi = Genshi(app)
app.db = SQLAlchemy(app)

app.register_blueprint(account)

# FIXME - Use app.config.from_object
app.config['DEBUG'] = True
app.config['PROPAGATE_EXCEPTIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = database_url
app.config['SECRET_KEY'] = secret

if canonical_domain:
    app.config['SESSION_COOKIE_DOMAIN'] = canonical_domain
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SECURE'] = always_secure

# Global HTTP response headers
cache_headers = [
    ('Cache-Control', 'public'),
]
no_cache_headers = [
    ('Cache-Control', 'no-cache'),
    ('Expires', 'Sat, 07 Jul 1979 23:00:00 GMT'),
]
hsts_headers = [
    ('Strict-Transport-Security', 'max-age=31536000; includeSubDomains'),
]

@app.after_request
def add_global_headers(response):
    expires = getattr(response, 'expires', None)
    if expires:
        response.headers.extend(cache_headers)
    else:
        response.headers.extend(no_cache_headers)

    if request.is_secure:
        response.headers.extend(hsts_headers)

    return response

@app.before_request
def canonical_redirect():
    if always_secure and not request.is_secure:
        return redirect(request.url.replace('http://', 'https://'))
    if canonical_domain and request.host != canonical_domain:
        return redirect(request.url.replace('://' + request.host,
                                            '://' + canonical_domain))

# Nice error pages
@app.errorhandler(404)
def not_found(e):
    return render_response('404.html'), 404

# Error-reporting middleware
if 'SENTRY_URL' in os.environ:
    app.wsgi_app = Sentry(app.wsgi_app, Client(os.environ['SENTRY_URL']))

# Nice 'Internal Server Error' page
# FIXME - should use render_template.
with app.test_request_context('/'):
    error_page = (app.genshi
                  .template_loader.load('500.html')
                  .generate(g={'user': None},
                            get_flashed_messages=lambda **kwargs: [],
                            static_url=static_url)
                  .render('html'))

if in_production:
    app.wsgi_app = middleware.error_page(app.wsgi_app, error_page)


text:
package org.apache.solr.common.cloud;

import static org.apache.solr.common.params.CommonParams.NAME;
import static org.apache.solr.common.params.CommonParams.VERSION;

import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
import org.apache.solr.cluster.api.SimpleMap;
import org.apache.solr.common.MapWriter;
import org.apache.solr.common.annotation.JsonProperty;
import org.apache.solr.common.cloud.Replica.ReplicaStateProps;
import org.apache.solr.common.util.ReflectMapWriter;
import org.apache.solr.common.util.StrUtils;
import org.apache.solr.common.util.WrappedSimpleMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This represents the individual replica states in a collection This is an immutable object. When
 * states are modified, a new instance is constructed
 */
public class PerReplicaStates implements ReflectMapWriter {
  private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
  public static final char SEPARATOR = ':';
  // no:of times to retry in case of a CAS failure
  public static final int MAX_RETRIES = 5;

  // znode path where thisis loaded from
  @JsonProperty public final String path;

  // the child version of that znode
  @JsonProperty public final int cversion;

  // states of individual replicas
  @JsonProperty public final SimpleMap<State> states;

  private volatile Boolean allActive;

  /**
   * Construct with data read from ZK
   *
   * @param path path from where this is loaded
   * @param cversion the current child version of the znode
   * @param states the per-replica states (the list of all child nodes)
   */
  public PerReplicaStates(String path, int cversion, List<String> states) {
    this.path = path;
    this.cversion = cversion;
    Map<String, State> tmp = new LinkedHashMap<>();

    for (String state : states) {
      State rs = State.parse(state);
      if (rs == null) continue;
      State existing = tmp.get(rs.replica);
      if (existing == null) {
        tmp.put(rs.replica, rs);
      } else {
        tmp.put(rs.replica, rs.insert(existing));
      }
    }
    this.states = new WrappedSimpleMap<>(tmp);
  }

  /** Check and return if all replicas are ACTIVE */
  public boolean allActive() {
    if (this.allActive != null) return allActive;
    boolean[] result = new boolean[] {true};
    states.forEachEntry(
        (r, s) -> {
          if (s.state != Replica.State.ACTIVE) result[0] = false;
        });
    return this.allActive = result[0];
  }

  /** Get the changed replicas */
  public static Set<String> findModifiedReplicas(PerReplicaStates old, PerReplicaStates fresh) {
    Set<String> result = new HashSet<>();
    if (fresh == null) {
      old.states.forEachKey(result::add);
      return result;
    }
    old.states.forEachEntry(
        (s, state) -> {
          // the state is modified or missing
          if (!Objects.equals(fresh.get(s), state)) result.add(s);
        });
    fresh.states.forEachEntry(
        (s, state) -> {
          if (old.get(s) == null) result.add(s);
        });
    return result;
  }

  public static String getReplicaName(String s) {
    int idx = s.indexOf(SEPARATOR);
    if (idx > 0) {
      return s.substring(0, idx);
    }
    return null;
  }

  public State get(String replica) {
    return states.get(replica);
  }

  public static class Operation {
    public final Type typ;
    public final State state;

    public Operation(Type typ, State replicaState) {
      this.typ = typ;
      this.state = replicaState;
    }

    public enum Type {
      // add a new node
      ADD,
      // delete an existing node
      DELETE
    }

    @Override
    public String toString() {
      return typ.toString() + " : " + state;
    }
  }

  @Override
  public String toString() {
    StringBuilder sb =
        new StringBuilder("{").append(path).append("/[").append(cversion).append("]: [");
    appendStates(sb);
    return sb.append("]}").toString();
  }

  private StringBuilder appendStates(StringBuilder sb) {
    states.forEachEntry(
        new BiConsumer<String, State>() {
          int count = 0;

          @Override
          public void accept(String s, State state) {
            if (count++ > 0) sb.append(", ");
            sb.append(state.asString);
            for (State d : state.getDuplicates()) sb.append(d.asString);
          }
        });
    return sb;
  }

  /**
   * The state of a replica as stored as a node under
   * /collections/collection-name/state.json/replica-state
   */
  public static class State implements MapWriter {

    public final String replica;

    public final Replica.State state;

    public final Boolean isLeader;

    public final int version;

    public final String asString;

    /**
     * if there are multiple entries for the same replica, e.g: core_node_1:12:A core_node_1:13:D
     *
     *
the entry with '13' is the latest and the one with '12' is considered a duplicate
     *
     *
These are unlikely, but possible
     */
    final State duplicate;

    private State(String serialized, List<String> pieces) {
      this.asString = serialized;
      replica = pieces.get(0);
      version = Integer.parseInt(pieces.get(1));
      String encodedStatus = pieces.get(2);
      this.state = Replica.getState(encodedStatus);
      isLeader = pieces.size() > 3 && "L".equals(pieces.get(3));
      duplicate = null;
    }

    public static State parse(String serialized) {
      List<String> pieces = StrUtils.splitSmart(serialized, ':');
      if (pieces.size() < 3) return null;
      return new State(serialized, pieces);
    }

    public State(String replica, Replica.State state, Boolean isLeader, int version) {
      this(replica, state, isLeader, version, null);
    }

    public State(
        String replica, Replica.State state, Boolean isLeader, int version, State duplicate) {
      this.replica = replica;
      this.state = state == null ? Replica.State.ACTIVE : state;
      this.isLeader = isLeader == null ? Boolean.FALSE : isLeader;
      this.version = version;
      asString = serialize();
      this.duplicate = duplicate;
    }

    @Override
    public void writeMap(EntryWriter ew) throws IOException {
      ew.put(NAME, replica);
      ew.put(VERSION, version);
      ew.put(ReplicaStateProps.STATE, state.toString());
      if (isLeader) ew.put(ReplicaStateProps.LEADER, isLeader);
      ew.putIfNotNull("duplicate", duplicate);
    }

    private State insert(State duplicate) {
      assert this.replica.equals(duplicate.replica);
      if (this.version >= duplicate.version) {
        if (this.duplicate != null) {
          duplicate =
              new State(
                  duplicate.replica,
                  duplicate.state,
                  duplicate.isLeader,
                  duplicate.version,
                  this.duplicate);
        }
        return new State(this.replica, this.state, this.isLeader, this.version, duplicate);
      } else {
        return duplicate.insert(this);
      }
    }

    /** fetch duplicates entries for this replica */
    List<State> getDuplicates() {
      if (duplicate == null) return Collections.emptyList();
      List<State> result = new ArrayList<>();
      State current = duplicate;
      while (current != null) {
        result.add(current);
        current = current.duplicate;
      }
      return result;
    }

    private String serialize() {
      StringBuilder sb =
          new StringBuilder(replica)
              .append(":")
              .append(version)
              .append(":")
              .append(state.shortName);
      if (isLeader) sb.append(":").append("L");
      return sb.toString();
    }

    @Override
    public String toString() {
      return asString;
    }

    @Override
    public boolean equals(Object o) {
      if (o instanceof State) {
        State that = (State) o;
        return Objects.equals(this.asString, that.asString);
      }
      return false;
    }

    @Override
    public int hashCode() {
      return asString.hashCode();
    }

    public State getDuplicate() {
      return duplicate;
    }
  }
}


text:
package security;

import java.io.*;
import java.nio.ByteBuffer;

class SecInputStream
		extends FilterInputStream
{

    private Key cipher ;
    private DataInputStream dis ;
    private ByteBuffer data = ByteBuffer.allocate(0) ;

    public SecInputStream( InputStream is, Key cipher ) {
        super(is) ;
        dis = new DataInputStream( is ) ;
        this.cipher = cipher ;
    }

    public int read() throws IOException {
        this.decodeBlock() ;
        if( data.remaining() > 0 ) {
        	byte b = data.get();
        	return ((int)b) & 0xFF;
        }
        else return -1 ;
    }

    public int read( byte[] b ) throws IOException {
        return this.read( b, 0, b.length ) ;
    }

    public int read( byte[] b, int offset, int length ) throws IOException {
        this.decodeBlock() ;
        if( data.remaining() > 0 ) {
            int l = Math.min( length, data.remaining() ) ;
            data.get( b, offset, l ) ;
            return l ;
        }
        else return -1 ;
    }

    private void decodeBlock() throws IOException {
        if( data.remaining() == 0 ) {
            try {
                byte[] block = new byte[ dis.readShort() ] ;
                dis.readFully( block ) ;
                data = ByteBuffer.wrap( cipher.decrypt( block ) ) ;
            } catch( EOFException x ) {
            }
        }
    }

}


text:
{% extends "wagtailadmin/base.html" %}
{% load i18n wagtailadmin_tags %}
{% block titletag %}{% blocktrans with title=page.get_admin_display_title %}Delete {{ title }}{% endblocktrans %}{% endblock %}

{% block content %}
    {% trans "Delete" as del_str %}
    {% include "wagtailadmin/shared/header.html" with title=del_str subtitle=page.get_admin_display_title icon="doc-empty-inverse" %}

            {% trans 'Are you sure you want to delete this page?' %}
            {% if descendant_count %}
                {% blocktrans count counter=descendant_count %}
                    This will also delete one more subpage.
                {% plural %}
                    This will also delete {{ descendant_count }} more subpages.
                {% endblocktrans %}
            {% endif %}

        <form action="{% url 'wagtailadmin_pages:delete' page.id %}" method="POST">
            {% csrf_token %}
            <input type="hidden" name="next" value="{{ next }}">
            <input type="submit" value="{% trans 'Yes, delete it' %}" class="button serious">
            {% trans "No, don't delete it" %}
        </form>

        {% page_permissions page as page_perms %}
        {% if page_perms.can_unpublish %}
            {% url 'wagtailadmin_pages:unpublish' page.id as unpublish_url %}

{% blocktrans %}Alternatively you can unpublish the page. This removes the page from public view and you can edit or publish it again later.{% endblocktrans %}

        {% endif %}

{% endblock %}


text:
/** Example of how a grid layout stylehseet could be done with Flex box: */

.umb-block-grid__layout-container {
    position: relative;
    display: flex;
    flex-wrap: wrap;
}
.umb-block-grid__layout-item {
    --umb-block-grid__layout-item-calc: calc(var(--umb-block-grid--item-column-span) / var(--umb-block-grid--grid-columns));
    width: calc(var(--umb-block-grid__layout-item-calc) * 100%);
}
.umb-block-grid__layout-item[data-force-left] {
    align-self: flex-start;
}
.umb-block-grid__layout-item[data-force-left]::before {
    content: '';
    flex-basis: 100%;
    height: 0;
}
.umb-block-grid__layout-item[data-force-right] {
    margin-left: auto;
    align-self: flex-end;
}

.umb-block-grid__area-container, .umb-block-grid__block--view::part(area-container) {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    width: 100%;
}
.umb-block-grid__area {
    --umb-block-grid__area-calc: calc(var(--umb-block-grid--area-column-span) / var(--umb-block-grid--area-grid-columns, 1));
    width: calc(var(--umb-block-grid__area-calc) * 100%);
}


text:
#region License

#endregion

using System.Reflection;
using AopAlliance.Intercept;

namespace Spring.Transaction.Interceptor
{
	///
	/// An AOP Alliance <see cref="AopAlliance.Intercept.IMethodInterceptor"/> providing
	/// declarative transaction management using the common Spring.NET transaction infrastructure.
	///
	/// <remarks>
	///

	/// That class contains the necessary calls into Spring.NET's underlying
	/// transaction API: subclasses such as this are responsible for calling
	/// superclass methods such as
    /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.CreateTransactionIfNecessary(MethodInfo, Type) "/>
	/// in the correct order, in the event of normal invocation return or an exception.
	///

	///

	/// <see cref="Spring.Transaction.Interceptor.TransactionInterceptor"/>s are thread-safe.
	///

	/// </remarks>
	/// <author>Rod Johnson</author>
	/// <author>Juergen Hoeller</author>
	/// <author>Griffin Caprio (.NET)</author>
	/// <author>Mark Pollack (.NET)</author>
	[Serializable]
	public class TransactionInterceptor : TransactionAspectSupport, IMethodInterceptor
	{
		///
		/// AOP Alliance invoke call that handles all transaction plumbing.
		///
		/// <param name="invocation">
		/// The method that is to execute in the context of a transaction.
		/// </param>
		/// <returns>The return value from the method invocation.</returns>
		public object Invoke(IMethodInvocation invocation)
		{
            // Work out the target class: may be null.
            // The TransactionAttributeSource should be passed the target class
            // as well as the method, which may be from an interface.
			Type targetType = ( invocation.This != null ) ? invocation.This.GetType() : null;

            // If the transaction attribute is null, the method is non-transactional.
			TransactionInfo txnInfo = CreateTransactionIfNecessary( invocation.Method, targetType );
			object returnValue = null;

			try
			{
                // This is an around advice.
                // Invoke the next interceptor in the chain.
                // This will normally result in a target object being invoked.
				returnValue = invocation.Proceed();
			}
			catch ( Exception ex )
			{
                // target invocation exception
				CompleteTransactionAfterThrowing( txnInfo, ex );
                throw;
			}
			finally
			{
				CleanupTransactionInfo( txnInfo );
			}
			CommitTransactionAfterReturning( txnInfo );
			return returnValue;
		}
	}
}


text:
package au.com.agic.apptesting.utils;

import au.com.agic.apptesting.profiles.configuration.UrlMapping;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * This class maintains a mapping between a thread id and the Selenium desired capabilities that
 * will be used by the web driver created inside that thread. <p> This is necessary because Cucumber
 * doesn't really support the notion of running tests in multiple threads with multiple
 * configurations (http://www.drobsonconsulting.co.uk/cucumber-and-concurrency/). But this is
 * exactly what we want to do when running against BrowserStack. <p> So this class provides a lookup
 * that is linked to a thread id. This means that when cucumber is creating instances of the Step
 * definitions, the actual configuration of the web driver can be retrieved against a specific
 * thread. In this way we can have multiple threads each creating webdrivers that are consistent for
 * that thread, but different to the other threads.
 */
public interface ThreadWebDriverMap {

	/**
	 * Initialise any internal structures with the list of loaded capabilities
	 *
	 * @param desiredCapabilities the list of capabilities that were loaded
	 * @param applicationUrls     the list of urls assocaited with the application we are testing
	 * @param datasets            the datasets that can be used by a test script
	 * @param myReportDirectory     The directory that holds reports and other test script outputs
	 * @param myTempFolders	      A list of directories that need to be deleted once the test is complete
	 * @param myProxies	  		  A list of the proxies that have been configured
	 */
	void initialise(
		@NotNull List<DesiredCapabilities> desiredCapabilities,
		@NotNull List<UrlMapping> applicationUrls,
		@NotNull Map<Integer, Map<String, String>> datasets,
		@NotNull String myReportDirectory,
		@NotNull List<File> myTempFolders,
		@NotNull List<ProxyDetails<?>> myProxies);

	/**
	 * @param name The name of the currently executing thread
	 * @return The state of the currently executing feature
	 */
	@NotNull
	FeatureState getDesiredCapabilitiesForThread(@NotNull String name);

	/**
	 * @return The web driver and url associated with the current thread
	 */
	@NotNull
	default FeatureState getDesiredCapabilitiesForThread() {
		return getDesiredCapabilitiesForThread(Thread.currentThread().getName());
	}

	/**
	 *
	 * @param name The name of the currently executing thread
	 * @param  createIfMissing set to true to create a web driver if one doesn't exist
	 * @return The web driver and url associated with the thread
     */
	@NotNull
	WebDriver getWebDriverForThread(@NotNull String name, boolean createIfMissing);

	/**
	 * @param  createIfMissing set to true to create a web driver if one doesn't exist
	 * @return The web driver for the current thread
	 */
	@NotNull
	default WebDriver getWebDriverForThread(final boolean createIfMissing) {
		return getWebDriverForThread(Thread.currentThread().getName(), createIfMissing);
	}

	/**
	 *
	 * @return The web driver for the current thread
	 */
	@NotNull
	default WebDriver getWebDriverForThread() {
		return getWebDriverForThread(Thread.currentThread().getName(), true);
	}

	/**
	 * Clears the web driver assigned to a thread.
	 * @param name The name of the thread
	 * @param quitDriver true if the driver should quit before it is cleared
	 */
	void clearWebDriverForThread(@NotNull String name, boolean quitDriver);

	/**
	 *
	 * Clears the web driver assigned to the current thread.
	 * @param quitDriver true if the driver should quit before it is cleared
     */
	default void clearWebDriverForThread(final boolean quitDriver) {
		clearWebDriverForThread(Thread.currentThread().getName(), quitDriver);
	}

	/**
	 * @return The number of threads that should be run in order to conver all the defined
	 * configurations
	 */
	int getNumberCapabilities();

	/**
	 *
	 * @return The list of temporary folders to be cleaned up when shutdown is called
	 */
	List<File> getTempFolders();

	/**
	 * Cleans up the web drivers
	 */
	void shutdown();

	/**
	 * Cleans up the web drivers for an individual thread
	 *
	 * @param name The name of the thread that should have its associated resources cleaned up
	 */
	void shutdown(@NotNull String name);

}


text:
^title Performance

Even though most benchmarks aren't worth the pixels they're printed on, people
seem to like them, so here's a few:

Method Call

    wren
0.12s

    luajit (-joff)
0.16s

    ruby
0.20s

    lua
0.35s

    python3
0.78s

    python
0.85s

DeltaBlue

    wren
0.13s

    python3
0.48s

    python
0.57s

Binary Trees

    luajit (-joff)
0.11s

    wren
0.22s

    ruby
0.24s

    python
0.37s

    python3
0.38s

    lua
0.52s

Recursive Fibonacci

    luajit (-joff)
0.10s

    wren
0.20s

    ruby
0.22s

    lua
0.28s

    python
0.51s

    python3
0.57s

**Shorter bars are better.** Each benchmark is run ten times and the best time
is kept. It only measures the time taken to execute the benchmarked code
itself, not interpreter startup.

These were run on my MacBook Pro 2.3 GHz Intel Core i7 with 16 GB of 1,600 MHz
DDR3 RAM. Tested against Lua 5.2.3, LuaJIT 2.0.2, Python 2.7.5, Python 3.3.4,
ruby 2.0.0p247. LuaJIT is run with the JIT *disabled* (i.e. in bytecode
interpreter mode) since I want to support platforms where JIT-compilation is
disallowed. LuaJIT with the JIT enabled is *much* faster than all of the other
languages benchmarked, including Wren, because Mike Pall is a robot from the
future.

The benchmark harness and programs are
[here](https://github.com/munificent/wren/tree/master/test/benchmark).

## Why is Wren fast?

Languages come in four rough performance buckets, from slowest to fastest:

1.  Tree-walk interpreters: Ruby 1.8.7 and earlier, Io, that
    interpreter you wrote for a class in college.

2.  Bytecode interpreters: CPython,
    Ruby 1.9 and later, Lua, early JavaScript VMs.

3.  JIT compiled dynamically typed languages: Modern JavaScript VMs,
    LuaJIT, PyPy, some Lisp/Scheme implementations.

4.  Statically typed languages: C, C++, Java, C#, Haskell, etc.

Most languages in the first bucket aren't suitable for production use. (Servers
are one exception, because you can throw more hardware at a slow language
there.) Languages in the second bucket are fast enough for many use cases, even
on client hardware, as the success of the listed languages shows. Languages in
the third bucket are quite fast, but their implementations are breathtakingly
complex, often rivaling that of compilers for statically-typed languages.

Wren is in the second bucket. If you want a simple implementation that's fast
enough for real use, this is the sweet spot. In addition, Wren has a few tricks
up its sleeve:

### A compact value representation

A core piece of a dynamic language implementation is the data structure used
for variables. It needs to be able to store (or reference) a value of any type,
while also being as compact as possible. Wren uses a technique called *[NaN
tagging][]* for this.

[nan tagging]: http://wingolog.org/archives/2011/05/18/value-representation-in-javascript-implementations

All values are stored internally in Wren as small, eight-byte double-precision
floats. Since that is also Wren's number type, in order to do arithmetic, no
conversion is needed before the "raw" number can be accessed: a value holding a
number *is* a valid double. This keeps arithmetic fast.

To store values of other types, it turns out there's a ton of unused bits in a
NaN double. You can stuff a pointer for heap-allocated objects, with room left
over for special values like `true`, `false`, and `null`. This means numbers,
bools, and null are unboxed. It also means an entire value is only eight bytes,
the native word size on 64-bit machines. Smaller = faster when you take into
account CPU caching and the cost of passing values around.

### Fixed object layout

Most dynamic languages treat objects as loose bags of named properties. You can
freely add and remove properties from an object after you've created it.
Languages like Lua and JavaScript don't even have a well-defined concept of a
"type" of object.

Wren is strictly class-based. Every object is an instance of a class. Classes
in turn have a well-defined declarative syntax, and cannot be imperatively
modified. In addition, fields in Wren are private to the class—they can
only be accessed from methods defined directly on that class.

Put all of that together and it means you can determine at *compile* time
exactly how many fields an object has and what they are. In other languages,
when you create an object, you allocate some initial memory for it, but that
may have to be reallocated multiple times as fields are added and the object
grows. Wren just does a single allocation up front for exactly the right number
of fields.

Likewise, when you access a field in other languages, the interpreter has to
look it up by name in a hash table in the object, and then maybe walk its
inheritance chain if it can't find it. It must do this every time since fields
may be added freely. In Wren, field access is just accessing a slot in the
instance by an offset known at compile time: it's just adding a few pointers.

### Copy-down inheritance

When you call a method on an object, the method must be located. It could be
defined directly on the object's class, or it may be inheriting it from some
superclass. This means that in the worst case, you may have to walk the
inheritance chain to find it.

Advanced implementations do very smart things to optimize this, but it's made
more difficult by the mutable nature of the underlying language: if you can add
new methods to existing classes freely or change the inheritance hierarchy, the
lookup for a given method may actually change over time. You have to check for
that which costs CPU cycles.

Wren's inheritance hierarchy is static and fixed at class definition time. This
means that we can copy down all inherited methods in the subclass when it's
created since we know those will never change. Method dispatch then just
requires locating the method in the class of the receiver.

### Method signatures

Wren supports overloading by arity using its concept of [signatures]. This makes
the language more expressive, but also faster. When a method is called, we look
it up on the receiver's class. If we succeed in finding it, we also know it has
the right number of parameters.

This lets Wren avoid the extra checking most languages need to do at runtime to
handle too few or too many arguments being passed to a method. In Wren, it's not
*syntactically* possible to call a method with the wrong number of arguments.

[signatures]: method-calls.html#signature

### Computed gotos

On compilers that support it, Wren's core bytecode interpreter loop uses
something called [*computed gotos*][goto]. The hot core of a bytecode
interpreter is effectively a giant `switch` on the instruction being executed.

[goto]: http://eli.thegreenplace.net/2012/07/12/computed-goto-for-efficient-dispatch-tables/

Doing that using an actual `switch` confounds the CPU's [branch
predictor][]—there is basically a single branch point for the entire
interpreter. That quickly saturates the predictor and it just gets confused and
fails to predict anything, which leads to more CPU stalls and pipeline flushes.

[branch predictor]: http://en.wikipedia.org/wiki/Branch_predictor

Using computed gotos gives you a separate branch point at the end of each
instruction. Each gets its own branch prediction, which often succeeds since
some instruction pairs are more common than others. In my rough testing, this
makes a 5-10% performance difference.

### A single-pass compiler

Compile time is a relatively small component of a language's performance: code
only has to be compiled once but a given line of code may be run many times.
However, fast compilation helps with *startup* speed—the time it takes to
get anything up and running. For that, Wren's compiler is quite fast.

It's modeled after Lua's compiler. Instead of tokenizing and then parsing to
create a bunch of AST structures which are then consumed and deallocated by
later phases, it emits code directly during parsing. This means it does minimal
memory allocation during a parse and has very little overhead.

## Why don't other languages do this?

Most of Wren's performance comes from language design decisions. While it's
dynamically *typed* and *dispatched*, classes are relatively statically
*defined*. That makes a lot of things much easier. Other languages have a much
more mutable object model, and cannot change that without breaking lots of
existing code.

Wren's closest sibling, by far, is Lua. Lua is more dynamic than Wren which
makes its job harder. Lua also tries very hard to be compatible across a wide
range of hardware and compilers. If you have a C89 compiler for it, odds are
very good that you can run Lua on it.

Wren cares about compatibility, but it requires C99 or C++98 and IEEE double
precision floats. That may exclude some edge case hardware, but makes things
like NaN tagging, computed gotos, and some other tricks possible.


text:
//
// Note: This example test is leveraging the Mocha test framework.
// Please refer to their documentation on https://mochajs.org/ for help.
//

// The module 'assert' provides assertion methods from node
import * as assert from "assert";

// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from "vscode";
import TestSetup from "./TestSetup";

// Defines a Mocha test suite to group tests of similar kind together
suite("C++ - Parameters Tests", () => {

    const testSetup: TestSetup = new TestSetup("void foo();");

    // Tests
    test("No parameters", () => {
        const result = testSetup.SetLine("void foo();").GetResult();
        assert.equal("/**\n * @brief \n * \n */", result);
    });

    test("Single parameter", () => {
        const result = testSetup.SetLine("void foo(int a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);
    });

    test("Multiple parameters", () => {
        const result = testSetup.SetLine("void foo(int a, int b, int c);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n * @param b \n * @param c \n */", result);
    });

    test("Parameters with numbers in them", () => {
        const result = testSetup.SetLine("void foo(int a1, int b23);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b23 \n */", result);
    });

    test("Reference parameter", () => {
        const result = testSetup.SetLine("void foo(int& a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);
    });

    test("Reference parameter with unsigned interger qualifier", () => {
        const result = testSetup.SetLine("void foo(unsigned int& a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);
    });

    test("Reference parameter with const qualifier", () => {
        const result = testSetup.SetLine("void foo(const int& a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);
    });

    test("Reference parameter with const and interger qualifier", () => {
        const result = testSetup.SetLine("void foo(const unsigned int& a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);
    });

    test("Pointer parameter", () => {
        const result = testSetup.SetLine("void foo(int* a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);
    });

    test("Const parameter", () => {
        let result = testSetup.SetLine("void foo(const int a1);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n */", result);

        result = testSetup.SetLine("void foo(int const a1);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n */", result);
    });

    test("Struct parameter", () => {
        const result = testSetup.SetLine("void foo(int a1, int b23);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b23 \n */", result);
    });

    test("Template parameter", () => {
        const result = testSetup.SetLine("void foo(Matrix<T, N, M> mat);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param mat \n */", result);
    });

    test("Enum parameter", () => {
        const result = testSetup.SetLine("void foo(enum foo bar);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param bar \n */", result);
    });

    test("Const parameter with const pointer to const pointer", () => {
        let result = testSetup.SetLine("void foo(const int * const * const a1);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n */", result);

        result = testSetup.SetLine("void foo(int const * const * const a1);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n */", result);
    });

    test("Fundamental return type with modifiers", () => {
        let result = testSetup.SetLine("void foo(unsigned int a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);

        result = testSetup.SetLine("void foo(unsigned short int a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);

        result = testSetup.SetLine("void foo(signed short a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);

        result = testSetup.SetLine("void foo(long a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);

        result = testSetup.SetLine("void foo(unsigned long long int a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);

        result = testSetup.SetLine("void foo(signed a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);

        result = testSetup.SetLine("void foo(unsigned a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);

        result = testSetup.SetLine("void foo(unsigned char a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);

        result = testSetup.SetLine("void foo(long double a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a \n */", result);

        result = testSetup.SetLine("void foo(long unsigned unsigned_a);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param unsigned_a \n */", result);
    });

    test("Parameter type in namespace", () => {
        const result = testSetup.SetLine("void foo(MyNamespace::Foo a1);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n */", result);
    });

    test("Parameter template type in namespace", () => {
        const result = testSetup.SetLine("void foo(Math::Matrix<A, B, C> mat);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param mat \n */", result);
    });

    test("Parameter template type within templated namespace", () => {
        const result = testSetup.SetLine("void foo(Matrix<A, B, C>::Matrix<A, B, C> mat);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param mat \n */", result);
    });

    test("Parameter type in nested namespacee", () => {
        const result = testSetup.SetLine("void foo( Math::LA::Matrix<A, B, C> mat);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param mat \n */", result);
    });

    test("Parameter with default char literal", () => {
        let result = testSetup.SetLine("void foo(char a1 = 'a', int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(char a1 = u'b', int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(char a1 = u8'b', int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(char a1 = U'a', int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(char a1 = l',', int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(int a1 = 'ab', int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);
    });

    test("Parameter with default string literal", () => {
        let result = testSetup.SetLine("void foo(std::string a1 = \"bar\", int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(std::string a1 = u\"bar, test\", int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(std::string a1 = u8\"bar\", int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(std::string a1 = U\"bar\", int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(std::string a1 = l\"bar\", int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(std::string a1 = R\"(bar\\t\\\")\", int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);
    });

    test("Parameter with default integer literal", () => {
        let result = testSetup.SetLine("void foo(int a1 = 1337, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(int a1 = 01337, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(int a1 = 1337, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(int a1 = 0x0FAB, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(int a1 = 0X0FAB, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(std::uint8_t a1 = 0b110011, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(std::byte a1 = 0B11111, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(long a1 = 1337l, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(long long a1 = 1337ll, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(unsigned long long a1 = 1337ull, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(long a1 = 1337L, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(long long a1 = 1337LL, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(unsigned long long a1 = 1337ULL, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);
    });

    test("Parameter with default floating point literal", () => {
        let result = testSetup.SetLine("void foo(double a1 = 1e10, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(double a1 = 1., int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(double a1 = .1, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(double a1 = 0.1e-1, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(float a1 = 1.0f, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(float a1 = 1.0F, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(long double a1 = 1.0lf, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(long double a1 = 1.0LF, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(double a1 = 0xa.bp10, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);

        result = testSetup.SetLine("void foo(double a1 = 0xa.bp10l, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);
    });

    test("Parameter with default compound literal", () => {
        const result = testSetup.SetLine("void foo(struct Bar a1 = {2, 3}, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);
    });

    test("Parameter with default template function call", () => {
        const result = testSetup.SetLine("void foo(struct Bar a1 = test::baz<3, 2, 5>(23), int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);
    });

    test("Parameter with default user defined literal.", () => {
        const result = testSetup.SetLine("void foo(double a1 = 0xa.bp10l_deg_test, int b);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param a1 \n * @param b \n */", result);
    });

    test("Member pointer as parameter", () => {
        const result = testSetup.SetLine("void test(int foo::* memberPointer);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param memberPointer \n */", result);
    });

    test("Restrict keyword", () => {
        const result = testSetup.SetLine("void some_function(char *restrict buf, const size_t buflen);").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param buf \n * @param buflen \n */", result);
    });

    test("Type as variable name", () => {
        let result = testSetup.SetLine("void MapPoint(double latitude, double longtitude) const;").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param latitude \n * @param longtitude \n */", result);

        result = testSetup.SetLine("void MapPoint(double latitude, double long int floattitude) const;").GetResult();
        assert.equal("/**\n * @brief \n * \n * @param latitude \n * @param floattitude \n */", result);
    });
});


text:
package Concurrency;
import java.util.concurrent.*;
import static Init.Print.*;
/**
 * Created by Defias on 2020/07.
 * Description: 线程中间的协作

 wait() 与 notify()/notifyAll()
 */

//Car上涂蜡和抛光
//抛光需要等待涂蜡完成才能进行
//第2层涂蜡开始,需要等待前一层的抛光完成才能进行
public class Test4_WaitNotify {
    public static void main(String[] args) throws Exception {
        Car car = new Car();
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(new WaxOff(car));  //控制权在两个任务之间来回传递
        exec.execute(new WaxOn(car));

        TimeUnit.SECONDS.sleep(5); // Run for a while...
        exec.shutdownNow(); // Interrupt all tasks
    }
}

class Car {
    private boolean waxOn = false;  //涂蜡抛光处理的状态

    public synchronized void waxed() {   //涂蜡完成
        waxOn = true; // Ready to buff
        notifyAll();
    }

    public synchronized void buffed() { //抛光完成
        waxOn = false; // Ready for another coat of wax
        notifyAll();
    }

    public synchronized void waitForWaxing()  //等待涂蜡完成
            throws InterruptedException {
        while(waxOn == false)
            wait();
    }

    public synchronized void waitForBuffing()   //等待抛光完成
            throws InterruptedException {
        while(waxOn == true)
            wait();
    }
}

//涂蜡
class WaxOn implements Runnable {
    private Car car;
    public WaxOn(Car c) { car = c; }
    public void run() {
        try {
            while(!Thread.interrupted()) {
                printnb("Wax On! ");
                TimeUnit.MILLISECONDS.sleep(200);
                car.waxed();
                car.waitForBuffing();
            }
        } catch(InterruptedException e) {
            print("Exiting via interrupt");
        }
        print("Ending Wax On task");
    }
}

//抛光
class WaxOff implements Runnable {
    private Car car;
    public WaxOff(Car c) { car = c; }
    public void run() {
        try {
            while(!Thread.interrupted()) {
                car.waitForWaxing();
                printnb("Wax Off! ");
                TimeUnit.MILLISECONDS.sleep(200);
                car.buffed();
            }
        } catch(InterruptedException e) {
            print("Exiting via interrupt");
        }
        print("Ending Wax Off task");
    }
}


text:
/* eslint-env mocha */

import expect from 'expect';
import vEmail from '../../src/validators/email.js';

describe('email', () => {
  context('.name', () => {
    it('is "email"', () => {
      expect(vEmail.name).toEqual('email');
    });
  });

  context('.validator', () => {
    it('accepts a valid email', () => {
      expect(vEmail.validator()('test@email.com')).toBe(true);
    });

    it('refuses a wrong email', () => {
      expect(vEmail.validator()('xxxx')).toBe('should be an email');
    });
  });
});


text:
/**
 * Require JS
 */
require.config({
  shim: {
    'tabletop': {
      exports: 'Tabletop'
    }
  },
  paths: {
    'jquery': '../bower_components/jquery/jquery.min',
    'underscore': '../bower_components/underscore/underscore',
    'Backbone': '../bower_components/backbone/backbone',
    'tabletop': '../bower_components/tabletop/src/tabletop',
    'Ractive': '../bower_components/ractive/build/Ractive-legacy.min',
    'Ractive-events-tap': '../bower_components/ractive-events-tap/Ractive-events-tap.min',
    'moment': '../bower_components/moment/min/moment.min',
    'LT': '../dist/legislature-tracker'
  }
});

require(['LT'], function(LT) {
  var app = new LT({
    el: '#legislature-tracker-container',
    imagePath: '../styles/images/',
    tabletopOptions: {
      parameterize: 'http://gs-proxy.herokuapp.com/proxy?url='
    },
    state: 'MN',
    session: '2013-2014',
    OSKey: '49c5c72c157d4b37892ddb52c63d06be',
    eKey: '0AtX8MXQ89fOKdFNaY1Nzc3p6MjJQdll1VEZwSDkzWEE',
    legImageProxy: 'http://i-mage-proxerific.herokuapp.com/resize?size=100x100&url='
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="3.1.0" client="site" method="upgrade">
	<name>Superb Slideshow</name>
	<author>Gopi Ramasamy</author>
	<creationDate>May 2015</creationDate>
	<copyright>(C) 2010 - 2015 www.gopiplus.com, LLC. All rights reserved.</copyright>
	<license>http://www.gnu.org/copyleft/gpl.html GNU/GPL</license>
	<authorEmail>gopiplus@gmail.com</authorEmail>
	<authorUrl>http://www.gopiplus.com/extensions/2011/06/superb-slideshow-joomla-module/</authorUrl>
	<version>3.4</version>
	<description>SUPERB_SLIDESHOW_DESC</description>
	<languages>
		<language tag="en-GB">language/en-GB.mod_superb_slideshow.ini</language>
		<language tag="en-US">language/en-US.mod_superb_slideshow.ini</language>
	</languages>
	<files>
		<filename module="mod_superb_slideshow">mod_superb_slideshow.php</filename>
		<filename>helper.php</filename>
		<filename>index.html</filename>
		<filename>mod_superb_slideshow.xml</filename>
		<folder>tmpl</folder>
		<folder>inc</folder>
		<folder>images</folder>
		<folder>language</folder>
	</files>
	<config>
		<fields name="params">
			<fieldset name="ImageDetails" label="IMAGE_DETAILS">
				<field name="sbs_imgfolder" type="text" size="50" default="modules/mod_superb_slideshow/images" label="IMAGE_FOLDER" description="IMAGE_FOLDER_DESC" />
				<field name="sbs_imglink" type="text" size="50" default="http://www.gopiplus.com" label="IMAGE_LINK" description="IMAGE_LINK_DESC" />
			</fieldset>
			<fieldset name="SlidshowSetting" label="SLIDESHOW_SETTING">
				<field name="sbs_width" type="text" default="150" label="SLIDESHOW_WIDTH" description="SLIDESHOW_WIDTH_DESC" />
				<field name="sbs_height" type="text" default="100" label="SLIDESHOW_HEIGHT" description="SLIDESHOW_HEIGHT_DESC" />
				<field name="sbs_random" type="list" default="N" label="SLIDESHOW_RANDOM" description="SLIDESHOW_RANDOM_DESC">
					<option value="Y">Y</option>
					<option value="N">N</option>
				</field>
				<field name="sbs_pause" type="text" default="2500" label="PAUSE" description="PAUSE_DESC" />
				<field name="sbs_fadeduration" type="text" default="500" label="FADE_DURATION" description="FADE_DURATION_DESC" />
				<field name="sbs_cycles" type="text" default="0" label="CYCLE" description="CYCLE_DESC" />
				<field name="sbs_durationoftrans" type="list" default="always" label="DURATION" description="DURATION_DESC">
					<option value="always">always</option>
					<option value="ondemand">ondemand</option>
					<option value="none">none</option>
				</field>
				<field name="moduleclass_sfx" type="text" default="" label="MODULE" description="MODULE_DESC" />
			</fieldset>
			<fieldset name="JquerySettings" label="JQUERY_SETTING">
				<field name="sbs_jquery" type="list" default="no" label="INCLUDE_JQUERY" description="INCLUDE_JQUERY_DESC">
						<option value="yes">YES</option>
						<option value="no">NO</option>
				</field>
			</fieldset>
		</fields>
	</config>
</extension>


text:
package com.github.javarch.persistence.orm.hibernate.spi.multitenant;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

import com.github.javarch.persistence.HibernateEnviroment;
import com.github.javarch.persistence.exception.CurrentTenantIdentifierResolverException;
import com.github.javarch.support.spring.Profiles;

/**
 * Classe responsavel por buscar o {@link org.hibernate.context.spi.CurrentTenantIdentifierResolver} no
 * pacote informado atraves do atributo {@link HibernateEnviroment}.CURRENT_TENANT_IDENTIFIER_RESOLVER_PACKAGE.
 * Caso não informado, busca através do root package.
 *
 * @author Lucas
 *
 */
@Component
@Profile(Profiles.MULT_TENANT)
public class CurrentTenantIdentifierFinder implements BeanDefinitionRegistryPostProcessor {

	private static final Logger LOGGER = LoggerFactory.getLogger(CurrentTenantIdentifierFinder.class);

	@Autowired
	private Environment env;

	@Override
	public void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory) throws BeansException {	}

	@Override
	public void postProcessBeanDefinitionRegistry( BeanDefinitionRegistry registry) throws BeansException {

		String connectionProvidersPackage = env.getProperty( HibernateEnviroment.CURRENT_TENANT_IDENTIFIER_RESOLVER_PACKAGE , "");
		LOGGER.debug("Buscando @CurrentTenantIdentifierResolver no pacote {}", connectionProvidersPackage );

		ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
		scanner.addIncludeFilter( new AnnotationTypeFilter(CurrentTenantIdentifierResolver.class) );

		Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents( connectionProvidersPackage );
		if ( beanDefinitions.isEmpty() ){
			Set<BeanDefinition> defaultBeanDefinition = scanner.findCandidateComponents( "com.github.javarch.persistence.orm.hibernate.spi.multitenant" );
			registrarBeanDefinitions(registry, defaultBeanDefinition);
		}else {
			registrarBeanDefinitions(registry, beanDefinitions);
		}

	}

	private void registrarBeanDefinitions(BeanDefinitionRegistry registry, Set<BeanDefinition> beanDefinitions) {
		if ( beanDefinitions.isEmpty() || beanDefinitions.size() > 1 ){
			throw new CurrentTenantIdentifierResolverException();
		}

		for (BeanDefinition bd : beanDefinitions ){
			LOGGER.debug("Encontrado CurrentTenantIdentifierResolver: {}" ,bd.getBeanClassName());
			if ( !registry.containsBeanDefinition( bd.getBeanClassName() ) ){
				String beanName = bd.getBeanClassName();
				registry.registerBeanDefinition( beanName , bd);
			}
		}
	}

}


text:
using UnityEngine;
using DataLoad;

public class GameLauncher : MonoBehaviour
{
    private void Awake()
    {
        GameObject obj = new GameObject("UIRoot");
        DontDestroyOnLoad(obj);
    }

    private void Start()
    {
        DictManager.Instance.Initialze("Dicts");
    }
}


text:
Accordion = Class.create();
Accordion.prototype = {
    initialize: function(elem, clickableEntity, checkAllow) {
        this.container = $(elem);
        this.checkAllow = checkAllow || false;
        this.disallowAccessToNextSections = false;
        this.sections = $$('#' + elem + ' .section');
        this.currentSection = false;
        var headers = $$('#' + elem + ' .section ' + clickableEntity);
        headers.each(function(header) {
            Event.observe(header,'click',this.sectionClicked.bindAsEventListener(this));
        }.bind(this));
    },

    sectionClicked: function(event) {
        this.openSection($(Event.element(event)).up('.section'));
        Event.stop(event);
    },

    openSection: function(section) {
        var section = $(section);

        // Check allow
        if (this.checkAllow && !Element.hasClassName(section, 'allow')){
            return;
        }

        if(section.id != this.currentSection) {
            this.closeExistingSection();
            this.currentSection = section.id;
            $(this.currentSection).addClassName('active');
            var contents = Element.select(section, '.a-item');
            contents[0].show();
            //Effect.SlideDown(contents[0], {duration:.2});

            if (this.disallowAccessToNextSections) {
                var pastCurrentSection = false;
                for (var i=0; i<this.sections.length; i++) {
                    if (pastCurrentSection) {
                        Element.removeClassName(this.sections[i], 'allow')
                    }
                    if (this.sections[i].id==section.id) {
                        pastCurrentSection = true;
                    }
                }
            }
        }
    },

    closeSection: function(section) {
        $(section).removeClassName('active');
        var contents = Element.select(section, '.a-item');
        contents[0].hide();
        //Effect.SlideUp(contents[0]);
    },

    openNextSection: function(setAllow){
        for (section in this.sections) {
            var nextIndex = parseInt(section)+1;
            if (this.sections[section].id == this.currentSection && this.sections[nextIndex]){
                if (setAllow) {
                    Element.addClassName(this.sections[nextIndex], 'allow')
                }
                this.openSection(this.sections[nextIndex]);
                return;
            }
        }
    },

    openPrevSection: function(setAllow){
        for (section in this.sections) {
            var prevIndex = parseInt(section)-1;
            if (this.sections[section].id == this.currentSection && this.sections[prevIndex]){
                if (setAllow) {
                    Element.addClassName(this.sections[prevIndex], 'allow')
                }
                this.openSection(this.sections[prevIndex]);
                return;
            }
        }
    },

    closeExistingSection: function() {
        if(this.currentSection) {
            this.closeSection(this.currentSection);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Base application theme -->
    <style name="BaseAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!--Platform compatibility them here. This is specific for OS versions that will be
            using this file (API 16-20 for this app).-->
    </style>
    <style name="AppTheme" parent="BaseAppTheme">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="colorButtonNormal">@color/colorAccent</item>
    </style>
</resources>


text:
package com.ra4king.circuitsim.simulator.components.memory;

import com.ra4king.circuitsim.simulator.CircuitState;
import com.ra4king.circuitsim.simulator.Component;
import com.ra4king.circuitsim.simulator.Utils;
import com.ra4king.circuitsim.simulator.WireValue;
import com.ra4king.circuitsim.simulator.WireValue.State;

/**
 * @author Roi Atalla
 */
public class SRFlipFlop extends Component {
	public static final int PORT_S = 0;
	public static final int PORT_R = 1;
	public static final int PORT_CLOCK = 2;
	public static final int PORT_ENABLE = 3;
	public static final int PORT_PRESET = 4;
	public static final int PORT_CLEAR = 5;
	public static final int PORT_Q = 6;
	public static final int PORT_QN = 7;

	public SRFlipFlop(String name) {
		super(name, Utils.getFilledArray(8, 1));
	}

	private void pushValue(CircuitState state, State bit) {
		state.putComponentProperty(this, bit);
		state.pushValue(getPort(PORT_Q), new WireValue(1, bit));
		state.pushValue(getPort(PORT_QN), new WireValue(1, bit.negate()));
	}

	@Override
	public void init(CircuitState state, Object lastProperty) {
		pushValue(state, lastProperty == null ? State.ZERO : (State)lastProperty);
	}

	@Override
	public void valueChanged(CircuitState state, WireValue value, int portIndex) {
		if(portIndex == PORT_Q || portIndex == PORT_QN) {
			return;
		}

		State clear = state.getLastReceived(getPort(PORT_CLEAR)).getBit(0);
		State preset = state.getLastReceived(getPort(PORT_PRESET)).getBit(0);
		State enable = state.getLastReceived(getPort(PORT_ENABLE)).getBit(0);

		if(clear == State.ONE) {
			pushValue(state, State.ZERO);
		} else if(preset == State.ONE) {
			pushValue(state, State.ONE);
		} else if(enable != State.ZERO && portIndex == PORT_CLOCK && value.getBit(0) == State.ONE) {
			State s = state.getLastReceived(getPort(PORT_S)).getBit(0);
			State r = state.getLastReceived(getPort(PORT_R)).getBit(0);

			if(s == State.ONE && r == State.ZERO) {
				pushValue(state, State.ONE);
			} else if(r == State.ONE && s == State.ZERO) {
				pushValue(state, State.ZERO);
			}
		}
	}
}


text:
class Transform:
	"""
	This class represents a single modification to the data set, designed
	to be applied in descending order by line number.  The operation determines
	where the new data will be applied, and how.
	"""

	lineum = -1
	oper = "noop"
	data = ""

	def __init__(self, linenum = -1, oper = "noop", data = ""):
		self.linenum = linenum
		self.oper = oper
		self.data = data

	def __str__(self):
		return "Transform: (line: %d, oper: %s, data: %s)" % (self.linenum, self.oper, self.data)


text:
package org.synyx.urlaubsverwaltung.person.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.synyx.urlaubsverwaltung.department.DepartmentService;
import org.synyx.urlaubsverwaltung.person.Person;
import org.synyx.urlaubsverwaltung.person.PersonService;
import org.synyx.urlaubsverwaltung.person.UnknownPersonException;
import org.synyx.urlaubsverwaltung.security.SessionService;

import static org.synyx.urlaubsverwaltung.person.web.PersonPermissionsMapper.mapToPersonPermissionsDto;
import static org.synyx.urlaubsverwaltung.person.web.PersonPermissionsMapper.merge;
import static org.synyx.urlaubsverwaltung.security.SecurityRules.IS_OFFICE;

@Controller
@RequestMapping("/web")
public class PersonPermissionsViewController {

    private final PersonService personService;
    private final DepartmentService departmentService;
    private final PersonPermissionsDtoValidator validator;
    private final SessionService sessionService;

    @Autowired
    public PersonPermissionsViewController(PersonService personService, DepartmentService departmentService, PersonPermissionsDtoValidator validator, SessionService sessionService) {
        this.personService = personService;
        this.departmentService = departmentService;
        this.validator = validator;
        this.sessionService = sessionService;
    }

    @PreAuthorize(IS_OFFICE)
    @GetMapping("/person/{personId}/edit")
    @Deprecated(forRemoval = true)
    public String redirectFromEditToPermissions(@PathVariable("personId") Integer personId) {
        return "redirect:/web/person/" + personId + "/permissions";
    }

    @PreAuthorize(IS_OFFICE)
    @GetMapping("/person/{personId}/permissions")
    public String showPersonPermissionsAndNotifications(@PathVariable("personId") Integer personId, Model model) throws UnknownPersonException {

        final Person person = personService.getPersonByID(personId).orElseThrow(() -> new UnknownPersonException(personId));

        model.addAttribute("person", mapToPersonPermissionsDto(person));
        model.addAttribute("departments", departmentService.getManagedDepartmentsOfDepartmentHead(person));
        model.addAttribute("secondStageDepartments", departmentService.getManagedDepartmentsOfSecondStageAuthority(person));

        return "thymeleaf/person/person_permissions";
    }

    @PreAuthorize(IS_OFFICE)
    @PostMapping("/person/{personId}/permissions")
    public String editPersonPermissionsAndNotifications(@PathVariable("personId") Integer personId,
                                                        @ModelAttribute("person") PersonPermissionsDto personPermissionsDto, Errors errors,
                                                        RedirectAttributes redirectAttributes) throws UnknownPersonException {

        validator.validate(personPermissionsDto, errors);

        if (errors.hasErrors()) {
            return "thymeleaf/person/person_permissions";
        }

        final Person person = personService.getPersonByID(personId).orElseThrow(() -> new UnknownPersonException(personId));
        personService.update(merge(person, personPermissionsDto));

        sessionService.markSessionToReloadAuthorities(person.getUsername());

        redirectAttributes.addFlashAttribute("updateSuccess", true);
        return "redirect:/web/person/" + personId;
    }
}


text:
<?php

namespace humhub\modules\notification;

use humhub\modules\notification\models\Notification;

/**
 * Events provides callbacks for all defined module events.
 *
 * @author luke
 */
class Events extends \yii\base\Object
{

    /**
     * On User delete, also delete all posts
     *
     * @param type $event
     */
    public static function onUserDelete($event)
    {
        foreach (Notification::findAll(['user_id' => $event->sender->id]) as $notification) {
            $notification->delete();
        }

        foreach (Notification::findAll(['originator_user_id' => $event->sender->id]) as $notification) {
            $notification->delete();
        }

        return true;
    }

    /**
     * On workspace deletion make sure to delete all posts
     *
     * @param type $event
     */
    public static function onSpaceDelete($event)
    {

        foreach (Notification::findAll(array('space_id' => $event->sender->id)) as $notification) {
            $notification->delete();
        }
    }

    /**
     * Callback to validate module database records.
     *
     * @param Event $event
     */
    public static function onIntegrityCheck($event)
    {

        $integrityChecker = $event->sender;
        $integrityChecker->showTestHeadline("Notification Module (" . Notification::find()->count() . " entries)");

        foreach (Notification::find()->joinWith(['space', 'user'])->each() as $notification) {

            // Check if Space still exists
            if ($notification->space_id != "" && $notification->space == null) {
                if ($integrityChecker->showFix("Deleting notification id " . $notification->id . " workspace seems to no longer exist!")) {
                    $notification->delete();
                }
            }

            // Check if source object exists when defined
            if ($notification->source_class != "" && $notification->getSourceObject() == null) {
                if ($integrityChecker->showFix("Deleting notification id " . $notification->id . " source class set but seems to no longer exist!")) {
                    $notification->delete();
                }
            }

            // Check if target user exists
            if ($notification->user == null) {
                if ($integrityChecker->showFix("Deleting notification id " . $notification->id . " target user seems to no longer exist!")) {
                    $notification->delete();
                }
            }

            // Check if target user exists
            if (!class_exists($notification->class)) {
                if ($integrityChecker->showFix("Deleting notification id " . $notification->id . " without valid class!")) {
                    $notification->delete();
                }
            }

            // Check if module id is set
            if ($notification->module == "") {
                if ($integrityChecker->showFix("Deleting notification id " . $notification->id . " without valid module!")) {
                    $notification->delete();
                }
            }
        }
    }

    /**
     * On run of the cron, do some cleanup stuff.
     * We delete all notifications which are older than 2 month and are seen.
     *
     * @param type $event
     */
    public static function onCronDailyRun($event)
    {
        $controller = $event->sender;

        $controller->stdout("Deleting old notifications... ");
        /**
         * Delete seen notifications which are older than 2 months
         */
        $deleteTime = time() - (60 * 60 * 24 * 31 * 2); // Notifcations which are older as ~ 2 Months
        foreach (Notification::find()->where(['seen' => 1])->andWhere(['<', 'created_at', date('Y-m-d', $deleteTime)])->all() as $notification) {
            $notification->delete();
        }
        $controller->stdout('done.' . PHP_EOL, \yii\helpers\Console::FG_GREEN);
    }

    public static function onActiveRecordDelete($event)
    {
        models\Notification::deleteAll([
            'source_class' => $event->sender->className(),
            'source_pk' => $event->sender->getPrimaryKey(),
        ]);
    }

}


text:
const AbsoluteTimeControl = require('../common/timecontrol/absolute');
const { GameEngine } = require('../common/engine');
const PuyoExporter = require('../common/puyo/export');

class PuyoDuelTimeControl extends AbsoluteTimeControl {
  constructor() {
    const numPlayers = 2;
    const maxTime = 60;

    super({ numPlayers, maxTime });
  }

  makeMove(event) {
    if (event.type === 'addPuyos') {
      super.makeMove(event.player);
    }
  }

  step(engine) {
    this.players.map(player => player.index)
      .filter(player => !engine.callStepper('canPlay', { player }))
      .forEach(player => super.makeMove(player));
  }
}

class GameMode {
  get engineOptions() {
    return {
      stepper: 'panelLeagueVs',
      width: 6,
      height: 12,
      flashTime: 40,
      floatTime: 10,
      swapTime: 3,
      garbageFlashTime: 2,
      blockTypes: [
        'red',
        'green',
        'blue',
        'yellow',
        'violet',
        'navy',
      ],
    };
  }

  get timeControlClass() {
    return null;
  }

  get name() {
    return 'panel-league:duel';
  }

  get maximumPlayerCount() {
    return 2;
  }

  get frameRate() {
    return 30;
  }

  shouldStep(game) {
    return true;
  }

  shouldSendClock(game) {
    return (game.engine.time % 10 === 0);
  }

  shouldStartGame(game) {
    return game.playerCount === this.maximumPlayerCount;
  }

  shouldTerminateGame(game) {
    return game.playerCount < this.maximumPlayerCount;
  }

  shouldStopGame(game) {
    return !game.playerCount;
  }

  shouldRebase(game) {
    return false;
  }

  export(game) {
    return game.engine.serialize();
  }

  import(game, data) {
    game.engine = GameMode.unserialize(data);
  }
}

class SandboxMode extends GameMode {
  get engineOptions() {
    return {
      stepper: 'panelLeagueScoring',
      width: 12,
      height: 12,
      flashTime: 40,
      floatTime: 10,
      swapTime: 3,
      blockTypes: [
        'red',
        'green',
        'blue',
        'yellow',
        'violet',
        'navy',
      ],
    };
  }

  get name() {
    return 'panel-league:sandbox';
  }

  get maximumPlayerCount() {
    return Number.MAX_VALUE;
  }

  shouldStartGame() {
    return true;
  }

  shouldTerminateGame() {
    return false;
  }

  shouldStopGame() {
    return false;
  }

  shouldRebase(game) {
    return (game.engine.time % 600 === 0);
  }
}

class PuyoEndlessMode extends GameMode {
  get engineOptions() {
    return { stepper: 'puyo:endless' };
  }

  get name() {
    return 'puyo:endless';
  }

  get maximumPlayerCount() {
    return 1;
  }

  get frameRate() {
    return 3;
  }

  shouldStep(game) {
    return game.engine.callStepper('canStep');
  }

  shouldSendClock() {
    return true;
  }

  export(game) {
    return PuyoExporter.exportEndless(game.engine);
  }

  import(game, data) {
    game.engine = PuyoExporter.importEndless(data);
  }
}

class PuyoDuelMode extends GameMode {
  get engineOptions() {
    return { stepper: 'puyo:duel' };
  }

  get timeControlClass() {
    return PuyoDuelTimeControl;
  }

  get name() {
    return 'puyo:duel';
  }

  get maximumPlayerCount() {
    return 2;
  }

  get frameRate() {
    return 5;
  }

  shouldStep(game) {
    return game.engine.callStepper('canStep');
  }

  shouldSendClock() {
    return true;
  }

  export(game) {
    return PuyoExporter.exportDuel(game.engine);
  }

  import(game, data) {
    game.engine = PuyoExporter.importDuel(data);
  }
}

const gameModeFactory = ((name) => {
  switch (name) {
    case 'panel-league:duel':
      return new GameMode();
    case 'panel-league:sandbox':
      return new SandboxMode();
    case 'puyo:endless':
      return new PuyoEndlessMode();
    case 'puyo:duel':
      return new PuyoDuelMode();
    default:
      throw new Error(`Unrecognized game mode: ${name}`);
  }
});

module.exports = gameModeFactory;


text:
$(document).ready(function() {
    $('#datatables').DataTable({
        responsive: true
    });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/web_view_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.PostViewActivity"
    />


text:
package testpackage1;

@FunctionalInterface
public interface LambdaTestInf {
  int getLength(String s);
}


text:
"""Identity v3 unscoped SAML auth action implementations.

The first step of federated auth is to fetch an unscoped token. From there,
the user can list domains and projects they are allowed to access, and request
a scoped token."""

from osc_lib.command import command
from osc_lib import utils

from openstackclient.i18n import _

class ListAccessibleDomains(command.Lister):
    _description = _("List accessible domains")

    def take_action(self, parsed_args):
        columns = ('ID', 'Enabled', 'Name', 'Description')
        identity_client = self.app.client_manager.identity
        data = identity_client.federation.domains.list()
        return (columns,
                (utils.get_item_properties(
                    s, columns,
                    formatters={},
                ) for s in data))

class ListAccessibleProjects(command.Lister):
    _description = _("List accessible projects")

    def take_action(self, parsed_args):
        columns = ('ID', 'Domain ID', 'Enabled', 'Name')
        identity_client = self.app.client_manager.identity
        data = identity_client.federation.projects.list()
        return (columns,
                (utils.get_item_properties(
                    s, columns,
                    formatters={},
                ) for s in data))


text:
package com.publicuhc.ultrahardcore.core.features;

import com.publicuhc.pluginframework.shaded.inject.Singleton;
import com.publicuhc.ultrahardcore.api.UHCFeature;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.CreatureSpawnEvent;

/**
 * WitchSpawns
 * <p/>
 * Enabled: Disables witch spawning
 * Disabled: Nothing
 */
@Singleton
public class WitchSpawnsFeature extends UHCFeature
{

    /**
     * Whenever a creature spawns
     *
     * @param ese the creaturespawnevent
     */
    @EventHandler
    public void onCreatureSpawnEvent(CreatureSpawnEvent ese)
    {
        if(isEnabled() && ese.getSpawnReason() == CreatureSpawnEvent.SpawnReason.NATURAL && ese.getEntity().getType() == EntityType.WITCH) {
            ese.setCancelled(true);
        }
    }

    @Override
    public String getFeatureID()
    {
        return "WitchSpawns";
    }

    @Override
    public String getDescription()
    {
        return "Disables natural witch spawns";
    }
}


text:
<?php

namespace Grav\Common\Page\Medium;

/**
 * Interface RenderableInterface
 * @package Grav\Common\Page\Medium
 */
interface RenderableInterface
{
    /**
     * Return HTML markup from the medium.
     *
     * @param string|null $title
     * @param string|null $alt
     * @param string|null $class
     * @param string|null $id
     * @param bool $reset
     * @return string
     */
    public function html($title = null, $alt = null, $class = null, $id = null, $reset = true);

    /**
     * Return Parsedown Element from the medium.
     *
     * @param string|null $title
     * @param string|null $alt
     * @param string|null $class
     * @param string|null $id
     * @param bool $reset
     * @return array
     */
    public function parsedownElement($title = null, $alt = null, $class = null, $id = null, $reset = true);
}


text:
from nflpool.viewmodels.viewmodelbase import ViewModelBase

class StandingsViewModel(ViewModelBase):
    def __init__(self):
        self.first_name = None
        self.last_name = None
        self.total_points = None
        self.player_id = None
        self.is_get = True

    def from_dict(self, data_dict):
        self.first_name = data_dict.get("first_name")
        self.last_name = data_dict.get("last_name")
        self.total_points = data_dict.get("total_points")
        self.player_id = data_dict.get("id")


text:
local autopairs_setup, autopairs = pcall(require, "nvim-autopairs")
if not autopairs_setup then
	return
end

-- configure autopairs
autopairs.setup({
	check_ts = true, -- enable treesitter
	ts_config = {
		lua = { "string" }, -- don't add pairs in lua string treesitter nodes
		javascript = { "template_string" }, -- don't add pairs in javscript template_string treesitter nodes
		java = false, -- don't check treesitter on java
	},
})

-- import nvim-autopairs completion functionality safely
local cmp_autopairs_setup, cmp_autopairs = pcall(require, "nvim-autopairs.completion.cmp")
if not cmp_autopairs_setup then
	return
end

-- import nvim-cmp plugin safely (completions plugin)
local cmp_setup, cmp = pcall(require, "cmp")
if not cmp_setup then
	return
end

-- make autopairs and completion work together
cmp.event:on("confirm_done", cmp_autopairs.on_confirm_done())


text:
<?php

namespace SimpleNote\WebAppBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SimpleNoteWebAppBundle extends Bundle
{
}


text:
ALTER TABLE vehicle_journeys DROP COLUMN IF EXISTS referential_id;
ALTER TABLE vehicle_journeys ADD COLUMN referential_slug text NOT NULL;

-- +migrate Down
-- SQL section 'Down' is executed when this migration is rolled back

ALTER TABLE vehicle_journeys DROP COLUMN IF EXISTS referential_slug;
ALTER TABLE vehicle_journeys ADD COLUMN referential_id uuid NOT NULL;


text:
using System.Reflection;

namespace Eventual.UnitTests
{
    public static class EventualUnitTestsAssembly
    {
        public static Assembly Assembly => typeof(EventualUnitTestsAssembly).GetTypeInfo().Assembly;
    }
}