text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit8dbdcf14844375902d870389bcfe5718::getLoader();


text:
FROM alpine:3.3

ADD ./atlas-meta /usr/local/bin/

ENTRYPOINT ["atlas-meta"]

redpajama_set_name: RedPajamaGithub


text:
<?php
/* @var $this SurveyQuestionController */
/* @var $model SurveyQuestion */
/* @var $form CActiveForm */
?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'action'=>Yii::app()->createUrl($this->route),
	'method'=>'get',
)); ?>

		<?php echo $form->label($model,'id'); ?>
		<?php echo $form->textField($model,'id'); ?>

		<?php echo $form->label($model,'survey_ID'); ?>
		<?php echo $form->textField($model,'survey_ID'); ?>

		<?php echo $form->label($model,'order_number'); ?>
		<?php echo $form->textField($model,'order_number'); ?>

		<?php echo $form->label($model,'type'); ?>
		<?php echo $form->textField($model,'type'); ?>

		<?php echo $form->label($model,'text'); ?>
		<?php echo $form->textField($model,'text',array('size'=>60,'maxlength'=>1000)); ?>

		<?php echo CHtml::submitButton('Search'); ?>

<?php $this->endWidget(); ?>


text:
'use strict';

var getWrappedService = require('../util/api-gateway-retry-wrapper');
var awsApiGateway = getWrappedService({ apiVersion: '2015-07-09' });
var async = require('async');
var Constants = require('../constants');
var logger = require('../util/logger');

var pub = {};

/*
    Due to unexpected issues during method creation a slight delay between operations was introduced.
    The issue at hand is that Amazon responds with ConcurrentModificationsException.
    After discussions with the AWS support it was deemed best to add a slight delay to ensure that each call
    was completed on the server side before executing the next request.
 */
pub.PUT_METHOD_STEP_DELAY_MILLIS = 100;

pub.getForResponse = function getForResponse(restApiId, resourceId, httpMethod, callback) {
    var params = {
        restApiId: restApiId,
        resourceId: resourceId,
        httpMethod: httpMethod
    };
    awsApiGateway.getMethod(params, function (error, apiMethod) {
        if (error) {
            logger.log('Error ApiMethodService::getForResponse', { error: error, params: params });
            return callback(error);
        }
        // Remove irrelevant data from response to reduce the size of the response body (CFN has a 4K limit on the response)
        delete apiMethod.methodResponses;
        delete apiMethod.methodIntegration.integrationResponses;
        delete apiMethod.methodIntegration.requestTemplates;
        delete apiMethod.requestModels;
        return callback(error, apiMethod);
    });
};

/* eslint max-nested-callbacks: 0 */
pub.createMethod = function createMethod(parameters, callback) {
    pub.getCorsOrigin(parameters.params, function (getError, corsOrigin) {
        if (getError) {
            return callback(getError);
        }

        parameters.params.responses = rebuildResponses(parameters.params.responses);
        if (corsOrigin) {
            parameters.params = appendCorsProperties(parameters.params, corsOrigin);
        }

        putMethod(parameters.params, function (putError, apiMethod) {
            if (putError) {
                return callback(putError);
            }
            createIntegration(parameters.params, function (integrationError) {
                if (integrationError) {
                    return callback(integrationError, apiMethod);
                }
                createResponses(parameters.params, function (responseError) {
                    if (responseError) {
                        return callback(responseError, apiMethod);
                    }
                    createIntegrationResponses(parameters.params, function (integrationResponseError) {
                        if (integrationResponseError) {
                            return callback(integrationResponseError, apiMethod);
                        }
                        return callback(undefined, apiMethod);
                    });
                });
            });
        });
    });
};

pub.getMethod = function getMethod(restApiId, resourceId, httpMethod, callback) {
    var params = {
        restApiId: restApiId,
        resourceId: resourceId,
        httpMethod: httpMethod
    };
    awsApiGateway.getMethod(params, function (error, method) {
        if (error && error.code !== 'NotFoundException') {
            logger.log('Error ApiMethodService::getMethod', { error: error, params: params });
            return callback(error);
        }
        callback(undefined, method);
    });
};

pub.getCorsOrigin = function getCorsOrigin(parameters, callback) {
    // If we are creating an OPTIONS method we don't need to get the origin
    if (parameters.method.httpMethod === Constants.CORS_OPTIONS_METHOD) {
        return callback();
    }

    pub.getMethod(parameters.restApiId, parameters.resourceId, Constants.CORS_OPTIONS_METHOD, function (error, method) {
        if (error) {
            return callback(error);
        }

        var origin;
        if (method && method.methodIntegration && method.methodIntegration.integrationResponses) {
            /* eslint max-len: 0 */
            var allowedMethods = method.methodIntegration.integrationResponses[Constants.CORS_STATUS_CODE].responseParameters['method.response.header.' + Constants.AWS_HEADER_PATHS.ALLOW_METHODS];
            if (allowedMethods.indexOf(parameters.method.httpMethod) > -1) {
                /* eslint max-len: 0 */
                origin = method.methodIntegration.integrationResponses[Constants.CORS_STATUS_CODE].responseParameters['method.response.header.' + Constants.AWS_HEADER_PATHS.ALLOW_ORIGIN];
            }
        }
        callback(error, origin);
    });
};

pub.deleteMethod = function deleteMethod(restApiId, resourceId, httpMethod, callback) {
    var params = {
        restApiId: restApiId,
        resourceId: resourceId,
        httpMethod: httpMethod
    };
    awsApiGateway.deleteMethod(params, function (error) {
        if (error && error.code !== 'NotFoundException' && error.code !== 'MissingRequiredParameter') {
            logger.log('Error ApiMethodService::deleteMethod', { error: error, params: params });
            return callback(error);
        }
        return callback();
    });
};

module.exports = pub;

function putMethod(parameters, callback) {
    var params = {
        restApiId: parameters.restApiId,
        resourceId: parameters.resourceId,
        httpMethod: parameters.method.httpMethod,
        authorizationType: parameters.method.authorizationType,
        apiKeyRequired: parameters.method.apiKeyRequired === 'true',
        requestModels: parameters.method.requestModels
    };

    if (parameters.method.authorizationType === 'CUSTOM') {
        params.authorizerId = parameters.method.authorizerId;
    }

    if (parameters.method.parameters) {
        params.requestParameters = {};
        for (var i = 0; i < parameters.method.parameters.length; i++) {
            params.requestParameters['method.request.' + parameters.method.parameters[i]] = true;
        }
    }
    awsApiGateway.putMethod(params, function (error, apiMethod) {
        if (error) {
            logger.log('Error ApiMethodService::putMethod', { error: error, params: params });
        }
        setTimeout(function () {
            return callback(error, apiMethod);
        }, pub.PUT_METHOD_STEP_DELAY_MILLIS);
    });
}

function createIntegration(parameters, callback) {
    var params = {
        restApiId: parameters.restApiId,
        resourceId: parameters.resourceId,
        httpMethod: parameters.method.httpMethod,
        type: parameters.integration.type,
        credentials: parameters.integration.credentials,
        passthroughBehavior: parameters.integration.passthroughBehavior,
        integrationHttpMethod: parameters.integration.httpMethod,
        requestParameters: parameters.integration.requestParameters,
        requestTemplates: stringifyIntegrationRequestTemplates(parameters.integration.requestTemplates),
        uri: parameters.integration.uri
    };
    if (parameters.integration.cacheKeyParameters) {
        params.cacheKeyParameters = parameters.integration.cacheKeyParameters;
        params.cacheNamespace = parameters.integration.cacheNamespace;
    }
    awsApiGateway.putIntegration(params, function (error) {
        if (error) {
            logger.log('Error ApiMethodService::createIntegration', { error: error, params: params });
        }
        setTimeout(function () {
            return callback(error);
        }, pub.PUT_METHOD_STEP_DELAY_MILLIS);
    });

    function stringifyIntegrationRequestTemplates(requestTemplates) {
        /* istanbul ignore else */
        if (requestTemplates) {
            for (var integrationContentType in requestTemplates) {
                /* istanbul ignore else */
                if (requestTemplates.hasOwnProperty(integrationContentType)) {
                    if (typeof requestTemplates[integrationContentType] === 'object') {
                        requestTemplates[integrationContentType] = JSON.stringify(requestTemplates[integrationContentType]);
                    }
                }
            }
        }
        return requestTemplates;
    }
}

function createResponses(parameters, callback) {
    var createdResponses = [];
    async.mapSeries(parameters.responses, function (response, asyncCallback) {
        // Response already created, skip
        /* istanbul ignore if */
        if (createdResponses.indexOf(response.statusCode) > -1) {
            return asyncCallback();
        }

        var params = {
            restApiId: parameters.restApiId,
            resourceId: parameters.resourceId,
            httpMethod: parameters.method.httpMethod,
            statusCode: response.statusCode,
            responseModels: response.responseModels
        };

        /* istanbul ignore else */
        if (response.headers) {
            var headers = Object.getOwnPropertyNames(response.headers);
            params.responseParameters = {};
            for (var i = 0; i < headers.length; i++) {
                params.responseParameters['method.response.header.' + headers[i]] = true;
            }
        }

        awsApiGateway.putMethodResponse(params, function (error) {
            if (error) {
                logger.log('Error ApiMethodService::createResponses', { error: error, params: params });
            }
            createdResponses.push(response.statusCode);
            asyncCallback(error);
        });
    }, function (error) {
        setTimeout(function () {
            return callback(error);
        }, pub.PUT_METHOD_STEP_DELAY_MILLIS);
    });
}

function createIntegrationResponses(parameters, callback) {
    async.mapSeries(parameters.responses, function (response, asyncCallback) {
        var params = {
            restApiId: parameters.restApiId,
            resourceId: parameters.resourceId,
            httpMethod: parameters.method.httpMethod,
            statusCode: response.statusCode,
            selectionPattern: response.selectionPattern,
            responseTemplates: response.responseTemplates
        };

        /* istanbul ignore else */
        if (response.headers) {
            var headers = Object.getOwnPropertyNames(response.headers);
            params.responseParameters = {};
            for (var i = 0; i < headers.length; i++) {
                params.responseParameters['method.response.header.' + headers[i]] = response.headers[headers[i]];
            }
        }
        awsApiGateway.putIntegrationResponse(params, function (error, data) {
            if (error) {
                logger.log('Error ApiMethodService::createIntegrationResponses', { error: error, params: params });
            }
            asyncCallback(error, data);
        });
    }, function (error) {
        setTimeout(function () {
            return callback(error);
        }, pub.PUT_METHOD_STEP_DELAY_MILLIS);
    });
}

function appendCorsProperties(parameters, corsOrigin) {
    for (var i = 0; i < parameters.responses.length; i++) {
        if (!parameters.responses[i].headers) {
            parameters.responses[i].headers = {};
        }
        parameters.responses[i].headers[Constants.AWS_HEADER_PATHS.ALLOW_ORIGIN] = corsOrigin;
    }
    return parameters;
}

/* eslint max-depth: 0 */
function rebuildResponses(responses) {
    var rebuiltResponses = [];
    if (responses) {
        for (var responseKey in responses) {
            /* istanbul ignore else */
            if (responses.hasOwnProperty(responseKey)) {
                var response = responses[responseKey];
                if (responseKey !== 'default') {
                    response.selectionPattern = responseKey;
                }

                if (response.responseTemplates) {
                    for (var responseContentType in response.responseTemplates) {
                        /* istanbul ignore else */
                        if (response.responseTemplates.hasOwnProperty(responseContentType)) {
                            if (typeof response.responseTemplates[responseContentType] === 'object') {
                                response.responseTemplates[responseContentType] = JSON.stringify(response.responseTemplates[responseContentType]);
                            }
                        }
                    }
                }
                rebuiltResponses.push(response);
            }
        }
    }
    return rebuiltResponses;
}


text:
package jef.database.wrapper.clause;

import java.util.Collections;
import java.util.List;

import jef.common.Entry;
import jef.database.wrapper.populator.ColumnDescription;
import jef.database.wrapper.populator.ColumnMeta;
import jef.http.client.support.CommentEntry;
import jef.tools.StringUtils;

public class OrderClause {
	@SuppressWarnings("unchecked")
	public static final OrderClause DEFAULT=new OrderClause("",Collections.EMPTY_LIST);

	//其实现代码和排序
	private List<Entry<String,Boolean>> asSelect;
	private String sql;
	public OrderClause(String sql, List<Entry<String,Boolean>> rs) {
		this.sql=sql;
		this.asSelect =rs;
	}
	public List<Entry<String, Boolean>> getAsSelect() {
		return asSelect;
	}

	public String getSql() {
		return sql;
	}
	public void setSql(String sql) {
		this.sql = sql;
	}
	@Override
	public String toString() {
		return sql;
	}
	public boolean isNotEmpty(){
		return !asSelect.isEmpty();
	}

	/**
	 * 当多库查询时,通过解析需要排序的列在结果集中的位置,计算重排序策略。
	 * @param select
	 * @param columns
	 * @return
	 */
	public InMemoryOrderBy parseAsSelectOrder(SelectPart select,ColumnMeta columns) {
		List<CommentEntry> selectItems=select.getEntries();
		int[] orders = new int[asSelect.size()];
		boolean[] orderAsc = new boolean[asSelect.size()];

		for (int i = 0; i < asSelect.size(); i++) {
			Entry<String, Boolean> order = asSelect.get(i);
			String alias = findAlias(order.getKey(), selectItems);
			if (alias == null) {
				throw new IllegalArgumentException("The order field " + order.getKey() + " does not selected in SQL!");
			}
			// 可能为null
			ColumnDescription selectedColumn = columns.getByUpperName(alias.toUpperCase());
			if (selectedColumn == null) {
				throw new IllegalArgumentException("The order field " + alias + " does not found in this Query!");
			}
			orders[i] = selectedColumn.getN();//
			orderAsc[i] = order.getValue();
		}
		return new InMemoryOrderBy(orders,orderAsc);
	}

	private String findAlias(String key, List<CommentEntry> selectItems) {
		String alias = null;
		for (CommentEntry c : selectItems) {
			if (key.equals(c.getKey())) {
				alias = c.getValue();
				break;
			}
		}
		if (alias == null) {
			alias = StringUtils.substringAfterIfExist(key, ".");
		}
		return alias;
	}

}


text:
package alluxio.client.hadoop;

import alluxio.client.file.FileSystemTestUtils;
import alluxio.conf.Configuration;
import alluxio.grpc.WritePType;
import alluxio.hadoop.FileSystem;
import alluxio.hadoop.HadoopConfigurationUtils;
import alluxio.testutils.BaseIntegrationTest;
import alluxio.testutils.LocalAlluxioClusterResource;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;

import java.net.URI;

/**
 * Integration tests for {@link FileSystem#getFileBlockLocations(FileStatus, long, long)}.
 */
public class FileSystemBlockLocationIntegrationTest extends BaseIntegrationTest {

  private static final int BLOCK_SIZE = 1024;
  private static final int FILE_LEN = BLOCK_SIZE * 3;
  @ClassRule
  public static LocalAlluxioClusterResource sLocalAlluxioClusterResource =
      new LocalAlluxioClusterResource.Builder().build();
  private static org.apache.hadoop.fs.FileSystem sTFS;

  @BeforeClass
  public static void beforeClass() throws Exception {
    org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
    conf.set("fs.alluxio.impl", FileSystem.class.getName());

    alluxio.client.file.FileSystem alluxioFS = sLocalAlluxioClusterResource.get().getClient();
    FileSystemTestUtils.createByteFile(alluxioFS, "/testFile1", WritePType.CACHE_THROUGH,
        FILE_LEN);

    URI uri = URI.create(sLocalAlluxioClusterResource.get().getMasterURI());
    sTFS = org.apache.hadoop.fs.FileSystem.get(uri, HadoopConfigurationUtils
        .mergeAlluxioConfiguration(conf, Configuration.global()));
  }

  /**
   * Test {@code BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len)}.
   * Test the different situations of different start and len.
   */
  @Test
  public void basicBlockLocation() throws Exception {
    FileStatus fStatus = sTFS.getFileStatus(new Path("/testFile1"));

    // block0.offset = start < start+len < block1.offset
    long start = 0;
    long len = BLOCK_SIZE - 1;
    Assert.assertEquals(1, sTFS.getFileBlockLocations(fStatus, start, len).length);

    // block0.offset < start < start+len < block1.offset
    start = 1;
    len = BLOCK_SIZE - 2;
    Assert.assertEquals(1, sTFS.getFileBlockLocations(fStatus, start, len).length);

    // block0.offset < start = start+len < block1.offset
    start = 1;
    len = 0;
    Assert.assertEquals(1, sTFS.getFileBlockLocations(fStatus, start, len).length);

    // block0.offset = start < start+len = block1.offset
    start = 0;
    len = BLOCK_SIZE;
    Assert.assertEquals(2, sTFS.getFileBlockLocations(fStatus, start, len).length);

    // block0.offset = start < block1.offset < start+len < block2.offset
    start = 0;
    len = BLOCK_SIZE + 1;
    Assert.assertEquals(2, sTFS.getFileBlockLocations(fStatus, start, len).length);

    // block0.offset < start < block1.offset < start+len < block2.offset
    start = 1;
    len = BLOCK_SIZE;
    Assert.assertEquals(2, sTFS.getFileBlockLocations(fStatus, start, len).length);

    // block0.offset = start < start+len = block2.offset
    start = 0;
    len = BLOCK_SIZE * 2;
    Assert.assertEquals(3, sTFS.getFileBlockLocations(fStatus, start, len).length);

    // block0.offset = start < start+len = file.len
    start = 0;
    len = FILE_LEN;
    Assert.assertEquals(3, sTFS.getFileBlockLocations(fStatus, start, len).length);

    // file.len < start < start+len
    start = FILE_LEN + 1;
    len = 1;
    Assert.assertEquals(0, sTFS.getFileBlockLocations(fStatus, start, len).length);
  }
}


text:
<input type="hidden" id="cb_csrf_secured" value="<?= $this->security->get_csrf_hash() ?>">
<!--jQuery CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!--Bootstrap JS CDN-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!--Form Validator-->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<!-- Ajax JS -->

<script src="<?= base_url('includes/js/ajax.js'); ?>"></script>
<!--Main Js file-->
<script src="<?= base_url('includes/js/main.js'); ?>"></script>
</body>

</html>


text:
package org.intellij.lang.xpath.psi.impl;

import com.intellij.lang.ASTNode;
import com.intellij.psi.tree.IElementType;
import org.intellij.lang.xpath.psi.XPathElementVisitor;
import org.intellij.lang.xpath.psi.XPathToken;

public class XPathTokenImpl extends XPathElementImpl implements XPathToken {
    public XPathTokenImpl(ASTNode node) {
        super(node);
    }

    @Override
    public IElementType getTokenType() {
        return getNode().getElementType();
    }

  @Override
  public void accept(XPathElementVisitor visitor) {
    visitor.visitXPathToken(this);
  }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using E2ETests.Common;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Testing.xunit;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;

namespace E2ETests
{
    // Uses ports ranging 5050 - 5060.
    public class NtlmAuthenticationTests : IDisposable
    {
        private readonly XunitLogger _logger;

        public NtlmAuthenticationTests(ITestOutputHelper output)
        {
            _logger = new XunitLogger(output, LogLevel.Information);
        }

        [ConditionalTheory, Trait("E2Etests", "E2Etests")]
        [OSSkipCondition(OperatingSystems.Linux)]
        [OSSkipCondition(OperatingSystems.MacOSX)]
        [InlineData(ServerType.WebListener, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5050/")]
        [InlineData(ServerType.WebListener, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Standalone, "http://localhost:5051/")]
        [InlineData(ServerType.IISExpress, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5052/")]
        [InlineData(ServerType.IISExpress, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Standalone, "http://localhost:5053/")]
        public async Task NtlmAuthenticationTest(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, ApplicationType applicationType, string applicationBaseUrl)
        {
            using (_logger.BeginScope("NtlmAuthenticationTest"))
            {
                var musicStoreDbName = DbUtils.GetUniqueName();

                var deploymentParameters = new DeploymentParameters(Helpers.GetApplicationPath(applicationType), serverType, runtimeFlavor, architecture)
                {
                    PublishApplicationBeforeDeployment = true,
                    PreservePublishedApplicationForDebugging = Helpers.PreservePublishedApplicationForDebugging,
                    TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
                    Configuration = Helpers.GetCurrentBuildConfiguration(),
                    ApplicationType = applicationType,
                    ApplicationBaseUriHint = applicationBaseUrl,
                    EnvironmentName = "NtlmAuthentication", //Will pick the Start class named 'StartupNtlmAuthentication'
                    ServerConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("NtlmAuthentation.config") : null,
                    SiteName = "MusicStoreNtlmAuthentication", //This is configured in the NtlmAuthentication.config
                    UserAdditionalCleanup = parameters =>
                    {
                        DbUtils.DropDatabase(musicStoreDbName, _logger);
                    }
                };

                // Override the connection strings using environment based configuration
                deploymentParameters.EnvironmentVariables
                    .Add(new KeyValuePair<string, string>(
                        MusicStoreConfig.ConnectionStringKey,
                        DbUtils.CreateConnectionString(musicStoreDbName)));

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, _logger))
                {
                    var deploymentResult = deployer.Deploy();
                    var httpClientHandler = new HttpClientHandler() { UseDefaultCredentials = true };
                    var httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(deploymentResult.ApplicationBaseUri) };

                    // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                    var response = await RetryHelper.RetryRequest(async () =>
                    {
                        return await httpClient.GetAsync(string.Empty);
                    }, logger: _logger, cancellationToken: deploymentResult.HostShutdownToken);

                    Assert.False(response == null, "Response object is null because the client could not " +
                        "connect to the server after multiple retries");

                    var validator = new Validator(httpClient, httpClientHandler, _logger, deploymentResult);

                    Console.WriteLine("Verifying home page");
                    await validator.VerifyNtlmHomePage(response);

                    Console.WriteLine("Verifying access to store with permissions");
                    await validator.AccessStoreWithPermissions();

                    _logger.LogInformation("Variation completed successfully.");
                }
            }
        }

        public void Dispose()
        {
            _logger.Dispose();
        }
    }
}


text:
var parser = function() {
  var _separator = '\t';

  var parse = function(line) {
    var columns = line.split(_separator);
    console.log(columns);

    if (columns.length < 9) {
      console.log("invalid log entry");
      return;
    }

    return {
      timestamp: columns[0],
      process: columns[1],
      threadId: columns[2],
      area: columns[3],
      category: columns[4],
      eventId: columns[5],
      level: columns[6],
      message: columns[7],
      correlation: columns[8]
    };
  };

  return {
    parse: parse
  }
};

module.exports = parser;


text:
import * as Sentry from '@sentry/nextjs';

const SENTRY_DSN = process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN;

Sentry.init({
  dsn: SENTRY_DSN || 'https://0aaab4b2111f48b089ef20fe63544312@o324782.ingest.sentry.io/1828398',
  // Adjust this value in production, or use tracesSampler for greater control
  //tracesSampleRate: 1.0,
  // ...
  // Note: if you want to override the automatic release value, do not set a
  // `release` value here - use the environment variable `SENTRY_RELEASE`, so
  // that it will also get attached to your source maps
});


text:
package net.sourceforge.easyml.marshalling.java.lang;

import net.sourceforge.easyml.InvalidFormatException;
import net.sourceforge.easyml.marshalling.AbstractStrategy;
import net.sourceforge.easyml.marshalling.MarshalContext;
import net.sourceforge.easyml.marshalling.SimpleStrategy;
import net.sourceforge.easyml.marshalling.UnmarshalContext;

/**
 * EnumStrategy class that implements the {@linkplain SimpleStrategy} interface
 * for the Java enums, including polymorphic ones. This implementation is
 * thread-safe.
 *
 * @author Victor Cordis ( cordis.victor at gmail.com)
 * @version 1.3.7
 * @since 1.0
 */
public final class EnumStrategy extends AbstractStrategy implements SimpleStrategy<Enum> {

    /**
     * Constant defining the value used for the strategy name.
     */
    public static final String NAME = "enum";
    /**
     * Constant defining the singleton instance.
     */
    public static final EnumStrategy INSTANCE = new EnumStrategy();
    private static final char SEPARATOR = '.';

    private EnumStrategy() {
    }

    /**
     * {@inheritDoc }
     */
    @Override
    public boolean strict() {
        return false;
    }

    /**
     * {@inheritDoc }
     */
    @Override
    public Class<Enum> target() {
        return Enum.class;
    }

    /**
     * {@inheritDoc }
     */
    @Override
    public boolean appliesTo(Class<Enum> c) {
        return Enum.class.isAssignableFrom(c); // not isEnum() because of polymorphic-enums.
    }

    /**
     * {@inheritDoc }
     */
    @Override
    public String name() {
        return EnumStrategy.NAME;
    }

    /**
     * {@inheritDoc }
     */
    @Override
    public String marshal(Enum target, MarshalContext ctx) {
        Class cls = target.getClass();
        if (!cls.isEnum()) {// handle polymorphic enums:
            cls = cls.getSuperclass();
        }
        // build enum name and constant name:
        return new StringBuilder(ctx.aliasOrNameFor(cls))
                .append(EnumStrategy.SEPARATOR)
                .append(target.name())
                .toString();
    }

    /**
     * {@inheritDoc }
     */
    @Override
    public Enum unmarshal(String text, UnmarshalContext ctx) {
        // find separator:
        final int index = text.lastIndexOf(EnumStrategy.SEPARATOR);
        if (index < 0 || index == text.length() - 1) {
            throw new InvalidFormatException(ctx.readerPositionDescriptor(), "text: missing separator");
        }
        try {
            // find enum class and value:
            return Enum.valueOf(ctx.classFor(text.substring(0, index)), text.substring(index + 1));
        } catch (ClassNotFoundException cnfx) {
            throw new InvalidFormatException(ctx.readerPositionDescriptor(), cnfx);
        }
    }
}


text:
const path = require('path');

module.exports = function(tests=null, testsDirectory = null) {
  let testsToRun = null;
  let testParamIndex = process.argv.findIndex(value => value === '--tests');
  if (testParamIndex > 0 && process.argv[testParamIndex + 1]) {
    testParamIndex++;
    testsToRun = process.argv[testParamIndex]
      .split(',')
      .map(name => tests.find(test => test.name == name))
      .filter(value => (!!value));
    if (!testsToRun.length) {
      console.log();
      console.log('Unknown tests', process.argv[testParamIndex]);
      console.error("Available tests: " + tests.map(test => test.name).join(', '));
      process.exit(1);
    }
  } else {
    console.log('Run all tests')
    testsToRun = tests;
  }
  testsToRun.map(({file}) => {
    require(path.join(testsDirectory, file))
  });
}


text:
define(function(){

    function Position(x,y) {
        this.x = x;
        this.y = y;
        this.copy = function(){
            return new Position(this.x, this.y);
        }
    }

    function MouseListener(){

        var clickPosition = new Position(0,0);

        window.addEventListener('mousedown', function(e){
            clickPosition = new Position(e.pageX, e.pageY);
        });

        this.getClickPosition = function(){
            return clickPosition.copy();
        }
    }

    window.Global = window.Global || {};

    window.Global.MouseListener = window.Global.MouseListener || new MouseListener();

    return window.Global.MouseListener;

});


text:
"""6

Revision ID: 3d8eec94b9a9
Revises: 3ec4ff2461dd
Create Date: 2014-03-28 19:50:32.968879

"""

# revision identifiers, used by Alembic.
revision = '3d8eec94b9a9'
down_revision = '3ec4ff2461dd'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    pass
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    pass
    ### end Alembic commands ###


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace Microsoft.Azure.WebJobs.Script.Eventing
{
    public class HostRestartEvent : ScriptEvent
    {
        public HostRestartEvent()
            : base(nameof(HostRestartEvent), EventSources.Worker)
        {
        }
    }
}


text:
            {{task.title}}

            {{task.perc}} %

Nuovo


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Managed3D.Geometry;
using Managed3D.SceneGraph;

namespace Managed3D.Rendering
{
    /// <summary>
    /// Defines the essential functionality that a 3d renderer implementation should provide.
    /// </summary>
    public interface IRenderer
    {
        #region Properties
        /// <summary>
        /// Gets or sets a <see cref="Vector4f"/> describing a background color for rendered frames.
        /// </summary>
        Vector4f BackgroundColor
        {
            get;
            set;
        }
        /// <summary>
        /// Gets a value indicating whether the renderer is performing real-time frame rendering.
        /// </summary>
        bool IsRunning
        {
            get;
        }

        /// <summary>
        /// Gets or sets the <see cref="Scene"/>
        /// </summary>
        Scene Scene
        {
            get;
            set;
        }
        #endregion
        #region Methods
        /// <summary>
        /// Prepares the renderer using the specified options.
        /// </summary>
        /// <param name="options"></param>
        void Initialize(RendererOptions options);

        /// <summary>
        /// Causes the renderer to render a frame.
        /// </summary>
        void RenderFrame();

        /// <summary>
        /// Causes the renderer to begin rendering frames for real-time operation.
        /// </summary>
        void Start();

        /// <summary>
        /// Causes the renderer to stop rendering real-time frames.
        /// </summary>
        void Stop();
        #endregion
    }
}


text:
package com.google.firebase.database;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.collect.ImmutableMap;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.TestOnlyImplFirebaseTrampolines;
import com.google.firebase.database.core.DatabaseConfig;
import com.google.firebase.database.snapshot.IndexedNode;
import com.google.firebase.database.snapshot.Node;
import com.google.firebase.database.snapshot.NodeUtilities;
import com.google.firebase.testing.ServiceAccount;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class DataSnapshotTest {

  private static FirebaseApp testApp;
  private static DatabaseConfig config;

  @BeforeClass
  public static void setUpClass() throws IOException {
    testApp = FirebaseApp.initializeApp(
        FirebaseOptions.builder()
            .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
            .setDatabaseUrl("https://admin-java-sdk.firebaseio.com")
            .build());
    // Obtain a new DatabaseConfig instance for testing. Since we are not connecting to an
    // actual Firebase database, it is necessary to use a stand-in DatabaseConfig here.
    config = TestHelpers.newTestConfig(testApp);
  }

  @AfterClass
  public static void tearDownClass() throws InterruptedException {
    // Tear down and clean up the test DatabaseConfig.
    TestHelpers.interruptConfig(config);
    TestOnlyImplFirebaseTrampolines.clearInstancesForTest();
  }

  private DataSnapshot snapFor(Object data) {
    Node node = NodeUtilities.NodeFromJSON(data);
    DatabaseReference ref = new DatabaseReference("https://test.firebaseio.com", config);
    return new DataSnapshot(ref, IndexedNode.from(node));
  }

  @Test
  public void testBasicIteration() {
    DataSnapshot snap1 = snapFor(null);

    assertFalse(snap1.hasChildren());
    assertFalse(snap1.getChildren().iterator().hasNext());

    DataSnapshot snap2 = snapFor(1L);
    assertFalse(snap2.hasChildren());
    assertFalse(snap2.getChildren().iterator().hasNext());

    DataSnapshot snap3 = snapFor(MapBuilder.of("a", 1L, "b", 2L));
    assertTrue(snap3.hasChildren());
    Iterator<DataSnapshot> iter = snap3.getChildren().iterator();
    assertTrue(iter.hasNext());

    String[] children = new String[] {null, null};
    int i = 0;
    for (DataSnapshot child : snap3.getChildren()) {
      children[i] = child.getKey();
      i++;
    }
    assertArrayEquals(children, new String[] {"a", "b"});
  }

  @Test
  public void testExists() {
    DataSnapshot snap;

    snap = snapFor(new HashMap<>());
    assertFalse(snap.exists());

    snap = snapFor(MapBuilder.of(".priority", 1));
    assertFalse(snap.exists());

    snap = snapFor(null);
    assertFalse(snap.exists());

    snap = snapFor(true);
    assertTrue(snap.exists());

    snap = snapFor(5);
    assertTrue(snap.exists());

    snap = snapFor(MapBuilder.of("x", 5));
    assertTrue(snap.exists());
  }

  @Test
  public void testChild() {
    DataSnapshot snapshot = snapFor(ImmutableMap.of("foo", "bar"));
    assertTrue(snapshot.hasChild("foo"));
    assertFalse(snapshot.hasChild("bar"));
    assertEquals(1, snapshot.getChildrenCount());

    DataSnapshot child = snapshot.child("foo");
    assertNotNull(child);
    assertEquals("foo", child.getKey());
    assertTrue(child.exists());

    child = snapshot.child("bar");
    assertNotNull(child);
    assertEquals("bar", child.getKey());
    assertFalse(child.exists());

    Iterator<DataSnapshot> iter = snapshot.getChildren().iterator();
    int count = 0;
    while (iter.hasNext()) {
      DataSnapshot next = iter.next();
      count++;
      assertNotNull(next);
      try {
        iter.remove();
        fail("No error thrown for remove() operation");
      } catch (UnsupportedOperationException expected) {
        // expected
      }
    }
    assertEquals(1, count);
  }

  @Test
  public void testGetValue() {
    DataSnapshot snapshot = snapFor("foo");
    assertEquals("foo", snapshot.getValue(String.class));

    snapshot = snapFor(9);
    assertEquals(9, (int) snapshot.getValue(Integer.class));

    snapshot = snapFor(9.9);
    assertEquals(9.9, snapshot.getValue(Double.class), 0.0001);

    snapshot = snapFor(true);
    assertTrue(snapshot.getValue(Boolean.class));

    ImmutableMap<String, String> map = ImmutableMap.of("foo", "bar");
    snapshot = snapFor(map);
    GenericTypeIndicator<Map<String, String>> generic =
        new GenericTypeIndicator<Map<String, String>>() {};
    assertEquals(map, snapshot.getValue(generic));
  }

  @Test
  public void testGetPriority() {
    DataSnapshot snapshot = snapFor(ImmutableMap.of(".value", "foo", ".priority", 10L));
    assertEquals(10.0, snapshot.getPriority());

    snapshot = snapFor(ImmutableMap.of(".value", "foo", ".priority", "p"));
    assertEquals("p", snapshot.getPriority());

    snapshot = snapFor("foo");
    assertNull(snapshot.getPriority());
  }

  @Test
  public void testToString() {
    DataSnapshot snapshot = snapFor(ImmutableMap.of("foo", "bar"));
    assertEquals("DataSnapshot { key = null, value = {foo=bar} }", snapshot.toString());

    DatabaseReference reference = new DatabaseReference("https://test.firebaseio.com/test", config);
    Node node = NodeUtilities.NodeFromJSON("foo");
    snapshot = new DataSnapshot(reference, IndexedNode.from(node));
    assertEquals("DataSnapshot { key = test, value = foo }", snapshot.toString());
  }
}


text:
/*
 * Single Window Application Template:
 * A basic starting point for your application.  Mostly a blank canvas.
 *
 * In app.js, we generally take care of a few things:
 * - Bootstrap the application with any data we need
 * - Check for dependencies like device type, platform version or network connection
 * - Require and open our top-level UI component
 *
 */
var platino = require("co.lanica.platino"),
	chipmunk2d = require('co.lanica.chipmunk2d'),
	animo = require("animo"),
	win = Ti.UI.createWindow(),
	game = platino.createGameView(),
	scene = platino.createScene();

//bootstrap and check dependencies
if (Ti.version < 3.2) {
	alert('Sorry - this application template requires Titanium Mobile SDK 3.2 or later');
}

// This is a single context application with multiple windows in a stack
(function() {
	//render appropriate components based on the platform and form factor
	var osname = Ti.Platform.osname,
		_W = Ti.Platform.displayCaps.platformWidth,
		_H = Ti.Platform.displayCaps.platformHeight,
		bg = platino.createSprite({
			width: _W,
			height: _H
		});
	scene.add(bg);

	game.enableOnDrawFrameEvent = true;
	game.fps = 10;
	game.color(0,0,0);

	game.addEventListener("onload", function(e){
		var self = e.source,
			SCREEN = {
				width: 320,
				height: 568
			},
			scale = self.size.height / SCREEN.height;

		self.screen = {
			width: self.size.width / scale,
			height: self.size.height / scale
		};
		self.touchScaleX = self.screen.width / self.size.width;
		self.touchScaleY = self.screen.height / self.size.height;

		self.pushScene(scene);

		self.start();
		skeleton = animo.createSkeletonWithFile('assets/skeletons/redman_Redman.json');
		skeleton.setPosition(SCREEN.width/2, SCREEN.height/2);
		skeleton_animation = animo.createSkeletalAnimationWithFile('assets/skeletons/animations/UntitledAnimation.json');
		skeleton.playAnimation(skeleton_animation);
	});

	win.add(game);
	win.open();
})();


text:
autoheader
rm aclocal.m4
libtoolize -c
aclocal
automake
autoconf

echo done creating autoconf files in `pwd`


text:
package com.inthergroup.internship.services;

import com.inthergroup.internship.models.User;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

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

public interface UserService {
    /**
     * Returns all instances of User entity.
     * @return
     */
    List<User> findAll();

    /**
     * Returns instance of User entity using his id.
     * @param id User id.
     */
    User findById(Long id);

    /**
     * Returns instance of User entity using his username.
     * @param username Username.
     */
    User findByUsername(String username);

    /**
     * Saves instance of User entity.
     */
    User create(User user);

    /**
     * Saves instance of User entity.
     */
    User edit(User user);

    /**
     * Deletes instance of User entity by his id.
     * @param id
     */
    void deleteById(Long id);

    long findRemainedPointsByUserId(Long userId);

    /**
     * Update points.
     * @param userId
     */
    void updateRemainedPointsByUserId(Long userId, Long pointsToUpdate);

    /**
     * Returns list of instances of User entity from a specific career level.
     * @param id Career level id.
     * @return
     */
    List<User> findUsersFromLevel(Long id);

    /**
     * Returns map with percent progress for corresponding user id.
     */
    Map<String, Integer> findUsersPercentProgress();

    Map<String, Integer> findUsersMandatoryTaskToBeDone();

    Map<String, Integer> findUsersMandatoryTaskDone();

    /**
     * Returns true if user is eligible to be promoted to any of 5 levels
     */
    boolean isUserEligibleToBePromoted(Long id);

    void updateRecentPromotionPoints(Long userId, Long pointsToUpdate);

    long findRecentPromotionPointsByUserId(Long userId);

    void updateRecentPromotionDate(Long userId);

    Date findRecentPromotionDateByUserId(Long userId);
}


text:
package org.uddi.custody_v3;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for keyBag complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="keyBag">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="key" type="{urn:uddi-org:api_v3}uddiKey" maxOccurs="unbounded"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "keyBag", propOrder = {
    "key"
})
public class KeyBag implements Serializable{
	@XmlTransient
	private static final long serialVersionUID = -965586924432616342L;
	@XmlElement(required = true)
    protected List<String> key;

    /**
     * Gets the value of the key property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the key property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getKey().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link String }
     *
     *
     */
    public List<String> getKey() {
        if (key == null) {
            key = new ArrayList<String>();
        }
        return this.key;
    }

}


text:
"""
Maintainer script for ruwiki's administrator attention requests table
([[:ru:ВП:ЗКАБ]]).

Log file is used for saving "администратор" field in deleted requests.

Usage:
    python fastrfaa.py [logfile]
"""

import re
import sys
from datetime import datetime
import pywikibot

REGEXP = re.compile(r"""
    (?P<indent>\n*)
    ==[ ]*(?P<header>.*?)[ ]*==\s+
    (?P<section>
        <onlyinclude>\s*
        (?P<template>
            (?:[^<]|<(?!/?onlyinclude))*?
        )
        \s*</onlyinclude>
    )
""", re.I | re.VERBOSE)

CONFIGURATION = {
    # nickname or "*" for any: [done delay, undone delay, period of moving to rfaa]
    "*": [24, 3 * 24, 7 * 24]
}

TIME_FORMAT = "%Y%m%d%H%M%S"
UTCNOW = datetime.utcnow()
UTCNOWSTR = UTCNOW.strftime(TIME_FORMAT)

MOVED_TEXT = ""

CORRECTED_COUNT = 0
DELETED_DONE_COUNT = 0
DELETED_UNDONE_COUNT = 0
MOVED_COUNT = 0

if len(sys.argv) > 1:
    LOGFILE = open(sys.argv[1], "a", encoding="utf-8")
else:
    LOGFILE = None

def load_configuration(config_text):
    """Load configuration and set individual delays."""
    for line in config_text.split("\n"):
        try:
            if re.match(r"^(#|</?pre>)", line):
                continue
            parsed = [value.strip() for value in line.split("/")]
            if len(parsed) != 4:
                continue
            CONFIGURATION[parsed[0]] = [int(value) for value in parsed[1:]]
        except:
            continue

def get_delays(user="*"):
    """Get delays for current user from configuration."""
    if user in CONFIGURATION:
        return CONFIGURATION[user]
    else:
        return CONFIGURATION["*"]

def minor_fixes(text):
    """Fix some minor errors before processing the page."""
    text = re.sub(r"^==.*?==\n+(==.*?==)$", "\\1", text, flags=re.M) # empty sections
    return text

def correct_request(match):
    """Fix some errors, for example, update header if it doesn't match the content."""
    # initialization
    corrected = False
    indent = match.group("indent")
    header = match.group("header")
    section = match.group("section")

    # missing timestamp fix
    (section, flag) = re.subn(
        r"(\|\s*администратор\s*=[^/\n]*[^/\s][^/\n]*)\n",
        "\\1/" + UTCNOWSTR + "\n",
        section)
    if flag > 0:
        corrected = True

    # wrong header fix
    question = re.search(r"\|\s*вопрос\s*=(.*)", section)
    timestamp = re.search(r"\|\s*автор\s*=[^/\n]+/\s*(\d{14})", section)
    if question is None or timestamp is None:
        # request is completely broken
        return match.group(0)

    correct_header = question.group(1).strip() + "/" + timestamp.group(1)
    if header != correct_header:
        corrected = True
        header = correct_header

    # finalization
    if corrected:
        global CORRECTED_COUNT
        CORRECTED_COUNT += 1
        return "{}== {} ==\n{}".format(indent, header, section)
    else:
        return match.group(0)

def move_old_request(template):
    """Forms text for (non-fast) rfaa in MOVED_TEXT."""
    global MOVED_TEXT
    global MOVED_COUNT
    parts = re.search(r"\|\s*вопрос\s*=(.*)", template).group(1).strip().split("/")
    if len(parts) == 2:
        header = parts[1]
    else:
        header = parts[0]
    MOVED_TEXT += "== {} (с ЗКАБ) ==\n".format(header)
    MOVED_TEXT += re.sub(r"(ЗКА:Быстрый запрос)", "subst:\\1", template)
    MOVED_TEXT += "\n* {{block-small|Перенесено со страницы быстрых запросов ботом," \
                + " поскольку запрос не был выполнен в течение 7 дней. ~~~~}}"
    MOVED_TEXT += "\n\n"
    MOVED_COUNT += 1

def delete_old_request(match):
    """Process one table row and delete it if it's neccessary."""
    template = match.group("template")
    status = re.search(r"\|\s*статус\s*=\s*([+-])", template)
    author = re.search(r"\|\s*автор\s*=([^/\n]+)/\s*(\d{14})", template)
    admin = re.search(r"\|\s*администратор\s*=([^/\n]+)/\s*(\d{14})", template)

    extract_name = lambda m: m.group(1).strip()
    extract_date = lambda m: datetime.strptime(m.group(2), TIME_FORMAT)
    check_delay = lambda date, delay: delay >= 0 and (UTCNOW - date).total_seconds() >= delay * 60 * 60

    if author is None:
        delays = get_delays()
    else:
        delays = get_delays(extract_name(author))

    if admin is None:
        # request is still open
        if author is not None:
            if check_delay(extract_date(author), delays[2]):
                # very old request that should be moved to rfaa
                move_old_request(template)
                return ""
    else:
        # request is closed
        if status is None:
            done = True
        else:
            done = status.group(1) == "+"
        if done:
            delay = delays[0]
        else:
            delay = delays[1]
        if check_delay(extract_date(admin), delay):
            # archiving
            if done:
                global DELETED_DONE_COUNT
                DELETED_DONE_COUNT += 1
            else:
                global DELETED_UNDONE_COUNT
                DELETED_UNDONE_COUNT += 1
            if LOGFILE:
                LOGFILE.write("{}/{}\n".format(extract_name(admin), admin.group(2)))
            return ""
    return match.group(0)

def form_comment():
    """Analyze global variables and form a comment for an edit."""
    plural = lambda num, word: word + ("ый" if num % 10 == 1 and num % 100 != 11 else "ых")
    plural_phrase = lambda num, word: str(num) + " " + plural(num, word)

    deleted_parts = []
    if DELETED_DONE_COUNT > 0:
        deleted_parts.append(plural_phrase(DELETED_DONE_COUNT, "выполненн"))
    if DELETED_UNDONE_COUNT > 0:
        deleted_parts.append(plural_phrase(DELETED_UNDONE_COUNT, "невыполненн"))
    if MOVED_COUNT > 0:
        deleted_parts.append(plural_phrase(MOVED_COUNT, "перенесённ"))
    deleted = ", ".join(deleted_parts)

    if CORRECTED_COUNT:
        corrected = str(CORRECTED_COUNT)
    else:
        corrected = ""

    if corrected and deleted:
        return "Исправление ошибочных ({}), удаление старых запросов ({}).".format(corrected, deleted)
    elif corrected:
        return "Исправление ошибочных запросов ({}).".format(corrected)
    elif deleted:
        return "Удаление старых запросов ({}).".format(deleted)
    else:
        return ""

def main():
    """Main script function."""
    site = pywikibot.Site()
    config = pywikibot.Page(site, "Википедия:Запросы к администраторам/Быстрые/Конфигурация")
    if config.exists():
        load_configuration(config.text)

    fast = pywikibot.Page(site, "Википедия:Запросы к администраторам/Быстрые")
    ftext = fast.text

    ftext = minor_fixes(ftext)
    ftext = REGEXP.sub(correct_request, ftext)
    ftext = REGEXP.sub(delete_old_request, ftext)

    if MOVED_TEXT != "":
        rfaa = pywikibot.Page(site, "Википедия:Запросы к администраторам")
        rtext = rfaa.text
        insert = rtext.find("==")
        if insert == -1:
            insert = len(rtext)
        rtext = rtext[:insert] + MOVED_TEXT + rtext[insert:]
        rfaa.text = rtext
        rfaa.save("Перенос залежавшихся быстрых запросов.", minor=False)

    comment = form_comment()
    if comment:
        fast.text = ftext
        fast.save(comment)

if __name__ == "__main__":
    main()


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/card_singer_album"
        style="@style/CardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="5dp"
        app:cardBackgroundColor="@color/grey"
        app:cardCornerRadius="3dp"
        app:cardElevation="5dp"
        app:cardMaxElevation="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/selectableItemBackground"
            android:padding="16dp">

            <ImageView
                android:id="@+id/iv_album"
                android:layout_width="130dp"
                android:layout_height="130dp" />

            <TextView
                android:id="@+id/tv_album_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="16dp"
                android:layout_marginTop="5dp"
                android:layout_toRightOf="@id/iv_album"
                android:ellipsize="end"
                android:maxLines="2"
                android:text="name"
                android:textColor="@android:color/white"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/tv_album_company"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@id/tv_album_name"
                android:layout_below="@id/tv_album_name"
                android:layout_marginTop="10dp"
                android:ellipsize="end"
                android:maxLines="1"
                android:text="company"
                android:textColor="@android:color/white" />

            <TextView
                android:id="@+id/tv_album_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@id/tv_album_name"
                android:layout_below="@id/tv_album_company"
                android:layout_marginTop="5dp"
                android:text="time"
                android:textColor="@android:color/white" />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>


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

package com.google.gerrit.acceptance.server.git;

import static com.google.common.truth.Truth.assertThat;

import com.google.gerrit.entities.Project;
import com.google.gerrit.server.git.CodeReviewCommit;
import com.google.gerrit.testing.InMemoryRepositoryManager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.junit.Test;

/** Tests for {@link CodeReviewCommit}. */
public class CodeReviewCommitTest {

  @Test
  public void checkSerializable_withStatusMessage() throws Exception {
    CodeReviewCommit commit = new CodeReviewCommit(createCommit());
    commit.setStatusMessage("Status");
    CodeReviewCommit deserializedCommit = serializeAndReadBack(commit);
    assertThat(deserializedCommit).isEqualTo(commit);
    assertThat(deserializedCommit.getStatusMessage().get()).isEqualTo("Status");
  }

  @Test
  public void checkSerializable_emptyStatusMessage() throws Exception {
    CodeReviewCommit commit = new CodeReviewCommit(createCommit());
    CodeReviewCommit deserializedCommit = serializeAndReadBack(commit);
    assertThat(deserializedCommit).isEqualTo(commit);
    assertThat(deserializedCommit.getStatusMessage().isPresent()).isFalse();
  }

  @SuppressWarnings("BanSerializableRead")
  private CodeReviewCommit serializeAndReadBack(CodeReviewCommit codeReviewCommit)
      throws Exception {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos)) {
      out.writeObject(codeReviewCommit);
      out.flush();
      try (ByteArrayInputStream fileIn = new ByteArrayInputStream(bos.toByteArray());
          ObjectInputStream in = new ObjectInputStream(fileIn); ) {
        return (CodeReviewCommit) in.readObject();
      }
    }
  }

  private ObjectId createCommit() throws Exception {
    InMemoryRepositoryManager repoManager = new InMemoryRepositoryManager();
    Project.NameKey project = Project.nameKey("test");
    try (Repository repo = repoManager.createRepository(project);
        TestRepository<Repository> tr = new TestRepository<>(repo)) {
      PersonIdent ident = new PersonIdent(new PersonIdent("Test Ident", "test@test.com"));
      return tr.commit().author(ident).committer(ident).message("Test commit").create();
    }
  }
}


text:
package com.atlassian.plugin.webresource;

import junit.framework.TestCase;

import java.util.LinkedHashMap;
import java.util.Map;

public class TestResourceUtils extends TestCase
{
    public void testGetType()
    {
        assertEquals("css", ResourceUtils.getType("/foo.css"));
        assertEquals("js", ResourceUtils.getType("/superbatch/js/foo.js"));
        assertEquals("", ResourceUtils.getType("/superbatch/js/foo."));
        assertEquals("", ResourceUtils.getType("/superbatch/js/foo"));
    }

    public void testCacheKeyParameterOrder() throws Exception
    {
        String path = "/A/year/is/a/long/time";
        Map<String,String> map = new LinkedHashMap<String, String> ();
        map.put(new String("Not"),"so");
        map.put(new String("long"),"Just");
        map.put(new String("once"),"around");
        map.put(new String("the"),"sun");

        Map<String,String> map2 = new LinkedHashMap<String, String> ();
        map2.put(new String("the"),"sun");
        map2.put(new String("once"),"around");
        map2.put(new String("long"),"Just");
        map2.put(new String("Not"),"so");

        assertEquals(ResourceUtils.buildCacheKey(path,map),ResourceUtils.buildCacheKey(path,map2));

        assertEquals(ResourceUtils.buildCacheKey(path,map).hashCode(),ResourceUtils.buildCacheKey(path,map2).hashCode());

    }
}


text:
<include src="data_series.js"/>
<include src="timeline_graph_view.js"/>

// Specifies which stats should be drawn on the 'bweCompound' graph and how.
var bweCompoundGraphConfig = {
  googAvailableSendBandwidth: {color: 'red'},
  googTargetEncBitrateCorrected: {color: 'purple'},
  googActualEncBitrate: {color: 'orange'},
  googRetransmitBitrate: {color: 'blue'},
  googTransmitBitrate: {color: 'green'},
};

// Converts the last entry of |srcDataSeries| from the total amount to the
// amount per second.
var totalToPerSecond = function(srcDataSeries) {
  var length = srcDataSeries.dataPoints_.length;
  if (length >= 2) {
    var lastDataPoint = srcDataSeries.dataPoints_[length - 1];
    var secondLastDataPoint = srcDataSeries.dataPoints_[length - 2];
    return (lastDataPoint.value - secondLastDataPoint.value) * 1000 /
           (lastDataPoint.time - secondLastDataPoint.time);
  }

  return 0;
};

// Converts the value of total bytes to bits per second.
var totalBytesToBitsPerSecond = function(srcDataSeries) {
  return totalToPerSecond(srcDataSeries) * 8;
};

// Specifies which stats should be converted before drawn and how.
// |convertedName| is the name of the converted value, |convertFunction|
// is the function used to calculate the new converted value based on the
// original dataSeries.
var dataConversionConfig = {
  packetsSent: {
    convertedName: 'packetsSentPerSecond',
    convertFunction: totalToPerSecond,
  },
  bytesSent: {
    convertedName: 'bitsSentPerSecond',
    convertFunction: totalBytesToBitsPerSecond,
  },
  packetsReceived: {
    convertedName: 'packetsReceivedPerSecond',
    convertFunction: totalToPerSecond,
  },
  bytesReceived: {
    convertedName: 'bitsReceivedPerSecond',
    convertFunction: totalBytesToBitsPerSecond,
  },
  // This is due to a bug of wrong units reported for googTargetEncBitrate.
  // TODO (jiayl): remove this when the unit bug is fixed.
  googTargetEncBitrate: {
    convertedName: 'googTargetEncBitrateCorrected',
    convertFunction: function (srcDataSeries) {
      var length = srcDataSeries.dataPoints_.length;
      var lastDataPoint = srcDataSeries.dataPoints_[length - 1];
      if (lastDataPoint.value < 5000)
        return lastDataPoint.value * 1000;
      return lastDataPoint.value;
    }
  }
};

var graphViews = {};
var dataSeries = {};

// Adds the stats report |singleReport| to the timeline graph for the given
// |peerConnectionElement| and |reportName|.
function drawSingleReport(peerConnectionElement, reportName, singleReport) {
  if (!singleReport || !singleReport.values)
    return;
  for (var i = 0; i < singleReport.values.length - 1; i = i + 2) {
    var rawLabel = singleReport.values[i];
    var rawValue = parseInt(singleReport.values[i + 1]);
    var rawDataSeriesId =
        peerConnectionElement.id + '-' + reportName + '-' + rawLabel;

    var finalDataSeriesId = rawDataSeriesId;
    var finalLabel = rawLabel;
    var finalValue = rawValue;
    // We need to convert the value if dataConversionConfig[rawLabel] exists.
    if (dataConversionConfig[rawLabel]) {
      // Updates the original dataSeries before the conversion.
      addDataSeriesPoint(rawDataSeriesId, singleReport.timestamp,
                         rawLabel, rawValue);

      // Convert to another value to draw on graph, using the original
      // dataSeries as input.
      finalValue = dataConversionConfig[rawLabel].convertFunction(
          dataSeries[rawDataSeriesId]);
      finalLabel = dataConversionConfig[rawLabel].convertedName;
      finalDataSeriesId =
          peerConnectionElement.id + '-' + reportName + '-' + finalLabel;
    }

    // Updates the final dataSeries to draw.
    addDataSeriesPoint(
        finalDataSeriesId, singleReport.timestamp, finalLabel, finalValue);

    // Updates the graph.
    var graphType = bweCompoundGraphConfig[finalLabel] ?
                    'bweCompound' : finalLabel;
    var graphViewId =
        peerConnectionElement.id + '-' + reportName + '-' + graphType;

    if (!graphViews[graphViewId]) {
      graphViews[graphViewId] = createStatsGraphView(peerConnectionElement,
                                                     reportName,
                                                     graphType);
      var date = new Date(singleReport.timestamp);
      graphViews[graphViewId].setDateRange(date, date);
    }
    // Adds the new dataSeries to the graphView. We have to do it here to cover
    // both the simple and compound graph cases.
    if (!graphViews[graphViewId].hasDataSeries(dataSeries[finalDataSeriesId]))
      graphViews[graphViewId].addDataSeries(dataSeries[finalDataSeriesId]);
    graphViews[graphViewId].updateEndDate();
  }
}

// Makes sure the TimelineDataSeries with id |dataSeriesId| is created,
// and adds the new data point to it.
function addDataSeriesPoint(dataSeriesId, time, label, value) {
  if (!dataSeries[dataSeriesId]) {
    dataSeries[dataSeriesId] = new TimelineDataSeries();
    if (bweCompoundGraphConfig[label]) {
      dataSeries[dataSeriesId].setColor(
          bweCompoundGraphConfig[label].color);
    }
  }
  dataSeries[dataSeriesId].addPoint(time, value);
}

// Ensures a div container to hold all stats graphs for a report type
// is created as a child of |peerConnectionElement|.
function ensureStatsGraphTopContainer(peerConnectionElement, reportName) {
  var containerId = peerConnectionElement.id + '-' +
                    reportName + '-graph-container';
  var container = $(containerId);
  if (!container) {
    container = document.createElement('div');
    container.id = containerId;
    container.className = 'stats-graph-container-collapsed';

    peerConnectionElement.appendChild(container);
    container.innerHTML =
        '<button>Expand/Collapse Graphs for ' + reportName + '</button>';

    // Expands or collapses the graphs on click.
    container.childNodes[0].addEventListener('click', function(event) {
      var element = event.target.parentNode;
      if (element.className == 'stats-graph-container-collapsed')
        element.className = 'stats-graph-container';
      else
        element.className = 'stats-graph-container-collapsed';
    });
  }
  return container;
}

// Creates the container elements holding a timeline graph
// and the TimelineGraphView object.
function createStatsGraphView(peerConnectionElement, reportName, statsName) {
  var topContainer = ensureStatsGraphTopContainer(peerConnectionElement,
                                                  reportName);

  var graphViewId =
      peerConnectionElement.id + '-' + reportName + '-' + statsName;
  var divId = graphViewId + '-div';
  var canvasId = graphViewId + '-canvas';
  var container = document.createElement("div");
  container.className = 'stats-graph-sub-container';

  topContainer.appendChild(container);
  container.innerHTML = '
' + statsName + '
' +
      '
<canvas id=' + canvasId + '></canvas>
';
  if (statsName == 'bweCompound') {
      container.insertBefore(createBweCompoundLegend(peerConnectionElement,
                                                     reportName),
                             $(divId));
  }
  return new TimelineGraphView(divId, canvasId);
}

// Creates the legend section for the bweCompound graph.
// Returns the legend element.
function createBweCompoundLegend(peerConnectionElement, reportName) {
  var legend = document.createElement('div');
  for (var prop in bweCompoundGraphConfig) {
    var div = document.createElement('div');
    legend.appendChild(div);
    div.innerHTML = '<input type=checkbox checked></input>' + prop;
    div.style.color = bweCompoundGraphConfig[prop].color;
    div.dataSeriesId = peerConnectionElement.id + '-' + reportName + '-' + prop;
    div.graphViewId =
        peerConnectionElement.id + '-' + reportName + '-bweCompound';
    div.firstChild.addEventListener('click', function(event) {
        var target = dataSeries[event.target.parentNode.dataSeriesId];
        target.show(event.target.checked);
        graphViews[event.target.parentNode.graphViewId].repaint();
    });
  }
  return legend;
}


text:
'use strict';
const Errors = require('esrol-errors');
const errors = new Errors();

errors.registerErrorWithNumber('Some error message', 1);
let all = errors.getAllErrors();
let error = errors.getByNumber(1);
console.log (error); // Some error message
console.log (all); // { '1': 'Some error message' }
try {
  errors.error('the reason for this erros is to show some example', 1);
} catch(e) {
  console.log (e);
  console.log (e.stack);
}


text:
#include "AzulCore.h"

#include "EnumName.h"
#include "TextMan.h"
#include "Text.h"
#include "Rect.h"
#include "Image.h"
#include "ImageMan.h"

//externs must be exterminated
extern GLShaderManager	shaderManager;

GameSprite :: GameSprite( SpriteBatchName::Name _spriteBatchName, SpriteName::Name _spriteName, ImageName::Name imageName, Rect destRect)
{
	this->setName( 0 );
	this->spriteBatchName = _spriteBatchName;
	this->spriteName = _spriteName;

	SpriteModel *p = new SpriteModel( imageName, destRect );
	this->spriteModel = p;

	this->angle = 0.0f;

	this->origWidth = p->destRect.width;
	this->origHeight = p->destRect.height;

	this->posX = p->destRect.x;
	this->posY = p->destRect.y;

	this->scaleX = 1.0f;
	this->scaleY = 1.0f;

	this->LocalToWorld.set(IDENTITY);
	this->ModelView.set(IDENTITY);

	SBNode *batch = SpriteBatchManager::Find(_spriteBatchName);
	assert( batch != 0 );
	batch->addSprite( _spriteName, this);

}

// Constructor make sure everything is initialized
GameSprite :: GameSprite( const char * const _Name, SpriteModel * const p)
{
	this->spriteModel = p;
	this->setName( _Name );

	this->angle = 0.0f;

	this->origWidth = p->destRect.width;
	this->origHeight = p->destRect.height;

	this->posX = p->destRect.x;
	this->posY = p->destRect.y;

	this->scaleX = 1.0f;
	this->scaleY = 1.0f;

	this->LocalToWorld.set(IDENTITY);
	this->ModelView.set(IDENTITY);
};

void GameSprite::transform( void )
{

	// create the tranformation matrices
	Matrix Scale(SCALE, this->scaleX, this->scaleY, 1.0f);
	Matrix RotZ( ROT_Z, angle );
	Matrix Trans( TRANS, this->posX, this->posY, 0.0f);

	// create the origin in the lower left corner
	Matrix TransToOriginLowerLeft( TRANS, -400.f, -300.f, 0.0f);

	// Create the local to world matrix (ie Model)
	this->LocalToWorld =  Scale * RotZ * Trans * TransToOriginLowerLeft;

	// Create the ModelView ( LocalToWorld * View)
	// Some pipelines have the project concatenated, others don't
	// Best to keep the separated, you can always join them with a quick multiply
   this->ModelView = this->LocalToWorld * Camera::getViewMatrix();

};

void GameSprite::setRenderState( void )
{
	// Blends for sprites
	glEnable(GL_BLEND);
	glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);

	// Bind the texture
	glBindTexture(GL_TEXTURE_2D, this->spriteModel->textureID);

	// Use the stock shader
	shaderManager.UseStockShader(GLT_SHADER_SPRITE,
								&ModelView,
								&Camera::getProjMatrix(),
								0);

};

void GameSprite::draw( void )
{
	if( display )
	{
		glBindVertexArray(this->spriteModel->vao);

		/*  render primitives from array data */
		// (GLenum  mode,  GLsizei  count,  GLenum  type,  const GLvoid *  indices);
		glDrawElements(GL_TRIANGLES, 3*2, GL_UNSIGNED_SHORT, 0);   //The starting point of the IBO
	}

};

void GameSprite::privDraw()
{
	transform();
	setRenderState();
	draw();
}


text:
package org.basex.http.rest;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

import org.basex.core.*;
import org.basex.core.cmd.*;
import org.basex.http.*;
import org.basex.query.value.type.*;

/**
 * Evaluate queries via REST.
 *
 * @author BaseX Team 2005-16, BSD License
 * @author Christian Gruen
 */
class RESTQuery extends RESTCmd {
  /** External variables. */
  private final Map<String, String[]> vars;
  /** Optional context value. */
  private final String value;

  /**
   * Constructor.
   * @param session REST Session
   * @param vars external variables
   * @param value context value
   */
  RESTQuery(final RESTSession session, final Map<String, String[]> vars, final String value) {
    super(session);
    this.vars = vars;
    this.value = value;
  }

  @Override
  protected void run0() throws IOException {
    query(session.context.soptions.get(StaticOptions.WEBPATH));
  }

  /**
   * Evaluates the specified query.
   * @param path query path
   * @throws HTTPException REST exception
   * @throws IOException I/O exception
   */
  void query(final String path) throws IOException {
    // set base path and serialization parameters
    final HTTPContext http = session.http;
    context.options.set(MainOptions.QUERYPATH, path);
    context.options.set(MainOptions.SERIALIZER, http.sopts());
    http.initResponse();

    for(final Command cmd : cmds) {
      if(cmd instanceof XQuery) {
        final XQuery xq = (XQuery) cmd;
        // create query instance
        if(value != null) xq.bind(null, value, NodeType.DOC.toString());

        // bind HTTP context and external variables
        xq.http(http);
        for(final Entry<String, String[]> e : vars.entrySet()) {
          final String key = e.getKey();
          final String[] val = e.getValue();
          if(val.length == 2) xq.bind(key, val[0], val[1]);
          if(val.length == 1) xq.bind(key, val[0]);
        }

        // initializes the response with query serialization options
        http.sopts().assign(xq.parameters(context));
        http.initResponse();
      }
      // run command
      run(cmd, http.res.getOutputStream());
    }
  }

  /**
   * Creates a new instance of this command.
   * @param session REST session
   * @param query query
   * @param vars external variables
   * @param val context value
   * @return command
   * @throws IOException I/O exception
   */
  @SuppressWarnings("unused")
  static RESTQuery get(final RESTSession session, final String query,
      final Map<String, String[]> vars, final String val) throws IOException {

    open(session);
    session.add(new XQuery(query));
    return new RESTQuery(session, vars, val);
  }
}


text:
RSpec.feature 'Sign In', type: :feature do

  background do
    @user = create(:user, email: 'email@person.com', password: 'secret', password_confirmation: 'secret')
    visit spree.login_path
  end

  scenario 'ask user to sign in' do
    visit spree.admin_path
    expect(page).not_to have_text 'Authorization Failure'
  end

  scenario 'let a user sign in successfully' do
    fill_in 'Email', with: @user.email
    fill_in 'Password', with: @user.password
    click_button 'Login'

    expect(page).to have_text 'Logged in successfully'
    expect(page).not_to have_text 'Login'
    expect(page).to have_text 'Logout'
    expect(current_path).to eq '/'
  end

  scenario 'show validation erros' do
    fill_in 'Email', with: @user.email
    fill_in 'Password', with: 'wrong_password'
    click_button 'Login'

    expect(page).to have_text 'Invalid email or password'
    expect(page).to have_text 'Login'
  end

  scenario 'allow a user to access a restricted page after logging in' do
    user = create(:admin_user, email: 'admin@person.com', password: 'password', password_confirmation: 'password')
    visit spree.admin_path

    fill_in 'Email', with: user.email
    fill_in 'Password', with: user.password
    click_button 'Login'

    expect(page).to have_text 'admin@person.com'
    expect(current_path).to eq '/admin/orders'
  end

  it "should store the user previous location" do
    visit spree.account_path
    fill_in "Email", with: @user.email
    fill_in "Password", with: @user.password
    click_button "Login"
    expect(current_path).to eq "/account"
  end
end


text:
> 基于 Vue jQuery Bootstrap的组件框架
> 外部依赖于jquery.js
> 运用于 vue组件

## Build Setup

```bash
# install dependencies
npm install

# 开发环境
npm run dev

# 生成vue-admin-bootstrap
npm run build

# 生成文档
npm run build-docs

```

## Documentation

详细的介绍, 请看[docs](https://liyanlong.github.io/vue-admin-bootstrap)

## How To Use

### Browser globals
``` html
<script src="http://cdn.bootcss.com/vue/1.0.26/vue.min.js"></script>
<script src="http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="dist/js/vue-admin-bootstrap.js"></script>
<script>
var app = new Vue({
    el: 'body',
    data: {
    },
    components: {
        modal: VueAdminBootStrap.components.Modal
    }
});
</script>
```

## LINCENSE
vue-admin-bootstrap is licensed under [The MIT License](LICENSE).


text:
//
//  DataManager.m
//  Videoplayer
//
//  Created by heiniz on 7/1/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DataManager.h"

@implementation DataManager

@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;

@synthesize dataConnector;

static DataManager *sharedInstance = nil;

// Get the shared instance and create it if necessary.
+ (DataManager *)sharedInstance {
    if (sharedInstance == nil) {
        sharedInstance = [[super alloc] init];
    }

    return sharedInstance;
}

// We can still have a regular init method, that will get called the first time the Singleton is used.
- (id)init
{
    self = [super init];

    if (self) {
        dataConnector = [DataConnector sharedInstance];
    }

    return self;
}

// Equally, we don't want to generate multiple copies of the singleton.
- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

#pragma mark -
#pragma mark Database

- (void) deleteObject: (NSManagedObject *) object{
    [[self managedObjectContext] deleteObject:object];
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;

    if (__managedObjectContext != nil)
    {
        if ([__managedObjectContext hasChanges] && ![__managedObjectContext save:&error])
        {
            /*
             Replace this implementation with code to handle the error appropriately.

             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
             */
            NSLog(@"Failed to save to data store: %@", [error localizedDescription]);
            NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
            if(detailedErrors != nil && [detailedErrors count] > 0) {
                for(NSError* detailedError in detailedErrors) {
                    NSLog(@"  DetailedError: %@", [detailedError userInfo]);
                }
            }
            else {
                NSLog(@"  %@", [error userInfo]);
            }
            abort();
        }
    }
}

- (void) deleteDatabase{
    NSURL *storeURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"Player.sqlite"];

    //in case of errors in persistance store use this to delete current store
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
}

#pragma mark - Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil)
    {
        return __managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}

/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil)
    {
        return __managedObjectModel;
    }
    //mom because no versioning. in case of arror try out momd
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Player" withExtension:@"momd"];

    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }

    NSURL *storeURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"Player.sqlite"];

    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return __persistentStoreCoordinator;
}

#pragma mark - Object creation

- (Actor *)createActorFrom:(NSDictionary *)actorDict{
    Actor* actor = (Actor *)[NSEntityDescription insertNewObjectForEntityForName:@"Actor" inManagedObjectContext:[self managedObjectContext]];
    actor.actorID = [[actorDict objectForKey:@"id"] stringValue];
    actor.name = [actorDict objectForKey:@"name"];

    NSString *bio = [actorDict objectForKey:@"biography"];
    if (bio == (id)[NSNull null] || bio.length == 0 ){
        actor.biography = @"Not available";
    }else {
        //initial Wikipedia annotation is redundant
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\.| |\\n)*from Wikipedia, the free encyclopedia(\\.| |\\n)*" options:NSRegularExpressionCaseInsensitive error:nil];
        actor.biography = [regex stringByReplacingMatchesInString:bio options:0 range:NSMakeRange(0, [bio length]) withTemplate:@""];
    }

    NSString *birthday = [actorDict objectForKey:@"birthday"];
    if (birthday == (id)[NSNull null] || birthday.length == 0 ){
        actor.birthdate = @"-";
    }else {
        actor.birthdate = birthday;
    }

    NSString *birthplace = [actorDict objectForKey:@"place_of_birth"];
    if (birthplace == (id)[NSNull null] || birthplace.length == 0 ){
        actor.birthplace = @"-";
    }else {
        actor.birthplace = birthplace;
    }

    actor.character = [actorDict objectForKey:@"character"];

    NSLog(@"Downloading picture of %@", actor.name);
    NSString *actorImage = [NSString stringWithFormat:@"%@%@%@?%@", BASEPATH, PROFILESIZEMEDIUM, [actorDict objectForKey:@"profile_path"], TMDB_APIKEY];
    NSURL *posterUrl = [NSURL URLWithString: actorImage];
    actor.picture = UIImagePNGRepresentation([self posterWithURL:posterUrl]);

    return actor;
}

- (Movie *)createMovie:(NSString *) movieTitle withPath:(NSURL *) movieURL{
    Movie* movie = (Movie *)[NSEntityDescription insertNewObjectForEntityForName:@"Movie" inManagedObjectContext:[self managedObjectContext]];
    Genre* genre = (Genre *)[NSEntityDescription insertNewObjectForEntityForName:@"Genre" inManagedObjectContext:[self managedObjectContext]];

    [dataConnector setupMovie:movieTitle withPath:movieURL];

    movie.title = movieTitle;
    movie.imdbRating = dataConnector.stringForIMDBRating;
    movie.imdbID = dataConnector.rottenConnector.stringForIMDBID;
    movie.rottenCriticRating = dataConnector.stringForCriticsRating;
    movie.rottenAudienceRating = dataConnector.stringForAudienceRating;
    movie.rottenID = dataConnector.rottenConnector.movieID;
    movie.plot = [dataConnector.stringForDescription stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    movie.releaseDate = dataConnector.stringForReleaseYear;
    movie.runningTimeInSec = dataConnector.stringForRuntime;
    movie.filePath = movieURL.absoluteString;

    NSLog(@"Downloading poster for %@", movieTitle);
    NSURL *posterUrl = [NSURL URLWithString: [dataConnector stringForPoster]];
    movie.poster = UIImagePNGRepresentation([self posterWithURL:posterUrl]);

    genre.name = dataConnector.stringForGenre;
    [genre addMoviesObject:movie];
    [movie addGenresObject:genre];

    int order = 0;
    for (NSDictionary *actorJSON in dataConnector.cast) {
        Actor *actor = [self getActorWithJSONData:actorJSON];
        actor.order = [NSNumber numberWithInt:order];
        order ++;
        [actor addMoviesObject:movie];
        [movie addActorsObject:actor];
    }

    for (NSString *triviaItem in dataConnector.trivia) {
        Trivia* trivia = (Trivia *)[NSEntityDescription insertNewObjectForEntityForName:@"Trivia" inManagedObjectContext:[self managedObjectContext]];
        [trivia setTrivia:[triviaItem stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]];
        [trivia setMovie:movie];
        [movie addTriviasObject:trivia];
    }

    [self saveContext];

    return movie;
}

- (UIImage *)posterWithURL:(NSURL *) posterUrl{
    if (posterUrl == nil){
        return [UIImage imageNamed:@"silhouette250x300"];
    }else{
        return [UIImage imageWithData: [NSData dataWithContentsOfURL:posterUrl]];
    }
}

- (Actor *)getActorWithJSONData:(NSDictionary *) jsonData{

    NSNumber *actorID = [jsonData objectForKey:@"id"];

    Actor* result = nil;
    // Set up the fetched results controller.
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Actor" inManagedObjectContext:[[DataManager sharedInstance] managedObjectContext]];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:
                              @"actorID LIKE %@",
                              [actorID stringValue]];

    [fetchRequest setPredicate:predicate];

    NSError *error = nil;
    NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
    if (!error){
        if ([fetchedObjects count] == 0) {
            result = [self createActorFrom:jsonData];
        }else {
            //fetch movie
            result = [fetchedObjects objectAtIndex:0];
        }
    }
    return result;

}

- (Movie *)getMovie:(NSString *) movieTitle withPath:(NSURL *) movieURL{
    Movie* result = nil;
    // Set up the fetched results controller.
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Movie" inManagedObjectContext:[[DataManager sharedInstance] managedObjectContext]];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:
                              @"filePath LIKE %@",
                              movieURL.absoluteString];

    [fetchRequest setPredicate:predicate];

    NSError *error = nil;
    NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
    if (!error){
        if ([fetchedObjects count] == 0) {
            result = [self createMovie:movieTitle withPath:movieURL];
        }else {
            //fetch movie
            result = [fetchedObjects objectAtIndex:0];
        }
    }
    return result;
}

/*
 Records sound from a certain position in movie and creates a fingerprint.
 Then sends finderprint to server asynchronously.

 TODO: Needs refactoring into another class

 */
- (void)recognizeSong: (NSURL *) songURL inInterval:(CMTimeRange) range withPauseTime:(NSNumber *) pauseTime{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSURL* destinationURL = [NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:@"temp_data"]];
    [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:nil];

    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:songURL options:nil];
    [asset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:@"tracks"] completionHandler:^ {

        NSArray* assets = [asset tracksWithMediaType:AVMediaTypeAudio];
        AVAssetTrack* audioTrack = [assets objectAtIndex:0];
        AVMutableComposition* audioComposition = [AVMutableComposition composition];
        AVMutableCompositionTrack* audioCompositionTrack = [audioComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        [audioCompositionTrack insertTimeRange:range ofTrack:audioTrack atTime:kCMTimeZero error:nil];

        AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:audioComposition presetName:AVAssetExportPresetPassthrough];
        exportSession.outputURL = destinationURL;
        exportSession.outputFileType = AVFileTypeAppleM4A;

        [exportSession exportAsynchronouslyWithCompletionHandler: ^(void) {

            if (exportSession.status == AVAssetExportSessionStatusCompleted) {
                NSString *outPath = [documentsDirectory stringByAppendingPathComponent:@"temp_data"];
                NSLog(@"done now. %@", outPath);
                //[statusLine setText:@"analysing..."];
                char * code = GetPCMFromFile((char*) [outPath  cStringUsingEncoding:NSASCIIStringEncoding]);

                NSString *songTitle = [dataConnector recognizeSongFromCode:code];
                NSLog(@"song = %@", songTitle);
                NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:songTitle, @"title", pauseTime, @"time", nil];
                [[NSNotificationCenter defaultCenter] postNotificationName: @"MusicTitleFoundNotification" object:nil userInfo:userInfo];

            }
        }];
    }];

}

- (NSString *)recognizeFace:(UIImage *)image
{
    return [dataConnector recognizeFace:image];
}

@end


text:
Clazz.declarePackage ("J.adapter.readers.xtal");
Clazz.load (["J.adapter.smarter.AtomSetCollectionReader"], "J.adapter.readers.xtal.XcrysdenReader", ["JU.PT"], function () {
c$ = Clazz.decorateAsClass (function () {
this.nAtoms = 0;
this.animation = false;
this.unitCellData = null;
this.animationStep = 0;
Clazz.instantialize (this, arguments);
}, J.adapter.readers.xtal, "XcrysdenReader", J.adapter.smarter.AtomSetCollectionReader);
Clazz.prepareFields (c$, function () {
this.unitCellData =  Clazz.newFloatArray (9, 0);
});
Clazz.overrideMethod (c$, "initializeReader",
function () {
this.doApplySymmetry = true;
});
Clazz.overrideMethod (c$, "checkLine",
function () {
if (this.line.contains ("ANIMSTEP")) {
this.readNostep ();
} else if (this.line.contains ("CRYSTAL")) {
this.setFractionalCoordinates (false);
} else if (this.line.contains ("PRIMVEC")) {
this.readUnitCell ();
} else if (this.line.contains ("PRIMCOORD")) {
this.readCoordinates ();
}return true;
});
Clazz.defineMethod (c$, "readNostep",
 function () {
this.animation = true;
});
Clazz.defineMethod (c$, "readUnitCell",
 function () {
this.setSymmetry ();
this.fillFloatArray (null, 0, this.unitCellData);
this.setUnitCell ();
});
Clazz.defineMethod (c$, "setUnitCell",
 function () {
this.addExplicitLatticeVector (0, this.unitCellData, 0);
this.addExplicitLatticeVector (1, this.unitCellData, 3);
this.addExplicitLatticeVector (2, this.unitCellData, 6);
});
Clazz.defineMethod (c$, "setSymmetry",
 function () {
this.applySymmetryAndSetTrajectory ();
this.asc.newAtomSet ();
this.setSpaceGroupName ("P1");
this.setFractionalCoordinates (false);
});
Clazz.defineMethod (c$, "readCoordinates",
 function () {
var atomStr = JU.PT.getTokens (this.rd ());
this.nAtoms = Integer.parseInt (atomStr[0]);
this.setFractionalCoordinates (false);
var counter = 0;
while (counter < this.nAtoms && this.rd () != null) {
var tokens = this.getTokens ();
this.addAtomXYZSymName (tokens, 1, null, J.adapter.smarter.AtomSetCollectionReader.getElementSymbol (Integer.parseInt (tokens[0])));
counter++;
}
this.asc.setAtomSetName (this.animation ? "Structure " + (this.animationStep++) : "Initial coordinates");
});
});


text:
from springfield.entity import Entity, FlexEntity
from springfield.types import Empty

__all__ = [
    'Entity',
    'FlexEntity',
    'Empty'
]