text:
import _ from 'lodash';
import path from 'path';
import * as ReactRouter from 'react-router';
import Transmit from 'react-transmit';

const routesContainer = require(path.resolve('./client/containers/routes'));

global.__SERVER__ = true;

exports.index = function index(req, res) {
  const webserver = process.env.NODE_ENV === 'production' ? '' : `//${req.hostname}:8080`;

  const location = req.originalUrl;

  const routes = routesContainer;

  ReactRouter.match({ routes, location }, (error, redirectLocation, renderProps) => {
    if (redirectLocation) {
      res.redirect(`${redirectLocation.pathname}${redirectLocation.search}/`);
      return;
    }

    if (error || !renderProps) {
      // callback(error);
      res.status(400);
      return;
    }

    Transmit.renderToString(ReactRouter.RouterContext, renderProps)
      .then(({ reactString, reactData }) => {
        const cssFiles = _.map(res.app.locals.cssFiles,
         (cssFile) => {
           if (_.isString(cssFile)) {
             return `<link rel="stylesheet" href="${cssFile}" />`;
           }

           return `<link rel="stylesheet" integrity="${cssFile.integrity}"` +
                  ` href="${cssFile.href}" crossorigin="anonymous" />`;
         }).join('');

        const template = (
`<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
    <base href="/">
    <title>${res.app.locals.title}</title>
    <meta name="description" content="${res.app.locals.description}">
    <link rel="shortcut icon" href="/favicon.ico">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <meta property="fb:app_id" content="${res.app.locals.facebookAppId}">
    <meta property="og:site_name" content="${res.app.locals.title}">
    <meta property="og:locale" content="en_US">
    <meta property="og:title" content="${res.app.locals.title}">
    <meta property="og:description" content="${res.app.locals.description}">
    <meta property="og:url" content="${res.locals.url}">
    <meta property="og:image" content="${res.app.locals.logo}">
    <meta property="og:card" content="summary">
    <meta property="og:type" content="website">
    <meta property="og:site" content="@viatsko">
    <meta property="og:creator" content="@viatsko">

    <meta name="twitter:title" content="${res.app.locals.title}">
    <meta name="twitter:description" content="${res.app.locals.description}">
    <meta name="twitter:url" content="${res.locals.url}">
    <meta name="twitter:image" content="${res.app.locals.logo}">

    <link href="${res.app.locals.favicon}" rel="shortcut icon" type="image/x-icon">

    ${cssFiles}

${reactString}

`
        );

        res.send(Transmit.injectIntoMarkup(template, reactData, [`${webserver}/client.js`]));
      });
  });
};


text:
package com.google.cloud.bigtable.hbase.async;

import static com.google.cloud.bigtable.hbase.test_env.SharedTestEnvRule.COLUMN_FAMILY;
import static java.util.stream.Collectors.toList;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.AsyncTable;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ScanResultConsumer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Test to make sure that basic {@link AsyncTable} operations work
 * @author sduskis
 */
@RunWith(JUnit4.class)
public class TestAsyncBatch extends AbstractAsyncTest {

  @Test
  public void testBasicAsyncOps() throws Exception {
    System.out.println("TestBasicAsyncOps");
    byte[][] rowKeys = dataHelper.randomData("TestBasicAsyncOps-", 5);
    byte[][] testQualifiers = dataHelper.randomData("testQualifier-", 5);
    byte[][] testValues = dataHelper.randomData("testValue-", 5);
    testPutsGetsDeletes(true, rowKeys, testQualifiers, testValues);
  }

  static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> futures) {
    return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
        .thenApply(v -> futures.stream().map(f -> f.getNow(null)).collect(toList()));
  }

  private void testPutsGetsDeletes(boolean doGet, byte[][] rowKeys, byte[][] testQualifiers,
      byte[][] testValues) throws IOException, InterruptedException, ExecutionException {
    AsyncTable<ScanResultConsumer> table = getDefaultAsyncTable();

    // setup
    List<Get> gets = new ArrayList<>();
    List<Put> puts = new ArrayList<>();
    List<Delete> deletes = new ArrayList<>();
    for (int i = 0; i < rowKeys.length; i++) {
      puts.add(new Put(rowKeys[i])
        .addColumn(COLUMN_FAMILY, testQualifiers[i], testValues[i]));

      gets.add(new Get(rowKeys[i])
        .addColumn(COLUMN_FAMILY, testQualifiers[i]));

      deletes.add(new Delete(rowKeys[i]));
    }

    Stopwatch stopwatch = new Stopwatch();
    // Put
    allOf(table.put(puts)).get();
    stopwatch.print("Put took %d ms");

    // Get

    // Do the get on some tests, but not others.  The rationale for that is to do performance
    // testing on large values.
    if (doGet) {
      stopwatch.print("Get took %d ms");
      List<Result> results = allOf(table.get(gets)).get();
      Assert.assertEquals(rowKeys.length, results.size());
      for (int i = 0; i < rowKeys.length; i++) {
        Result result = results.get(i);
        Assert.assertTrue(result.containsColumn(COLUMN_FAMILY, testQualifiers[i]));
        List<Cell> cells = result.getColumnCells(COLUMN_FAMILY, testQualifiers[i]);
        Assert.assertEquals(1, cells.size());
        Assert.assertTrue(CellUtil.matchingValue(cells.get(0), testValues[i]));
      }
      stopwatch.print("Verifying took %d ms");
    }
    // Delete
    allOf(table.delete(deletes)).get();
    stopwatch.print("Delete took %d ms");

    // Confirm deleted
    List<Boolean> exists = table.existsAll(gets).get();
    Assert.assertNotNull(exists);
    Assert.assertEquals(rowKeys.length, exists.size());
    for (Boolean b : exists) {
      Assert.assertFalse(b);
    }
    stopwatch.print("Exists took %d ms");
  }

  private class Stopwatch {
    long lastCheckin = System.currentTimeMillis();

    private void print(String string) {
      long now = System.currentTimeMillis();
      logger.info(string, now - lastCheckin);
      lastCheckin = now;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.sap.cloud.lm.sl.cf.core.util;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;

public class SecurityUtilTest {

    @ParameterizedTest
    @MethodSource
    void testGetTokenUserInfo(String userId, String username, String tokenString, String exchangedTokenString, UserInfo expectedUserInfo) {
        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(tokenString);
        Map<String, Object> additionalInformation = setAdditionalInformation(userId, username, tokenString, exchangedTokenString);
        token.setAdditionalInformation(additionalInformation);
        UserInfo userInfo = SecurityUtil.getTokenUserInfo(token);
        assertEquals(expectedUserInfo.getId(), userInfo.getId());
        assertEquals(expectedUserInfo.getName(), userInfo.getName());
        assertEquals(expectedUserInfo.getToken()
            .getValue(),
            userInfo.getToken()
                .getValue());
    }

    public static Stream<Arguments> testGetTokenUserInfo() {
        return Stream.of(
        // @formatter:off
            // (1) UserInfo with user token
            Arguments.of("cf","CF_USER", "dUTjdafgtw3wRUMkt4XDu2IidcEHNPoh", null, new UserInfo("cf", "CF_USER", new DefaultOAuth2AccessToken("dUTjdafgtw3wRUMkt4XDu2IidcEHNPoh"))),
            // (2) UserInfo with exchanged token
            Arguments.of("cf","CF_USER", "dUTjdafgtw3wRUMkt4XDu2IidcEHNPoh", "Xk2s5nIQPqjzoZ9KPwL2uPUhuiuUsbm2",
                new UserInfo("cf", "CF_USER", new DefaultOAuth2AccessToken("Xk2s5nIQPqjzoZ9KPwL2uPUhuiuUsbm2")))
        // @formatter:on
        );
    }

    private Map<String, Object> setAdditionalInformation(String userid, String username, String tokenString, String exchangedTokenString) {
        Map<String, Object> additionalInformationMap = new HashMap<>();
        additionalInformationMap.put("user_name", username);
        additionalInformationMap.put("user_id", userid);
        additionalInformationMap.put("exchangedToken", exchangedTokenString);
        return additionalInformationMap;
    }

}


text:
#region License
//
// Author: Nate Kohari <nkohari@gmail.com>
// Copyright (c) 2007-2008, Enkari, Ltd.
//
// 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.
//
#endregion
#region Using Directives
using System;
using Ninject.Core.Infrastructure;
#endregion

namespace Ninject.Core.Planning
{
	/// <summary>
	/// Creates <see cref="IActivationPlan"/>s that describe the means by which an object should
	/// be created and injected.
	/// </summary>
	public class StandardActivationPlanFactory : KernelComponentBase, IActivationPlanFactory
	{
		/*----------------------------------------------------------------------------------------*/
		/// <summary>
		/// Creates an empty activation plan for the specified type.
		/// </summary>
		/// <param name="type">The type to create the plan for.</param>
		/// <returns>The specified plan.</returns>
		public IActivationPlan Create(Type type)
		{
			return new StandardActivationPlan(type);
		}
		/*----------------------------------------------------------------------------------------*/
	}
}


text:
'use strict';

angular.module('common').factory('hpUtils',
	['Authentication', function (Authentication) {
		function refineInputDate(inputDate) {
			var dateRegex = /^([0-9]{2})([0-9]{2})([0-9]{4})$/g;
			if (dateRegex.test(inputDate)) {
				return inputDate.replace(inputDate, '$1.$2.$3');
			}
			return inputDate;
		}

		function firstDayOfNextMonth() {
			var current = new Date();
			return new Date(current.getFullYear(), current.getMonth() + 1, 1);
		}

		function lastDayOfNextMonth() {
			var current = new Date();
			return new Date(current.getFullYear(), current.getMonth() + 2, 0);
		}

		function firstDayOfCurrentMonth() {
			var current = new Date();
			return new Date(current.getFullYear(), current.getMonth(), 1);
		}

		function lastDayOfCurrentMonth() {
			var current = new Date();
			return new Date(current.getFullYear(), current.getMonth() + 1, 0);
		}

		function firstDayOfLastMonth() {
			var current = new Date();
			return new Date(current.getFullYear(), current.getMonth() - 1, 1);
		}

		function lastDayOfLastMonth() {
			var current = new Date();
			return new Date(current.getFullYear(), current.getMonth(), 0);
		}

		function firstDayOfCurrentYear() {
			var current = new Date();
			return new Date(current.getFullYear(), 0, 1);
		}

		function lastDayOfCurrentYear() {
			var current = new Date();
			return new Date(current.getFullYear() + 1, 0, 0);
		}

		function hasAuthorization(allowedRoles, userRoles) {
			var interSetRoles = _.difference(allowedRoles, userRoles);
			return interSetRoles.length < allowedRoles.length;
		}

		function userHasRoles(allowedRoles) {
			var userRoles = Authentication.user && Authentication.user.roles || [];
			var interSetRoles = _.difference(allowedRoles, userRoles);
			return interSetRoles.length < allowedRoles.length;
		}

		/**
		 * Prepend vietnam country code +84 to phone number if it has exactly 10 digits
		 * @param phoneNumber
		 * @returns {string}
		 */
		function refinePhoneNumber(phoneNumber) {
			if (/^[0-9]{10}$/g.test(phoneNumber)) {
				return '+84' + phoneNumber.substr(1);
			} else {
				return phoneNumber;
			}
		}

        function objectToArray(object, propertiesArray) {
            var result = [];
            _.forEach(propertiesArray, function(property) {
                result.push(object[property].toString());
            });
            return result;
        }

		return {
			refineInputDate: refineInputDate,
			firstDayOfNextMonth: firstDayOfNextMonth,
			lastDayOfNextMonth: lastDayOfNextMonth,
			firstDayOfCurrentMonth: firstDayOfCurrentMonth,
			lastDayOfCurrentMonth: lastDayOfCurrentMonth,
			firstDayOfLastMonth: firstDayOfLastMonth,
			lastDayOfLastMonth: lastDayOfLastMonth,
			firstDayOfCurrentYear: firstDayOfCurrentYear,
			lastDayOfCurrentYear: lastDayOfCurrentYear,
			hasAuthorization: hasAuthorization,
			userHasRoles: userHasRoles,
			refinePhoneNumber: refinePhoneNumber,
            objectToArray: objectToArray
		};
	}]);


text:
namespace Poco {
namespace XML {

NodeFilter::~NodeFilter()
{
}

} } // namespace Poco::XML


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Cron;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

use Oro\Bundle\CronBundle\Entity\Manager\DeferredScheduler;

abstract class AbstractTriggerCronScheduler implements LoggerAwareInterface
{
    /** @var DeferredScheduler */
    protected $deferredScheduler;

    /**
     * @param DeferredScheduler $deferredScheduler
     */
    public function __construct(DeferredScheduler $deferredScheduler)
    {
        $this->deferredScheduler = $deferredScheduler;
        $this->setLogger(new NullLogger());
    }

    /**
     * {@inheritdoc}
     */
    public function setLogger(LoggerInterface $logger)
    {
        if ($this->deferredScheduler instanceof LoggerAwareInterface) {
            $this->deferredScheduler->setLogger($logger);
        }
    }

    /**
     * @return void
     */
    public function flush()
    {
        $this->deferredScheduler->flush();
    }
}


text:
package myProject.pojo;

public class Status {
    final static public String STATUS_OK="OK";
    final static public String STATUS_WAITING_ANOTHER="WAITING_ANOTHER";
    final static public String STATUS_WAITING_YOU="WAITING_YOU";
}


text:
/*
07. Write a SQL query to find the number of all employees that have manager.
*/

USE TelerikAcademy

SELECT COUNT(*) AS [Number of Employees with manager]
FROM Employees e
WHERE e.ManagerID IS NOT NULL


text:
gulp-sequence
====
Run a series of gulp tasks in order.

[![NPM version][npm-image]][npm-url]
[![Build Status][travis-image]][travis-url]
[![Downloads][downloads-image]][downloads-url]

## Install

Install with [npm](https://npmjs.org/package/gulp-sequence)

```
npm install --save-dev gulp-sequence
```

## Usage

```js
var gulp = require('gulp')
var gulpSequence = require('gulp-sequence')

gulp.task('a', function (cb) {
  //... cb()
})

gulp.task('b', function (cb) {
  //... cb()
})

gulp.task('c', function (cb) {
  //... cb()
})

gulp.task('d', function (cb) {
  //... cb()
})

gulp.task('e', function (cb) {
  //... cb()
})

gulp.task('f', function () {
  // return stream
  return gulp.src('*.js')
})

// usage 1, recommend
// 1. run 'a', 'b' in parallel;
// 2. run 'c' after 'a' and 'b';
// 3. run 'd', 'e' in parallel after 'c';
// 3. run 'f' after 'd' and 'e'.
gulp.task('sequence-1', gulpSequence(['a', 'b'], 'c', ['d', 'e'], 'f'))

// usage 2
gulp.task('sequence-2', function (cb) {
  gulpSequence(['a', 'b'], 'c', ['d', 'e'], 'f', cb)
})

// usage 3
gulp.task('sequence-3', function (cb) {
  gulpSequence(['a', 'b'], 'c', ['d', 'e'], 'f')(cb)
})

gulp.task('gulp-sequence', gulpSequence('sequence-1', 'sequence-2', 'sequence-3'))
```

**with `gulp.watch`**:
```js
gulp.watch('src/**/*.js', function (event) {
  gulpSequence('a', 'b')(function (err) {
    if (err) console.log(err)
  })
})
```

## API

```js
var gulpSequence = require('gulp-sequence')
```

### gulpSequence('subtask1', 'subtask2',...[, callback])
return a [thunk](https://github.com/teambition/thunks) function.

```js
var gulp = require('gulp')
var gulpSequence = require('gulp-sequence')

gulp.task('test', gulpSequence(['a', 'b'], 'c', ['d', 'e'], 'f'))
```

### gulpSequence.use(gulp)
return a new gulpSequence function with the gulp. If you have some errors such as "task xxx is not defined", this will resolve it.

```js
var gulp = require('gulp')
var gulpSequence = require('gulp-sequence').use(gulp)

gulp.task('test', gulpSequence(['a', 'b'], 'c', ['d', 'e'], 'f'))
```

## License

MIT © [Teambition](https://www.teambition.com)

[npm-url]: https://npmjs.org/package/gulp-sequence
[npm-image]: http://img.shields.io/npm/v/gulp-sequence.svg

[travis-url]: https://travis-ci.org/teambition/gulp-sequence
[travis-image]: http://img.shields.io/travis/teambition/gulp-sequence.svg

[downloads-url]: https://npmjs.org/package/gulp-sequence
[downloads-image]: http://img.shields.io/npm/dm/gulp-sequence.svg?style=flat-square


text:
package org.apache.derby.impl.sql.execute;

import org.apache.derby.iapi.services.stream.HeaderPrintWriter;

import org.apache.derby.iapi.services.io.ArrayUtil;
import org.apache.derby.iapi.services.io.StoredFormatIds;
import org.apache.derby.iapi.services.io.FormatIdUtil;

import org.apache.derby.iapi.services.context.ContextManager;

import org.apache.derby.iapi.sql.dictionary.IndexRowGenerator;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.iapi.sql.dictionary.TableDescriptor;
import org.apache.derby.iapi.sql.conn.LanguageConnectionContext;
import org.apache.derby.iapi.sql.execute.ConstantAction;
import org.apache.derby.iapi.sql.execute.ExecRow;

import org.apache.derby.iapi.error.StandardException;

import org.apache.derby.iapi.store.access.StaticCompiledOpenConglomInfo;
import org.apache.derby.iapi.types.RowLocation;

import org.apache.derby.catalog.UUID;

import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;

import java.util.Properties;

/**
 *	This class  describes compiled constants that are passed into
 *	InsertResultSets.
 *
 */

public class InsertConstantAction extends WriteCursorConstantAction
{
	/********************************************************
	**
	**	This class implements Formatable. But it is NOT used
 	**	across either major or minor releases.  It is only
	** 	written persistently in stored prepared statements,
	**	not in the replication stage.  SO, IT IS OK TO CHANGE
	**	ITS read/writeExternal.
	**
	********************************************************/

	/* Which (0-based) columns are indexed */
	boolean[]	indexedCols;

	/* These variables are needed to support Autoincrement-- after an insert
	 * we need to remember the last autoincrement value inserted into the
	 * table and the user could do a search based on schema,table,columnname
	 */
	private String schemaName;
	private String tableName;
	private String columnNames[];

	/**
	 * An array of row location objects (0 based), one for each
	 * column in the table. If the column is an
	 * autoincrement table then the array points to
	 * the row location of the column in SYSCOLUMNS.
	 * if not, then it contains null.
	 */
    RowLocation[] autoincRowLocation;
	private long[] autoincIncrement;

    /** Position of autogenerated column */
    private transient   int firstAutoGenColumn = -1;
    final public boolean hasDeferrableChecks;

    String  identitySequenceUUIDString;

	// CONSTRUCTORS

	/**
	 * Public niladic constructor. Needed for Formatable interface to work.
	 *
	 */
    public  InsertConstantAction() {
        super();
        hasDeferrableChecks = false;
    }

	/**
	 *	Make the ConstantAction for an INSERT statement.
	 *
     *  @param tableDescriptor
	 *  @param conglomId	Conglomerate ID.
	 *	@param heapSCOCI	StaticCompiledOpenConglomInfo for heap.
	 *  @param irgs			Index descriptors
	 *  @param indexCIDS	Conglomerate IDs of indices
	 *	@param indexSCOCIs	StaticCompiledOpenConglomInfos for indexes.
	 *  @param indexNames   Names of indices on this table for error reporting.
	 *  @param deferred		True means process as a deferred insert.
     *  @param hasDeferrableChecks
     *                      The target table has deferrable CHECK constraints
	 *  @param targetProperties	Properties on the target table.
	 *	@param targetUUID	UUID of target table
	 *	@param lockMode		The lockMode to use on the target table
	 *	@param fkInfo		Array of structures containing foreign key info,
	 *						if any (may be null)
	 *	@param triggerInfo	Array of structures containing trigger info,
	 *						if any (may be null)
     *  @param streamStorableHeapColIds Null for non rep. (0 based)
	 *  @param indexedCols	boolean[] of which (0-based) columns are indexed.
	 *  @param singleRowSource		Whether or not source is a single row source
	 *  @param autoincRowLocation Array of rowlocations of autoincrement values
	 * 							  in SYSCOLUMNS for each ai column.
	 *  @param underMerge   True if this is an action of a MERGE statement.
	 *  @param identitySequenceUUIDString   For 10.11 and higher, the handle on the sequence for the identity column
	 */
    InsertConstantAction(TableDescriptor tableDescriptor,
								long				conglomId,
								StaticCompiledOpenConglomInfo heapSCOCI,
								IndexRowGenerator[]	irgs,
								long[]				indexCIDS,
								StaticCompiledOpenConglomInfo[] indexSCOCIs,
								String[]			indexNames,
								boolean				deferred,
                                boolean             hasDeferrableChecks,
								Properties			targetProperties,
								UUID				targetUUID,
								int 				lockMode,
								FKInfo[]			fkInfo,
								TriggerInfo			triggerInfo,
								int[]               streamStorableHeapColIds,
								boolean[]			indexedCols,
								boolean				singleRowSource,
                                RowLocation[]		autoincRowLocation,
								boolean		underMerge,
								String		identitySequenceUUIDString)
	{
		super(conglomId,
			  heapSCOCI,
			  irgs,
			  indexCIDS,
			  indexSCOCIs,
			  indexNames,
			  deferred,
			  targetProperties,
			  targetUUID,
			  lockMode,
			  fkInfo,
			  triggerInfo,
			  null,
			  null,
			  streamStorableHeapColIds,
			  singleRowSource,
			  underMerge
			  );
		this.indexedCols = indexedCols;
		this.autoincRowLocation = autoincRowLocation;
		this.schemaName = tableDescriptor.getSchemaName();
		this.tableName  = tableDescriptor.getName();
		this.columnNames = tableDescriptor.getColumnNamesArray();
		this.autoincIncrement = tableDescriptor.getAutoincIncrementArray();
		this.indexNames = indexNames;
        this.hasDeferrableChecks = hasDeferrableChecks;
        this.identitySequenceUUIDString = identitySequenceUUIDString;
	}

	// INTERFACE METHODS

	// Formatable methods
	public void readExternal (ObjectInput in)
		 throws IOException, ClassNotFoundException
	{
		Object[] objectArray = null;
		super.readExternal(in);
		indexedCols = ArrayUtil.readBooleanArray(in);

		// RESOLVEAUTOINCREMENT: this is the new stuff-- probably version!!
		objectArray = ArrayUtil.readObjectArray(in);

		if (objectArray != null)
		{
			// is there a better way to do cast the whole array?
			autoincRowLocation = new RowLocation[objectArray.length];
			for (int i = 0; i < objectArray.length; i++)
				autoincRowLocation[i] = (RowLocation)objectArray[i];
		}

		schemaName = (String)in.readObject();
		tableName  = (String)in.readObject();
		objectArray = ArrayUtil.readObjectArray(in);
		if (objectArray != null)
		{
			// is there a better way to do cast the whole array?
			columnNames = new String[objectArray.length];
			for (int i = 0; i < objectArray.length; i++)
				columnNames[i] = (String)objectArray[i];
		}

		autoincIncrement = ArrayUtil.readLongArray(in);
        identitySequenceUUIDString = (String) in.readObject();
	}

	/**
	 * Write this object to a stream of stored objects.
	 *
	 * @param out write bytes here.
	 *
	 * @exception IOException		thrown on error
	 */
	public void writeExternal( ObjectOutput out )
		 throws IOException
	{
		super.writeExternal(out);
		ArrayUtil.writeBooleanArray(out, indexedCols);
		ArrayUtil.writeArray(out, autoincRowLocation);
		out.writeObject(schemaName);
		out.writeObject(tableName);
		ArrayUtil.writeArray(out, columnNames);
		ArrayUtil.writeLongArray(out, autoincIncrement);
        out.writeObject( identitySequenceUUIDString );
	}

    /** Get the 0-based position of the autogenerated column */
    public  int     getAutoGenColumn()
    {
        if ( !hasAutoincrement() ) { return -1; }
        if ( firstAutoGenColumn < 0 )
        {
            for ( int i = 0; i < autoincIncrement.length; i++ )
            {
                if ( autoincIncrement[ i ] > 0 )
                {
                    firstAutoGenColumn = i;
                    break;
                }
            }
        }

        return firstAutoGenColumn;
    }

	/**
	  *	Gets the name of the schema that the table is in
	  *
	  *	@return	schema name
	  */
	public String getSchemaName() { return schemaName; }

	/**
	  *	Gets the name of the table being inserted into
	  *
	  *	@return	name of table being inserted into
	  */
	public String getTableName() { return tableName; }

	/**
	 * gets the name of the desired column in the taget table.
	 *
	 * @param 	i	the column number
	 */
	public String getColumnName(int i) { return columnNames[i]; }

	/**
	 * gets the increment value for a column.
	 *
	 * @param 	i 	the column number
	 */
	public long   getAutoincIncrement(int i) { return autoincIncrement[i]; }

	/**
	 * Does the target table has autoincrement columns.
	 *
	 * @return 	True if the table has ai columns
	 */
	public boolean hasAutoincrement()
	{
		return (autoincRowLocation != null);
	}

	/**
	 * gets the row location
	 */
    RowLocation[] getAutoincRowLocation()
	{
		return autoincRowLocation;
	}

	/**
	 * Get the formatID which corresponds to this class.
	 *
	 *	@return	the formatID of this class
	 */
	public	int	getTypeFormatId()	{ return StoredFormatIds.INSERT_CONSTANT_ACTION_V01_ID; }

	// CLASS METHODS

}


text:
      SUBROUTINE CHKXER( SRNAMT, INFOT, NOUT, INFO, OK )
*
*  Tests whether XERBLA has detected an error when it should.
*
*  Auxiliary routine for test program for Level 2 Blas.
*
*  -- Written on 10-August-1987.
*     Richard Hanson, Sandia National Labs.
*     Jeremy Du Croz, NAG Central Office.
*
*  =====================================================================
*
*     .. Scalar Arguments ..
      LOGICAL            OK
      CHARACTER*6        SRNAMT
      INTEGER            INFOT, INFO, NOUT
*     ..
*     .. Executable Statements ..
      IF( INFOT.NE.ABS( INFO )  ) THEN
         WRITE( NOUT, FMT = 9999 ) INFOT, SRNAMT
         OK = .FALSE.
      END IF
      RETURN
*
 9999 FORMAT( ' *** Illegal value of parameter number ', I2,
     $      ' not detected by ', A6, ' ***' )
*
*     End of CHKXER.
*
      END


text:
require 'time'

module Wayground
  module Event

    # A list of events for a specific day.
    # Includes the events that start on the day and multi-day events that started before the day.
    # Can determine which of those events carry over from the day to subsequent days.
    # :events must be events that start on :day.
    # :multiday must be events that started before :day and end on or after :day.
    class DayEvents
      attr_reader :events, :multiday

      def initialize(params)
        @day = params[:day]
        @events = params[:events] || []
        @multiday = params[:multiday] || []
      end

      def count
        @count ||= events.count + multiday.count
      end

      # Combines the events and multiday into one array, sorted by start_at time.
      def all
        (events + multiday).sort_by! do |event|
          time = event.start_at
          timezone = event.timezone
          timezone = ActiveSupport::TimeZone.new(timezone) if timezone
          timezone ||= Time.zone
          Time.new(2000, 1, 1, time.hour, time.min, time.sec, timezone.utc_offset)
        end
      end

      # The events (including multiday) from the day that carry over after the day.
      def carryover
        @carryover ||= determine_carryover_events + determine_carryover_multiday
      end

      private

      def determine_carryover_events
        events.select(&:multi_day?)
      end

      def determine_carryover_multiday
        multiday.select { |event| event.end_at.to_date > @day }
      end
    end

  end
end


text:
function checkEnv {
    if [ -z "$KEYCLOAK_ADMIN_USER" ]; then
        export KEYCLOAK_ADMIN_USER=admin
        echo "Using default keycloak admin user: $KEYCLOAK_ADMIN_USER"
    else
        echo "Using keycloak admin user: $KEYCLOAK_ADMIN_USER"
    fi
    if [ -z "$KEYCLOAK_ADMIN_PASSWORD" ]; then
        export KEYCLOAK_ADMIN_PASSWORD=admin
        echo "Using default keycloak admin password: $KEYCLOAK_ADMIN_PASSWORD"
    else
        echo "Using keycloak admin password: ${KEYCLOAK_ADMIN_PASSWORD:0:4}******"
    fi
    if [ -z "$KEYCLOAK_POSTGRES_HOST" ]; then
        export KEYCLOAK_POSTGRES_HOST="postgres"
        echo "Using default postgres host: $KEYCLOAK_POSTGRES_HOST"
    else
        echo "Using postgres host: $KEYCLOAK_POSTGRES_HOST"
    fi
    if [ -z "$KEYCLOAK_POSTGRES_PORT" ]; then
        export KEYCLOAK_POSTGRES_PORT="5432"
        echo "Using default postgres port: $KEYCLOAK_POSTGRES_PORT"
    else
        echo "Using postgres port: $KEYCLOAK_POSTGRES_PORT"
    fi
    if [ -z "$KEYCLOAK_POSTGRES_USER" ]; then
        export KEYCLOAK_POSTGRES_USER="keycloak"
        echo "Using default postgres user: $KEYCLOAK_POSTGRES_USER"
    else
        echo "Using postgres user: $KEYCLOAK_POSTGRES_USER"
    fi
    if [ -z "$KEYCLOAK_POSTGRES_PASSWORD" ]; then
        export KEYCLOAK_POSTGRES_PASSWORD="keycloak"
        echo "Using default postgres password: $KEYCLOAK_POSTGRES_PASSWORD"
    else
        echo "Using postgres password: ${KEYCLOAK_POSTGRES_PASSWORD:0:4}******"
    fi
    if [ -z "$KEYCLOAK_POSTGRES_DATABASE" ]; then
        export KEYCLOAK_POSTGRES_DATABASE="keycloak"
        echo "Using default postgres database: $KEYCLOAK_POSTGRES_DATABASE"
    else
        echo "Using postgres database: $KEYCLOAK_POSTGRES_DATABASE"
    fi
}

if [ $# -lt 1 ]; then
    exec /bin/bash
fi

if [ $1 != "server" ]; then
    exec $@
fi

here=`cd $(dirname $BASH_SOURCE); pwd`
checkEnv

$here/add-user-keycloak.sh --user $KEYCLOAK_ADMIN_USER --password $KEYCLOAK_ADMIN_PASSWORD &&
    exec $here/standalone.sh -Dfile.encoding=UTF-8 -b 0.0.0.0 --server-config standalone.xml


text:
require 'net/http'
require 'uri'
require 'json'

require 'webmock-rspec-helper'
require 'webmock/rspec'

WebMock.disable_net_connect!

class WebMock::RSpec::Helper::Rails
  def self.root
    Pathname.new File.expand_path('../..', __FILE__)
  end
end

describe '#webmock' do
  it 'mocks GET google using default response 200' do
    webmock :get, %r{google.com} => 'GET_google.json'
    response = GET 'http://google.com'
    expect(response.status).to eq 200
    expect(response.body['google']).to eq true
  end

  it 'mocks GET google with custom response code' do
    webmock :get, %r{google.com} => 'GET_google.999.json'
    response = GET 'http://google.com'
    expect(response.status).to eq 999
    expect(response.body['google']).to eq true
  end

  it 'accepts a block that returns the with options' do
    webmock :get, %r{google.com} => 'GET_google.json', with: Hash[query: { test: '123' }]
    expect { GET 'http://google.com' }.to raise_error WebMock::NetConnectNotAllowedError
    response = GET 'http://google.com?test=123'
    expect(response.status).to eq 200
  end

  it 'mocks GET google with an empty body and given status code' do
    webmock :get, %r{google.com} => 204
    response = GET 'http://google.com'
    expect(response.body).to eq ''
    expect(response.status).to eq 204
  end

  it 'mocks GET google with response headers' do
    webmock :get, %r{google.com} => 'GET_google.json', headers: { 'Content-Type' => 'text/html' }
    response = GET 'http://google.com'
    expect(response.content_type).to eq 'text/html'
  end
end

describe '#fetch_webmock' do
  it 'should provide json data as a hash' do
    expect(fetch_webmock(:GET_google).json).to eq('google' => true)
    expect(fetch_webmock('GET_google.999').json).to eq('google' => true)
  end

  it 'should access nested stubs' do
    expect(fetch_webmock(:nested, :GET_nested).json).to eq('nested' => true)
    expect(fetch_webmock('nested/GET_nested').json).to eq('nested' => true)
  end

  it 'should provide raw data as a verbatim string' do
    expect(fetch_webmock('GET_google.json').raw).to eq '{ "google": true }'
    expect(fetch_webmock(:GET_google).raw(:json)).to eq '{ "google": true }'
  end
end

def GET(url)
  response = Net::HTTP.get_response URI.parse(url)
  body = response.body ? JSON.parse(response.body) : ''
  OpenStruct.new status: response.code.to_i, body: body, content_type: response['Content-Type']
end


text:
package com.softwaremill.play24.it

import com.softwaremill.play24.AppApplicationLoader
import play.api.test.WithApplicationLoader

class IntegrationContext extends WithApplicationLoader(
  applicationLoader = new AppApplicationLoader
)


text:
interface ViewOptions<TModel> {
    model: TModel;
}

class View<TModel> {
    constructor(options: ViewOptions<TModel>) { }
    model: TModel;
}

class Model { }
class MyView extends View<Model> { }

var m: ViewOptions<Model> = { model: new Model() };
var aView = new View({ model: new Model() });
var aView2 = new View(m);
var myView = new MyView(m); // was error


text:
namespace T4WebFormsInjection.Tests.Modules
{
    using T4WebFormsInjection.Tests.Helper;

    using T4WFI.App.Code;
    using T4WFI.App.Modules;

    using Xunit;

    public class MyModule2Tests
    {
        [Fact]
        public void DependenciesCreated()
        {
            Target.CheckDependenciesAreConstructed<MyModule2>(Dependency.Create<IDummyInterface>(), Dependency.Create<IDummyInterface2>());
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:background="@drawable/find_head_line"
            android:gravity="center">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textSize="15sp"
                android:text="亚洲"/>
            <TextView
                android:id="@+id/find_Asia_num"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textSize="10sp"
                android:textColor="@color/orange"
                android:text="21"/>
        </LinearLayout>

    </LinearLayout>
</LinearLayout>


text:
import React from 'react';
import { GenericDataType } from '@superset-ui/core';
import ControlForm, {
  ControlFormRow,
  ControlFormItem,
  ControlFormItemSpec,
} from '../../../components/ControlForm';
import {
  SHARED_COLUMN_CONFIG_PROPS,
  SharedColumnConfigProp,
} from './constants';
import {
  ColumnConfig,
  ColumnConfigFormLayout,
  ColumnConfigInfo,
} from './types';

export type ColumnConfigPopoverProps = {
  column: ColumnConfigInfo;
  configFormLayout: ColumnConfigFormLayout;
  onChange: (value: ColumnConfig) => void;
};

export default function ColumnConfigPopover({
  column,
  configFormLayout,
  onChange,
}: ColumnConfigPopoverProps) {
  return (
    <ControlForm onChange={onChange} value={column.config}>
      {configFormLayout[
        column.type === undefined ? GenericDataType.STRING : column.type
      ].map((row, i) => (
        <ControlFormRow key={i}>
          {row.map(meta => {
            const key = typeof meta === 'string' ? meta : meta.name;
            const override =
              typeof meta === 'string'
                ? {}
                : 'override' in meta
                ? meta.override
                : meta.config;
            const props = {
              ...(key in SHARED_COLUMN_CONFIG_PROPS
                ? SHARED_COLUMN_CONFIG_PROPS[key as SharedColumnConfigProp]
                : undefined),
              ...override,
            } as ControlFormItemSpec;
            return <ControlFormItem key={key} name={key} {...props} />;
          })}
        </ControlFormRow>
      ))}
    </ControlForm>
  );
}


text:
class ConfigManager

  # The defaults for the config file
  DEFAULT = {
    :build_folder => "build",
    :copy_formats => ["js","css"]
  }

  @@config = {}

  # Access the configuration hash
  def self.config
    @@config
  end

  # A getter method for the config defaults
  def self.default
    DEFAULT
  end

  # Create a config file if there isn't yet one
  def self.init_config
    if File.exists?("#{Dir.pwd}/dinconfig.yaml")
      self.load_config("#{Dir.pwd}/dinconfig.yaml")
    else
      File.open("#{Dir.pwd}/dinconfig.yaml","w+") do |file|
        file.puts(DEFAULT.to_yaml)
      end
      self.load_config("#{Dir.pwd}/dinconfig.yaml")
    end
  end

  # Load the current config file
  def self.load_config(file_path)
    @@config = YAML.load(File.read(file_path))
  end
end


text:
package mcjty.rftoolsdim.blocks.shards;

import mcjty.lib.McJtyRegister;
import mcjty.rftoolsdim.RFToolsDim;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class DimensionalSmallBlocks extends Block {

    public DimensionalSmallBlocks() {
        super(Material.ROCK);
        setHardness(2.0f);
        setResistance(4.0f);
        setUnlocalizedName(RFToolsDim.MODID + "." + "dimensional_small_blocks");
        setRegistryName("dimensional_small_blocks");
        setLightLevel(0.6f);
        setCreativeTab(RFToolsDim.setup.getTab());
        McJtyRegister.registerLater(this, RFToolsDim.instance, ItemBlock::new);
    }

    @SideOnly(Side.CLIENT)
    public void initModel() {
        ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory"));
    }
}


text:
mongrey package
===============

.. automodule:: mongrey
    :members:
    :undoc-members:
    :show-inheritance:

Subpackages
-----------

.. toctree::

    mongrey.api
    mongrey.ext
    mongrey.helpers
    mongrey.server
    mongrey.storage
    mongrey.translations
    mongrey.web

Submodules
----------

.. automodule:: mongrey.cache
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: mongrey.constants
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: mongrey.exceptions
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: mongrey.policy
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: mongrey.utils
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: mongrey.validators
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: mongrey.version
    :members:
    :undoc-members:
    :show-inheritance:


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>Aplicativo de Acidentes</title>

  <link href="css/bootstrap.min.css" rel="stylesheet">

  <link href="css/3-col-portfolio.css" rel="stylesheet">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          Toggle navigation

        </button>
        Sinaliza

E-mail

          <input type="text" class="form-control" placeholder="Insira seu e-mail" aria-describedby="basic-addon1">

Senha

          <input type="password" class="form-control" placeholder="Insira sua senha" aria-describedby="basic-addon1">

        <button class="btn btn-info btn-block login" type="submit">Entrar</button>

          Registrar-se

          Esqueci a senha


text:
<!DOCTYPE HTML>
<html>
<head>
  <title>Secure img load</title>
  <script type="text/javascript" src="/MochiKit/Base.js"></script>
  <script type="text/javascript" src="/MochiKit/DOM.js"></script>
  <script type="text/javascript" src="/MochiKit/Style.js"></script>
  <script type="text/javascript" src="/MochiKit/Signal.js"></script>
  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
  <script type="text/javascript" src="mixedContentTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />

  <script class="testbody" type="text/javascript">

  loadAsInsecure = true;

  function runTest()
  {
    isSecurityState("insecure", "left insecure");
    finish();
  }

  function afterNavigationTest()
  {
    isSecurityState("insecure", "left insecure after renavigation");
    finish();
  }

  </script>
</head>

<body>
  <img src="https://example.com/tests/security/ssl/mixedcontent/moonsurface.jpg" />
</body>
</html>


text:
package storages.sql_commands;

import storages.connection_sources.ConnectionSource;
import storages.dto.UserInfo;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;

public class AddUserSqlCommand extends SqlCommand {

    public AddUserSqlCommand(ConnectionSource connectionSource, UserInfo userInfo) {
        super(connectionSource, INSERT_USER_STATEMENT);
        this.userInfo = userInfo;
    }

    @Override
    protected void addParameters(PreparedStatement preparedStatement) throws SQLException {
        String newUserId = UUID.randomUUID().toString();
        preparedStatement.setString(1, newUserId);
        preparedStatement.setString(2, userInfo.getGoogleIdentity());
        userInfo.setUserId(newUserId);
    }

    private static final String INSERT_USER_STATEMENT = "INSERT INTO Users Values (?, ?)";
    private UserInfo userInfo;
}


text:
#ifndef ScrollbarThemeMac_h
#define ScrollbarThemeMac_h

#include "core/platform/ScrollbarThemeComposite.h"

typedef id ScrollbarPainter;

namespace WebCore {

class ScrollbarThemeMac : public ScrollbarThemeComposite {
public:
    ScrollbarThemeMac();
    virtual ~ScrollbarThemeMac();

    void preferencesChanged();

    virtual void updateEnabledState(ScrollbarThemeClient*);

    virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar);

    virtual bool supportsControlTints() const { return true; }
    virtual bool usesOverlayScrollbars() const;
    virtual void updateScrollbarOverlayStyle(ScrollbarThemeClient*);

    virtual double initialAutoscrollTimerDelay();
    virtual double autoscrollTimerDelay();

    virtual ScrollbarButtonsPlacement buttonsPlacement() const;

    virtual void registerScrollbar(ScrollbarThemeClient*);
    virtual void unregisterScrollbar(ScrollbarThemeClient*);

    void setNewPainterForScrollbar(ScrollbarThemeClient*, ScrollbarPainter);
    ScrollbarPainter painterForScrollbar(ScrollbarThemeClient*);

    static bool isCurrentlyDrawingIntoLayer();
    static void setIsCurrentlyDrawingIntoLayer(bool);

protected:
    virtual bool hasButtons(ScrollbarThemeClient*);
    virtual bool hasThumb(ScrollbarThemeClient*);

    virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
    virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false);
    virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false);

    virtual int maxOverlapBetweenPages() { return 40; }

    virtual int minimumThumbLength(ScrollbarThemeClient*);

    virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
    virtual bool shouldDragDocumentInsteadOfThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
    int scrollbarPartToHIPressedState(ScrollbarPart);
};

}

#endif


text:
package origins

// Buffer holds a slice of facts. The buffer dynamically grows as facts
// are written to it. The position is maintained across reads.
type Buffer struct {
	buf Facts
	// Contents are buf[off : len(buf)]
	off int
}

// grow grows the buffer to guarantee space for n more facts.
// It returns the index where facts should be written.
func (b *Buffer) grow(n int) int {
	m := b.Len()

	// Buffer is empty, reset to reclaim space.
	if m == 0 && b.off != 0 {
		b.Truncate(0)
	}

	if len(b.buf)+n > cap(b.buf) {
		var buf Facts

		if m+n <= cap(b.buf)/2 {
			copy(b.buf[:], b.buf[b.off:])
			buf = b.buf[:m]
		} else {
			buf = make(Facts, 2*cap(b.buf)+n)
			copy(buf, b.buf[b.off:])
		}

		b.buf = buf
		b.off = 0
	}

	b.buf = b.buf[0 : b.off+m+n]
	return b.off + m
}

// Grow increase the buffer size by a minimum of n.
func (b *Buffer) Grow(n int) {
	b.grow(n)
}

// Len returns the length of the unread portion of the buffer.
func (b *Buffer) Len() int {
	return len(b.buf) - b.off
}

// Write writes a fact to the buffer.
func (b *Buffer) Write(f *Fact) error {
	_, err := b.Append(f)
	return err
}

// Write takes a slice of facts and writes them to the buffer.
func (b *Buffer) Append(buf ...*Fact) (int, error) {
	m := b.grow(len(buf))
	return copy(b.buf[m:], buf), nil
}

// Facts returns a copy of the unread portion of facts.
func (b *Buffer) Facts() Facts {
	n := b.Len()

	if n == 0 {
		return Facts{}
	}

	c := make(Facts, n)
	copy(c, b.buf[b.off:])

	// Reclaim space.
	b.Truncate(0)
	return c
}

// Truncate resets the read and write position to the specified index.
func (b *Buffer) Truncate(n int) {
	switch {
	case n < 0 || n > b.Len():
		panic("origins.Buffer: truncation out of range")
	case n == 0:
		// Reuse buffer space.
		b.off = 0
	}

	b.buf = b.buf[0 : b.off+n]
}

// Reset resets the buffer so it has not content. This is equivalent to
// calling b.Truncate(0).
func (b *Buffer) Reset() {
	b.Truncate(0)
}

// Next returns the next unread fact in the buffer.
func (b *Buffer) Next() *Fact {
	// Do not exceed to the write position.
	if b.off >= len(b.buf) {
		// Buffer is empty, reset.
		b.Truncate(0)

		return nil
	}

	f := b.buf[b.off]
	b.off++

	return f
}

func (b *Buffer) Err() error {
	return nil
}

// NewBuffer initializes a buffer of facts.
func NewBuffer(buf Facts) *Buffer {
	return &Buffer{
		buf: buf,
	}
}


text:
"""
Tests For Cells Utility methods
"""
import inspect
import mock
import random

from jacket.compute.cells import utils as cells_utils
from jacket.compute import exception
from jacket.objects import compute
from jacket.compute import test
from jacket.tests.compute.unit import fake_instance

class CellsUtilsTestCase(test.NoDBTestCase):
    """Test case for Cells utility methods."""
    def test_get_instances_to_sync(self):
        fake_context = 'fake_context'

        call_info = {'get_all': 0, 'shuffle': 0}

        def random_shuffle(_list):
            call_info['shuffle'] += 1

        @staticmethod
        def instance_get_all_by_filters(context, filters,
                sort_key, sort_dir, limit, marker):
            # Pretend we return a full list the first time otherwise we loop
            # infinitely
            if marker is not None:
                return []
            self.assertEqual(fake_context, context)
            self.assertEqual('deleted', sort_key)
            self.assertEqual('asc', sort_dir)
            call_info['got_filters'] = filters
            call_info['get_all'] += 1
            instances = [fake_instance.fake_db_instance() for i in range(3)]
            return instances

        self.stubs.Set(compute.InstanceList, 'get_by_filters',
                instance_get_all_by_filters)
        self.stubs.Set(random, 'shuffle', random_shuffle)

        instances = cells_utils.get_instances_to_sync(fake_context)
        self.assertTrue(inspect.isgenerator(instances))
        self.assertEqual(3, len([x for x in instances]))
        self.assertEqual(1, call_info['get_all'])
        self.assertEqual({}, call_info['got_filters'])
        self.assertEqual(0, call_info['shuffle'])

        instances = cells_utils.get_instances_to_sync(fake_context,
                                                      shuffle=True)
        self.assertTrue(inspect.isgenerator(instances))
        self.assertEqual(3, len([x for x in instances]))
        self.assertEqual(2, call_info['get_all'])
        self.assertEqual({}, call_info['got_filters'])
        self.assertEqual(1, call_info['shuffle'])

        instances = cells_utils.get_instances_to_sync(fake_context,
                updated_since='fake-updated-since')
        self.assertTrue(inspect.isgenerator(instances))
        self.assertEqual(3, len([x for x in instances]))
        self.assertEqual(3, call_info['get_all'])
        self.assertEqual({'changes-since': 'fake-updated-since'},
                         call_info['got_filters'])
        self.assertEqual(1, call_info['shuffle'])

        instances = cells_utils.get_instances_to_sync(fake_context,
                project_id='fake-project',
                updated_since='fake-updated-since', shuffle=True)
        self.assertTrue(inspect.isgenerator(instances))
        self.assertEqual(3, len([x for x in instances]))
        self.assertEqual(4, call_info['get_all'])
        self.assertEqual({'changes-since': 'fake-updated-since',
                 'project_id': 'fake-project'}, call_info['got_filters'])
        self.assertEqual(2, call_info['shuffle'])

    @mock.patch.object(compute.InstanceList, 'get_by_filters')
    @mock.patch.object(random, 'shuffle')
    def _test_get_instances_pagination(self, mock_shuffle,
            mock_get_by_filters, shuffle=False, updated_since=None,
            project_id=None):
        fake_context = 'fake_context'

        instances0 = compute.instance._make_instance_list(fake_context,
                compute.InstanceList(),
                [fake_instance.fake_db_instance() for i in range(3)],
                expected_attrs=None)
        marker0 = instances0[-1]['uuid']
        instances1 = compute.instance._make_instance_list(fake_context,
                compute.InstanceList(),
                [fake_instance.fake_db_instance() for i in range(3)],
                expected_attrs=None)
        marker1 = instances1[-1]['uuid']

        mock_get_by_filters.side_effect = [instances0, instances1, []]

        instances = cells_utils.get_instances_to_sync(fake_context,
                updated_since, project_id, shuffle=shuffle)
        self.assertEqual(len([x for x in instances]), 6)

        filters = {}
        if updated_since is not None:
            filters['changes-since'] = updated_since
        if project_id is not None:
            filters['project_id'] = project_id
        limit = 100
        expected_calls = [mock.call(fake_context, filters, sort_key='deleted',
                              sort_dir='asc', limit=limit, marker=None),
                          mock.call(fake_context, filters, sort_key='deleted',
                              sort_dir='asc', limit=limit, marker=marker0),
                          mock.call(fake_context, filters, sort_key='deleted',
                              sort_dir='asc', limit=limit, marker=marker1)]
        mock_get_by_filters.assert_has_calls(expected_calls)
        self.assertEqual(3, mock_get_by_filters.call_count)

    def test_get_instances_to_sync_limit(self):
        self._test_get_instances_pagination()

    def test_get_instances_to_sync_shuffle(self):
        self._test_get_instances_pagination(shuffle=True)

    def test_get_instances_to_sync_updated_since(self):
        self._test_get_instances_pagination(updated_since='fake-updated-since')

    def test_get_instances_to_sync_multiple_params(self):
        self._test_get_instances_pagination(project_id='fake-project',
                updated_since='fake-updated-since', shuffle=True)

    def test_split_cell_and_item(self):
        path = 'australia', 'queensland', 'gold_coast'
        cell = cells_utils.PATH_CELL_SEP.join(path)
        item = 'host_5'
        together = cells_utils.cell_with_item(cell, item)
        self.assertEqual(cells_utils._CELL_ITEM_SEP.join([cell, item]),
                         together)

        # Test normal usage
        result_cell, result_item = cells_utils.split_cell_and_item(together)
        self.assertEqual(cell, result_cell)
        self.assertEqual(item, result_item)

        # Test with no cell
        cell = None
        together = cells_utils.cell_with_item(cell, item)
        self.assertEqual(item, together)
        result_cell, result_item = cells_utils.split_cell_and_item(together)
        self.assertEqual(cell, result_cell)
        self.assertEqual(item, result_item)

    def test_add_cell_to_compute_node(self):
        fake_compute = compute.ComputeNode(id=1, host='fake')
        cell_path = 'fake_path'

        proxy = cells_utils.add_cell_to_compute_node(fake_compute, cell_path)

        self.assertIsInstance(proxy, cells_utils.ComputeNodeProxy)
        self.assertEqual(cells_utils.cell_with_item(cell_path, 1), proxy.id)
        self.assertEqual(cells_utils.cell_with_item(cell_path, 'fake'),
                         proxy.host)

    @mock.patch.object(compute.Service, 'obj_load_attr')
    def test_add_cell_to_service_no_compute_node(self, mock_get_by_id):
        fake_service = compute.Service(id=1, host='fake')
        mock_get_by_id.side_effect = exception.ServiceNotFound(service_id=1)
        cell_path = 'fake_path'

        proxy = cells_utils.add_cell_to_service(fake_service, cell_path)

        self.assertIsInstance(proxy, cells_utils.ServiceProxy)
        self.assertEqual(cells_utils.cell_with_item(cell_path, 1), proxy.id)
        self.assertEqual(cells_utils.cell_with_item(cell_path, 'fake'),
                         proxy.host)
        self.assertRaises(AttributeError,
                          getattr, proxy, 'compute_node')

    def test_add_cell_to_service_with_compute_node(self):
        fake_service = compute.Service(id=1, host='fake')
        fake_service.compute_node = compute.ComputeNode(id=1, host='fake')
        cell_path = 'fake_path'

        proxy = cells_utils.add_cell_to_service(fake_service, cell_path)

        self.assertIsInstance(proxy, cells_utils.ServiceProxy)
        self.assertEqual(cells_utils.cell_with_item(cell_path, 1), proxy.id)
        self.assertEqual(cells_utils.cell_with_item(cell_path, 'fake'),
                         proxy.host)
        self.assertRaises(AttributeError,
                          getattr, proxy, 'compute_node')

    def test_proxy_object_serializer_to_primitive(self):
        obj = compute.ComputeNode(id=1, host='fake')
        obj_proxy = cells_utils.ComputeNodeProxy(obj, 'fake_path')
        serializer = cells_utils.ProxyObjectSerializer()

        primitive = serializer.serialize_entity('ctx', obj_proxy)
        self.assertIsInstance(primitive, dict)
        class_name = primitive.pop('cell_proxy.class_name')
        cell_path = primitive.pop('cell_proxy.cell_path')
        self.assertEqual('ComputeNodeProxy', class_name)
        self.assertEqual('fake_path', cell_path)
        self.assertEqual(obj.obj_to_primitive(), primitive)

    def test_proxy_object_serializer_from_primitive(self):
        obj = compute.ComputeNode(id=1, host='fake')
        serializer = cells_utils.ProxyObjectSerializer()

        # Recreating the primitive by hand to isolate the test for only
        # the deserializing method
        primitive = obj.obj_to_primitive()
        primitive['cell_proxy.class_name'] = 'ComputeNodeProxy'
        primitive['cell_proxy.cell_path'] = 'fake_path'

        result = serializer.deserialize_entity('ctx', primitive)
        self.assertIsInstance(result, cells_utils.ComputeNodeProxy)
        self.assertEqual(obj.obj_to_primitive(),
                         result._obj.obj_to_primitive())
        self.assertEqual('fake_path', result._cell_path)


text:
#include "devices.h"
#include "pocl_cl.h"
#include "pocl_util.h"

extern unsigned long sampler_c;

extern CL_API_ENTRY cl_sampler CL_API_CALL
POname(clCreateSampler)(cl_context          context,
                cl_bool             normalized_coords,
                cl_addressing_mode  addressing_mode,
                cl_filter_mode      filter_mode,
                cl_int *            errcode_ret)
CL_API_SUFFIX__VERSION_1_0
{
  int errcode = CL_SUCCESS;
  cl_sampler sampler = NULL;

  POCL_GOTO_ERROR_COND ((!IS_CL_OBJECT_VALID (context)), CL_INVALID_CONTEXT);

  /* at least 1 device must support images */
  size_t i, any_device_has_images = 0;
  for (i = 0; i < context->num_devices; i++)
    any_device_has_images += (size_t)context->devices[i]->image_support;
  POCL_GOTO_ERROR_ON ((!any_device_has_images), CL_INVALID_OPERATION,
                      "None of the devices within context support images\n");

  /* check requested sampler validity */
  POCL_GOTO_ERROR_COND (
      ((normalized_coords != CL_TRUE) && (normalized_coords != CL_FALSE)),
      CL_INVALID_VALUE);
  POCL_GOTO_ERROR_COND (((normalized_coords != CL_TRUE)
                         && (addressing_mode == CL_ADDRESS_MIRRORED_REPEAT)),
                        CL_INVALID_VALUE);
  POCL_GOTO_ERROR_COND (((normalized_coords != CL_TRUE)
                         && (addressing_mode == CL_ADDRESS_REPEAT)),
                        CL_INVALID_VALUE);

  sampler = (cl_sampler) malloc(sizeof(struct _cl_sampler));
  POCL_GOTO_ERROR_COND ((sampler == NULL), CL_OUT_OF_HOST_MEMORY);

  POCL_INIT_OBJECT (sampler);
  POname (clRetainContext) (context);
  sampler->context = context;
  sampler->normalized_coords = normalized_coords;
  sampler->addressing_mode = addressing_mode;
  sampler->filter_mode = filter_mode;
  sampler->device_data = (void **)calloc (pocl_num_devices, sizeof (void *));

  TP_CREATE_SAMPLER (context->id, sampler->id);

  POCL_ATOMIC_INC (sampler_c);

  for (i = 0; i < context->num_devices; ++i)
    {
      cl_device_id dev = context->devices[i];
      if (dev->available != CL_TRUE)
        continue;
      if (dev->image_support == CL_TRUE && dev->ops->create_sampler)
        dev->ops->create_sampler (dev, sampler, dev->dev_id);
    }

ERROR:
  if(errcode_ret)
  {
    *errcode_ret = errcode;
  }
  return sampler;
}
POsym(clCreateSampler)


text:
"""
A very simple script that creates an appropriate systemd service config.
Currently works only on raspbian/debian and is pretty spaghettyish overall.
"""

from os import path
import sys

kahvibot_root = path.dirname(path.abspath(__file__))

virtualenv_path = path.join(kahvibot_root, "venv")
if not path.exists(virtualenv_path):
    raise ValueError(f"Could not find virtual env at '{virtualenv_path}'.")

exec_path = path.join(kahvibot_root, "kahvibot")
service_path = "/etc/systemd/system/kahvibot.service"

service_content_fmt = """
# systemd configuration for kahvibot
[Unit]
Description=Telegram bot for checking the amount of coffee

# Only enable after network is online (after reboot)
# see https://unix.stackexchange.com/questions/379167/starting-systemd-service-after-network-online-target-but-dns-is-still-not-availa
# and https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/
After=systemd-resolved.service network-online.target
Wants=systemd-resolved.service network-online.target

# Even though we have the After and Wants options above, the first restart still fails.
# So we add these and the RstartSec and Restart options below.
StartLimitIntervalSec=1h
StartLimitBurst=5

[Service]
ExecStart={}
ExecReload=/bin/kill -HUP $MAINPID
Type=simple
PIDFile=/var/run/kahvibot.pid
WorkingDirectory={}
RestartSec=10
Restart=on-failure

[Install]
WantedBy=multi-user.target
""".strip()

"""
Check if the specified configuration file already exists. If it doesn't, create
it. If it does, ask if the user wants to overwrite it.
"""
def create_config_file(fname: str, content: str):
    if path.exists(fname):
        ans = input(f"Found existing systemd configuration file {fname}. "
                    "Do you want to overwrite it? (y/n) ")
        ans = ans.lower()
        if not ans in ["y", "yes"]:
            print("Not writing configuration file.")
            return

    with open(fname, "w") as f:
        f.write(content)

    print(f"Created systemd configuration file {fname}. You can check the status with 'sudo service kahvibot status' and use 'sudo systemctl enable kahvibot' to make it run on startup.")

if __name__ == "__main__":

    # prepend the python interpreter inside the virtualenv to use that, see
    # https://stackoverflow.com/a/37211676
    exec_start = f"{virtualenv_path}/bin/python {exec_path}"
    service_content = service_content_fmt.format(exec_start, kahvibot_root)
    create_config_file(service_path, service_content)


text:
many esa on the sara

# features

- It's wiki for a team has many teams.
- Teams and permissions.
- Search within all wikis.


text:
title: Import
page_title: Import | UI for ASP.NET AJAX Documentation
description: Import
slug: introduction/themebuilder/import
tags: import,theme
published: True
position: 1
---

# Importing a Theme

The **ThemeBuilder** tool enables you to upload your own theme that you have created previously. You need to select the *Import existing theme* option.

>note You must upload both **ScssPrimitives.json** and **UsedControls.json** files in order for the imported theme to be recognized correctly.

![themebuilder-import-existing-theme](images/themebuilder-import-existing-theme.png)

Once you have uploaded the theme you can customize it as described in the [create and download]({%slug introduction/themebuilder/create-and-download%}) article.


text:
//
//  uniform_generator.h
//  YCSB-C
//
//  Created by Jinglei Ren on 12/6/14.
//  Copyright (c) 2014 Jinglei Ren <jinglei@ren.systems>.
//

#ifndef YCSB_C_UNIFORM_GENERATOR_H_
#define YCSB_C_UNIFORM_GENERATOR_H_

#include "generator.h"
#include <random>

namespace Ycsb {
namespace Core {

/*
 * UniformGenerator is adapted by constructing std::mt19937_64 with
 * different int numbers.
 * Now if multiple threads create multiple UniformGenerators, the random
 * number series will be also different
 */
class UniformGenerator: public Generator<uint64_t> {
public:
	/*
	 * Both min and max are inclusive
	 */
	UniformGenerator(uint64_t min, uint64_t max)
			: dist_(min, max) {
		struct timespec now;
		clock_gettime(CLOCK_MONOTONIC_RAW, &now);
		generator_ = std::default_random_engine(now.tv_nsec);
		Next();
	}

	uint64_t Next() {
		return last_int_ = dist_(generator_);
	}
	uint64_t Last() {
		return last_int_;
	}

private:
	uint64_t last_int_;
	//std::mt19937_64 generator_;
	std::default_random_engine generator_;
	std::uniform_int_distribution<uint64_t> dist_;
};

} // Core
} // Ycsb

#endif // YCSB_C_UNIFORM_GENERATOR_H_


text:
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/c329c8cdd744463dbda6a726e20f2383)](https://www.codacy.com/app/arnomoonens/DeepRL?utm_source=github.com&utm_medium=referral&utm_content=arnomoonens/DeepRL&utm_campaign=badger)

**Update 25/03/2019**: For now, the master branch won't get big changes. Instead, algorithms are adapted for TensorFlow 2 (and new ones may be added) on the [TF2 branch](https://github.com/arnomoonens/yarll/tree/tf2).

**Update 29/10/2018**: New library name.

**Update 25/10/2018**: Added [SAC implementation](./yarll/agents/sac.py).

## Status

Different algorithms have currently been implemented (in no particular order):

- [Advantage Actor Critic](./yarll/agents/actorcritic/a2c.py)
- [Asynchronous Advantage Actor Critic (A3C)](./yarll/agents/actorcritic/a3c.py)
- [Deep Deterministic Policy Gradient (DDPG)](./yarll/agents/ddpg.py)
- [Proximal Policy Optimization (PPO)](./yarll/agents/ppo/ppo.py)
  - [Distributed version (DPPO)](./yarll/agents/ppo/dppo.py)
- [Soft Actor-Critic (SAC)](./yarll/agents/sac.py)
- [Trust Region Policy Optimization (TRPO)](./yarll/agents/trpo/trpo.py)
  - [Distributed version (DTRPO)](./yarll/agents/trpo/dtrpo.py)
- [REINFORCE](./yarll/agents/reinforce.py) (convolutional neural network part has not been tested yet)
- [Cross-Entropy Method](./yarll/agents/cem.py)
- [Sarsa with with function approximation and eligibility traces](./yarll/agents/sarsa/sarsa_fa.py)
- [Karpathy's policy gradient algorithm](./yarll/agents/karpathy.py) ([version using convolutional neural networks](./yarll/agents/karpathy_cnn.py) has not been tested yet)
- [(Sequential) knowledge transfer](./yarll/agents/knowledgetransfer/knowledge_transfer.py)
- [Asynchronous knowledge transfer](./yarll/agents/knowledgetransfer/async_knowledge_transfer.py)

## Asynchronous Advantage Actor Critic (A3C)

The code for this algorithm can be found [here](./yarll/agents/actorcritic/a3c.py).
Example run after training using 16 threads for a total of 5 million timesteps on the _PongDeterministic-v4_ environment:

![Pong example run](./results/pong.gif)

## How to run

First, install the library using [pip](https://pypi.python.org/pypi/pip) (you can first remove _OpenCV_ from the `setup.py` file if it is already installed):

```Shell

pip install yarll

```

### Algorithms/experiments

You can run algorithms by passing the path to an experiment specification (which is a file in _json_ format) to `main.py`:

```Shell

python -m yarll.main <path_to_experiment_specification>

```

Examples of experiment specifications can be found in the [_experiment_specs_](./experiment_specs) folder.

### Statistics

Statistics can be plot using:

```Shell

python -m yarll.misc.plot_statistics <path_to_stats>

```

`<path_to_stats>` can be one of 2 things:

- A _json_ file generated using `gym.wrappers.Monitor`, in case it plots the episode lengths and total reward per episode.
- A directory containing _TensorFlow_ scalar summaries for different tasks, in which case all of the found scalars are plot.

Help about other arguments (e.g. for using smoothing) can be found by executing `python -m yarll.misc.plot_statistics -h`.

Alternatively, it is also possible to use [_Tensorboard_](https://www.tensorflow.org/get_started/summaries_and_tensorboard) to show statistics in the browser by passing the directory with the scalar summaries as `--logdir` argument.


text:
package io.victoralbertos.example_rx_retrofit2.data;

import io.victoralbertos.example_rx_retrofit2.domain.Repo;
import io.victoralbertos.example_rx_retrofit2.domain.User;
import io.victoralbertos.mockery.api.built_in_mockery.DTO;
import io.victoralbertos.mockery.api.built_in_mockery.DTOArgs;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.MatcherAssert;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.notNullValue;

public class Mockeries {

  public static class UserDTO implements DTOArgs.Behaviour<User> {
    @Override public User legal(Object[] args) {
      String userName = (String) args[0];
      User user = new User(1, userName);
      return user;
    }

    @Override public void validate(User candidate) throws AssertionError {
      MatcherAssert.assertThat(candidate, notNullValue());
      MatcherAssert.assertThat(candidate.getId(), is(not(0)));
      MatcherAssert.assertThat(candidate.getLogin().isEmpty(), is(not(true)));
    }
  }

  public static class UsersDTO implements DTOArgs.Behaviour<List<User>> {
    @Override public List<User> legal(Object[] args) {
      List<User> users = new ArrayList<>();

      int perPage = (int) args[1];
      for (int i = 0; i <= perPage; i++) {
        users.add(new User(i, "User "+ i));
      }

      return users;
    }

    @Override public void validate(List<User> candidate) throws AssertionError {
      MatcherAssert.assertThat(candidate, notNullValue());
      MatcherAssert.assertThat(candidate.isEmpty(), is(not(true)));

      User user = candidate.get(0);
      MatcherAssert.assertThat(user.getId(), is(not(0)));
      MatcherAssert.assertThat(user.getLogin().isEmpty(), is(not(true)));
    }
  }

  public static class ReposDTO implements DTO.Behaviour<List<Repo>> {
    @Override public List<Repo> legal() {
      List<Repo> repos = new ArrayList<>();
      repos.add(new Repo(1, "Repo 1 "));
      repos.add(new Repo(2, "Repo 2 "));
      repos.add(new Repo(3, "Repo 3 "));
      repos.add(new Repo(4, "Repo 4 "));
      return repos;
    }

    @Override public void validate(List<Repo> candidate) throws AssertionError {
      MatcherAssert.assertThat(candidate, notNullValue());
      MatcherAssert.assertThat(candidate.isEmpty(), is(not(true)));

      Repo repo = candidate.get(0);
      MatcherAssert.assertThat(repo.getId(), is(not(0)));
      MatcherAssert.assertThat(repo.getName().isEmpty(), is(not(true)));
    }
  }

}


text:
var component = portal.component;
var content = portal.content;
var page = portal.content.page;
var relatedPerson = component.config.getProperty('person');
var person,personData;

if (content.type == 'person') {
    personData = content;
} else {
    var personId;
    if (relatedPerson) {
        personId = relatedPerson.getString();
        if (personId) {
            personData = system.contentService.getContentById(personId);
        }
    }
}

if (personData) {
    var imageContent = system.contentService.getContentById(personData.contentData.getProperty('image').getString());
    person = {
        name: personData.contentData.getProperty('first-name').getString() + ' ' + personData.contentData.getProperty('middle-name').getString() + ' ' + personData.contentData.getProperty('last-name').getString(),
        title: personData.contentData.getProperty('job-title').getString(),
        image: portal.url.createImageByIdUrl(imageContent.id).filter("scaleblock(400,400)")
    };
} else {
    person = {
        name: 'Test Testesen',
        title: 'Sjefen over alle sjefer',
        image: portal.url.createResourceUrl('images/team1.jpg')
    };
}

var params = {
	context: portal,
	component: component,
    content: content,
    person: person
};

var body = system.thymeleaf.render('view/person.html', params);

portal.response.contentType = 'text/html';
portal.response.body = body;


text:
"""Helper functions for Cloud Storage utility classes.

These are *not* part of the API.
"""

import base64
from hashlib import md5
import os

STORAGE_EMULATOR_ENV_VAR = "STORAGE_EMULATOR_HOST"
"""Environment variable defining host for Storage emulator."""

_DEFAULT_STORAGE_HOST = u"https://storage.googleapis.com"

def _get_storage_host():
    return os.environ.get(STORAGE_EMULATOR_ENV_VAR, _DEFAULT_STORAGE_HOST)

def _validate_name(name):
    """Pre-flight ``Bucket`` name validation.

    :type name: str or :data:`NoneType`
    :param name: Proposed bucket name.

    :rtype: str or :data:`NoneType`
    :returns: ``name`` if valid.
    """
    if name is None:
        return

    # The first and last characters must be alphanumeric.
    if not all([name[0].isalnum(), name[-1].isalnum()]):
        raise ValueError("Bucket names must start and end with a number or letter.")
    return name

class _PropertyMixin(object):
    """Abstract mixin for cloud storage classes with associated properties.

    Non-abstract subclasses should implement:
      - path
      - client
      - user_project

    :type name: str
    :param name: The name of the object. Bucket names must start and end with a
                 number or letter.
    """

    def __init__(self, name=None):
        self.name = name
        self._properties = {}
        self._changes = set()

    @property
    def path(self):
        """Abstract getter for the object path."""
        raise NotImplementedError

    @property
    def client(self):
        """Abstract getter for the object client."""
        raise NotImplementedError

    @property
    def user_project(self):
        """Abstract getter for the object user_project."""
        raise NotImplementedError

    def _require_client(self, client):
        """Check client or verify over-ride.

        :type client: :class:`~google.cloud.storage.client.Client` or
                      ``NoneType``
        :param client: the client to use.  If not passed, falls back to the
                       ``client`` stored on the current object.

        :rtype: :class:`google.cloud.storage.client.Client`
        :returns: The client passed in or the currently bound client.
        """
        if client is None:
            client = self.client
        return client

    def _encryption_headers(self):
        """Return any encryption headers needed to fetch the object.

        .. note::
           Defined here because :meth:`reload` calls it, but this method is
           really only relevant for :class:`~google.cloud.storage.blob.Blob`.

        :rtype: dict
        :returns: a mapping of encryption-related headers.
        """
        return {}

    @property
    def _query_params(self):
        """Default query parameters."""
        params = {}
        if self.user_project is not None:
            params["userProject"] = self.user_project
        return params

    def reload(self, client=None):
        """Reload properties from Cloud Storage.

        If :attr:`user_project` is set, bills the API request to that project.

        :type client: :class:`~google.cloud.storage.client.Client` or
                      ``NoneType``
        :param client: the client to use.  If not passed, falls back to the
                       ``client`` stored on the current object.
        """
        client = self._require_client(client)
        query_params = self._query_params
        # Pass only '?projection=noAcl' here because 'acl' and related
        # are handled via custom endpoints.
        query_params["projection"] = "noAcl"
        api_response = client._connection.api_request(
            method="GET",
            path=self.path,
            query_params=query_params,
            headers=self._encryption_headers(),
            _target_object=self,
        )
        self._set_properties(api_response)

    def _patch_property(self, name, value):
        """Update field of this object's properties.

        This method will only update the field provided and will not
        touch the other fields.

        It **will not** reload the properties from the server. The behavior is
        local only and syncing occurs via :meth:`patch`.

        :type name: str
        :param name: The field name to update.

        :type value: object
        :param value: The value being updated.
        """
        self._changes.add(name)
        self._properties[name] = value

    def _set_properties(self, value):
        """Set the properties for the current object.

        :type value: dict or :class:`google.cloud.storage.batch._FutureDict`
        :param value: The properties to be set.
        """
        self._properties = value
        # If the values are reset, the changes must as well.
        self._changes = set()

    def patch(self, client=None):
        """Sends all changed properties in a PATCH request.

        Updates the ``_properties`` with the response from the backend.

        If :attr:`user_project` is set, bills the API request to that project.

        :type client: :class:`~google.cloud.storage.client.Client` or
                      ``NoneType``
        :param client: the client to use.  If not passed, falls back to the
                       ``client`` stored on the current object.
        """
        client = self._require_client(client)
        query_params = self._query_params
        # Pass '?projection=full' here because 'PATCH' documented not
        # to work properly w/ 'noAcl'.
        query_params["projection"] = "full"
        update_properties = {key: self._properties[key] for key in self._changes}

        # Make the API call.
        api_response = client._connection.api_request(
            method="PATCH",
            path=self.path,
            data=update_properties,
            query_params=query_params,
            _target_object=self,
        )
        self._set_properties(api_response)

    def update(self, client=None):
        """Sends all properties in a PUT request.

        Updates the ``_properties`` with the response from the backend.

        If :attr:`user_project` is set, bills the API request to that project.

        :type client: :class:`~google.cloud.storage.client.Client` or
                      ``NoneType``
        :param client: the client to use.  If not passed, falls back to the
                       ``client`` stored on the current object.
        """
        client = self._require_client(client)
        query_params = self._query_params
        query_params["projection"] = "full"
        api_response = client._connection.api_request(
            method="PUT",
            path=self.path,
            data=self._properties,
            query_params=query_params,
            _target_object=self,
        )
        self._set_properties(api_response)

def _scalar_property(fieldname):
    """Create a property descriptor around the :class:`_PropertyMixin` helpers.
    """

    def _getter(self):
        """Scalar property getter."""
        return self._properties.get(fieldname)

    def _setter(self, value):
        """Scalar property setter."""
        self._patch_property(fieldname, value)

    return property(_getter, _setter)

def _write_buffer_to_hash(buffer_object, hash_obj, digest_block_size=8192):
    """Read blocks from a buffer and update a hash with them.

    :type buffer_object: bytes buffer
    :param buffer_object: Buffer containing bytes used to update a hash object.

    :type hash_obj: object that implements update
    :param hash_obj: A hash object (MD5 or CRC32-C).

    :type digest_block_size: int
    :param digest_block_size: The block size to write to the hash.
                              Defaults to 8192.
    """
    block = buffer_object.read(digest_block_size)

    while len(block) > 0:
        hash_obj.update(block)
        # Update the block for the next iteration.
        block = buffer_object.read(digest_block_size)

def _base64_md5hash(buffer_object):
    """Get MD5 hash of bytes (as base64).

    :type buffer_object: bytes buffer
    :param buffer_object: Buffer containing bytes used to compute an MD5
                          hash (as base64).

    :rtype: str
    :returns: A base64 encoded digest of the MD5 hash.
    """
    hash_obj = md5()
    _write_buffer_to_hash(buffer_object, hash_obj)
    digest_bytes = hash_obj.digest()
    return base64.b64encode(digest_bytes)


text:
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path"

	taosupport "github.com/jlmucb/cloudproxy/go/apps/simpleexample/taosupport"
)

var simpleCfg = flag.String("tao.config",
			"/Domains/domain.simpleexample/tao.config",
			"path to tao configuration")
var simpleClientPath = flag.String("/Domains/domain.simpleexample/SimpleClient",
			"/Domains/domain.simpleexample/SimpleClient",
			"path to SimpleClient files")
var serverHost = flag.String("host", "localhost", "address for client/server")
var serverPort = flag.String("port", "8123", "port for client/server")
var serverAddr string

func main() {

	// This holds the cloudproxy specific data for simpleclient
	// including the Program Cert and Program Private key.
	var clientProgramData taosupport.TaoProgramData

	// Make sure we zero keys when we're done.
	defer taosupport.ClearTaoProgramData(&clientProgramData)

	// Parse flags
	flag.Parse()
	serverAddr = *serverHost + ":" + *serverPort

	// If TaoParadigm completes without error, clientProgramData contains all the
	// Cloudproxy information needed throughout simpleclient execution.
	if taosupport.TaoParadigm(simpleCfg, simpleClientPath, &clientProgramData) !=
			nil {
		log.Fatalln("simpleclient: Can't establish Tao")
	}
	fmt.Printf("simpleclient: TaoParadigm complete, name: %s\n",
	   clientProgramData.TaoName)

	// Open the Tao Channel using the Program key.  This program does all the
	// standard channel negotiation and presents the secure server name after
	// negotiation is complete.
	ms, serverName, err := taosupport.OpenTaoChannel(&clientProgramData,
             &serverAddr)
	if err != nil {
		log.Fatalln("simpleclient: Can't establish Tao Channel")
	}
	log.Printf("simpleclient: establish Tao Channel with %s, %s\n",
		serverAddr, serverName)

	// Send a simple request and get response.
	// We have a simple service protobuf for requests and reponsed between
	// simpleclient and simpleserver.  There's only on request: tell me the
	// secret.
	secretRequest := "SecretRequest"

	msg := new(taosupport.SimpleMessage)
	msg.RequestType = &secretRequest
	taosupport.SendRequest(ms, msg)
	if err != nil {
		log.Fatalln("simpleclient: Error in response to SendRequest\n")
	}
	respmsg, err := taosupport.GetResponse(ms)
	if err != nil {
		log.Fatalln("simpleclient: Error in response to GetResponse\n")
	}

	// This is the secret.
	retrieveSecret := respmsg.Data[0]

	// Encrypt and store the secret in simpleclient's save area.
	out, err := taosupport.Protect(clientProgramData.ProgramSymKeys, retrieveSecret)
	if err != nil {
		log.Fatalln("simpleclient: Error protecting data\n")
	}
	err = ioutil.WriteFile(path.Join(*simpleClientPath,
			"retrieved_secret"), out, os.ModePerm)
	if err != nil {
		log.Fatalln("simpleclient: error saving retrieved secret\n")
	}

	// Close down.
	log.Printf("simpleclient: secret is %s, done\n", retrieveSecret)
}


text:
from game.ai.helpers.defence import TileDanger
from mahjong.constants import EAST
from mahjong.tile import TilesConverter
from utils.general import revealed_suits_tiles

class PossibleFormsAnalyzer:
    POSSIBLE_TANKI = 1
    POSSIBLE_SYANPON = 2
    POSSIBLE_PENCHAN = 3
    POSSIBLE_KANCHAN = 4
    POSSIBLE_RYANMEN = 5
    POSSIBLE_RYANMEN_SIDES = 6

    def __init__(self, player):
        self.player = player

    def calculate_possible_forms(self, safe_tiles):
        possible_forms_34 = [None] * 34

        closed_hand_34 = TilesConverter.to_34_array(self.player.closed_hand)

        # first of all let's find suji for suits tiles
        suits = revealed_suits_tiles(self.player, closed_hand_34)
        for x in range(0, 3):
            suit = suits[x]

            for y in range(0, 9):
                tile_34_index = y + x * 9

                # we are only interested in tiles that we can discard
                if closed_hand_34[tile_34_index] == 0:
                    continue

                forms_count = self._init_zero_forms_count()
                possible_forms_34[tile_34_index] = forms_count

                # that means there are no possible forms for him to wait (we don't consider furiten here,
                # because we are defending from enemy taking ron)
                if tile_34_index in safe_tiles:
                    continue

                # tanki
                forms_count[self.POSSIBLE_TANKI] = 4 - suit[y]

                # syanpon
                if suit[y] == 1:
                    forms_count[self.POSSIBLE_SYANPON] = 3
                if suit[y] == 2:
                    forms_count[self.POSSIBLE_SYANPON] = 1
                else:
                    forms_count[self.POSSIBLE_SYANPON] = 0

                # penchan
                if y == 2:
                    forms_count[self.POSSIBLE_PENCHAN] = (4 - suit[0]) * (4 - suit[1])
                elif y == 6:
                    forms_count[self.POSSIBLE_PENCHAN] = (4 - suit[8]) * (4 - suit[7])

                # kanchan
                if 1 <= y <= 7:
                    tiles_cnt_left = 4 - suit[y - 1]
                    tiles_cnt_right = 4 - suit[y + 1]
                    forms_count[self.POSSIBLE_KANCHAN] = tiles_cnt_left * tiles_cnt_right

                # ryanmen
                if 0 <= y <= 2:
                    if not (tile_34_index + 3) in safe_tiles:
                        forms_count[self.POSSIBLE_RYANMEN] = (4 - suit[y + 1]) * (4 - suit[y + 2])
                        forms_count[self.POSSIBLE_RYANMEN_SIDES] = 1
                elif 3 <= y <= 5:
                    if not (tile_34_index - 3) in safe_tiles:
                        forms_left = (4 - suit[y - 1]) * (4 - suit[y - 2])
                        if forms_left != 0:
                            forms_count[self.POSSIBLE_RYANMEN_SIDES] += 1
                        forms_count[self.POSSIBLE_RYANMEN] += forms_left
                    if not (tile_34_index + 3) in safe_tiles:
                        forms_right = (4 - suit[y + 1]) * (4 - suit[y + 2])
                        if forms_right != 0:
                            forms_count[self.POSSIBLE_RYANMEN_SIDES] += 1
                        forms_count[self.POSSIBLE_RYANMEN] += forms_right
                else:
                    if not (tile_34_index - 3) in safe_tiles:
                        forms_count[self.POSSIBLE_RYANMEN] = (4 - suit[y - 1]) * (4 - suit[y - 2])
                        forms_count[self.POSSIBLE_RYANMEN_SIDES] = 1

        for tile_34_index in range(EAST, 34):
            if closed_hand_34[tile_34_index] == 0:
                continue

            forms_count = self._init_zero_forms_count()
            possible_forms_34[tile_34_index] = forms_count

            total_tiles = self.player.number_of_revealed_tiles(tile_34_index, closed_hand_34)

            # tanki
            forms_count[self.POSSIBLE_TANKI] = 4 - total_tiles

            # syanpon
            forms_count[self.POSSIBLE_SYANPON] = 3 - total_tiles if total_tiles < 3 else 0

        return possible_forms_34

    @staticmethod
    def calculate_possible_forms_total(forms_count):
        total = 0
        total += forms_count[PossibleFormsAnalyzer.POSSIBLE_TANKI]
        total += forms_count[PossibleFormsAnalyzer.POSSIBLE_SYANPON]
        total += forms_count[PossibleFormsAnalyzer.POSSIBLE_PENCHAN]
        total += forms_count[PossibleFormsAnalyzer.POSSIBLE_KANCHAN]
        total += forms_count[PossibleFormsAnalyzer.POSSIBLE_RYANMEN]
        return total

    @staticmethod
    def calculate_possible_forms_danger(forms_count):
        danger = 0
        danger += forms_count[PossibleFormsAnalyzer.POSSIBLE_TANKI] * TileDanger.FORM_BONUS_TANKI
        danger += forms_count[PossibleFormsAnalyzer.POSSIBLE_SYANPON] * TileDanger.FORM_BONUS_SYANPON
        danger += forms_count[PossibleFormsAnalyzer.POSSIBLE_PENCHAN] * TileDanger.FORM_BONUS_PENCHAN
        danger += forms_count[PossibleFormsAnalyzer.POSSIBLE_KANCHAN] * TileDanger.FORM_BONUS_KANCHAN
        danger += forms_count[PossibleFormsAnalyzer.POSSIBLE_RYANMEN] * TileDanger.FORM_BONUS_RYANMEN
        return danger

    def _init_zero_forms_count(self):
        forms_count = dict()
        forms_count[self.POSSIBLE_TANKI] = 0
        forms_count[self.POSSIBLE_SYANPON] = 0
        forms_count[self.POSSIBLE_PENCHAN] = 0
        forms_count[self.POSSIBLE_KANCHAN] = 0
        forms_count[self.POSSIBLE_RYANMEN] = 0
        forms_count[self.POSSIBLE_RYANMEN_SIDES] = 0
        return forms_count


text:
<resources>
    <string name="app_name">FilePersistenceTest</string>
</resources>


text:
package org.niso.schemas.sushi;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "ExceptionSeverity")
@XmlEnum
public enum ExceptionSeverity {

    @XmlEnumValue("Info")
    INFO("Info"),

    @XmlEnumValue("Debug")
    DEBUG("Debug"),

    @XmlEnumValue("Warning")
    WARNING("Warning"),

    @XmlEnumValue("Error")
    ERROR("Error"),

    @XmlEnumValue("Fatal")
    FATAL("Fatal");
    private final String value;

    ExceptionSeverity(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static ExceptionSeverity fromValue(String v) {
        for (ExceptionSeverity c: ExceptionSeverity.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
MAMMALDIR="./catscripts/Science/Biology/Animals/Vertebrates/Mammals"
KEYWORDS_MAMMALS="mammal"

if [ "$1" == "" ];
then

  debug_start "Mammals"

  . $MAMMALDIR/Placental_mammals/PlacentalMammals.sh #KEYWORDS_PLACENTALMAMMALS_ALL

  KEYWORDS_MAMMALS_EXCLUDE="$KEYWORDS_PLACENTALMAMMALS_ALL"

  debug_end "Mammals"

else

  . $MAMMALDIR/Placental_mammals/PlacentalMammals.sh norun #KEYWORDS_PLACENTALMAMMALS_ALL

  KEYWORDS_MAMMALS_EXCLUDE="$KEYWORDS_PLACENTALMAMMALS_ALL"

fi


text:
package ru.itpgrad.crmka.model.dao.imp;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import ru.itpgrad.crmka.model.dao.Dao;
import ru.itpgrad.crmka.model.entity.Entity;

import java.io.Serializable;
import java.util.List;

/**
 * Parent for all DAO implementations
 *
 * @author Ivan Maslov
 */
class AbstractHibernateDao<E extends Entity, ID extends Serializable> implements Dao<E, ID> {
    protected final Logger logger;
    private final SessionFactory sessionFactory;
    private final Class<E> targetClass;

    protected AbstractHibernateDao(SessionFactory sessionFactory, Class<E> targetClass) {
        logger = Logger.getLogger(getClass());
        this.sessionFactory = sessionFactory;
        this.targetClass = targetClass;
    }

    protected final Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @SuppressWarnings("unchecked")
    @Override
    public ID create(E newInstance) {
        return (ID) getSession().save(newInstance);
    }

    /**
     * Default implementation this method throw {@link java.lang.UnsupportedOperationException}
     */
    @Override
    public ID create(E newInstance, ID foreignId) {
        throw new UnsupportedOperationException("Table don't have foreign key");
    }

    @SuppressWarnings("unchecked")
    @Override
    public E read(ID id) {
        return (E) getSession().get(targetClass, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<E> readAll() {
        return (List<E>) getSession().createCriteria(targetClass).list();
    }

    @Override
    public void update(E transientObject) {
        getSession().update(transientObject);
    }

    /**
     * Default implementation this method throw {@link java.lang.UnsupportedOperationException}
     */
    @Override
    public void update(E transientObject, ID foreignId) {
        throw new UnsupportedOperationException("Table don't have foreign key");
    }

    @Override
    public void delete(E persistentObject) {
        getSession().delete(persistentObject);
    }
}


text:
package cellsociety_team01.rules;

import cellsociety_team01.CellState.State;

public class MovementThresholdRule extends MovementRule{

	protected State myCause;
	protected double mySatisfactionThreshold;

	public MovementThresholdRule(State targetState, State cause, double t) {
		super(targetState);
		myCause = cause;
		mySatisfactionThreshold = t;
	}

}


text:
//
//  RKObjectMapper.h
//  RestKit
//
//  Created by Blake Watters on 5/6/11.
//  Copyright (c) 2009-2012 RestKit. All rights reserved.
//
//  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.
//

#import <Foundation/Foundation.h>
#import "RKObjectMapping.h"
#import "RKObjectMappingOperation.h"
#import "RKObjectMappingResult.h"
#import "RKObjectMappingProvider.h"
#import "RKMappingOperationQueue.h"
#import "Support.h"

@class RKObjectMapper;

@protocol RKObjectMapperDelegate <NSObject>

@optional

- (void)objectMapperWillBeginMapping:(RKObjectMapper *)objectMapper;
- (void)objectMapperDidFinishMapping:(RKObjectMapper *)objectMapper;
- (void)objectMapper:(RKObjectMapper *)objectMapper didAddError:(NSError *)error;
- (void)objectMapper:(RKObjectMapper *)objectMapper didFindMappableObject:(id)object atKeyPath:(NSString *)keyPath withMapping:(RKObjectMappingDefinition *)mapping;
- (void)objectMapper:(RKObjectMapper *)objectMapper didNotFindMappableObjectAtKeyPath:(NSString *)keyPath;

- (void)objectMapper:(RKObjectMapper *)objectMapper willMapFromObject:(id)sourceObject toObject:(id)destinationObject atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)objectMapping;
- (void)objectMapper:(RKObjectMapper *)objectMapper didMapFromObject:(id)sourceObject toObject:(id)destinationObject atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)objectMapping;
- (void)objectMapper:(RKObjectMapper *)objectMapper didFailMappingFromObject:(id)sourceObject toObject:(id)destinationObject withError:(NSError *)error atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)objectMapping;
@end

/**

 */
@interface RKObjectMapper : NSObject {
  @protected
    RKMappingOperationQueue *operationQueue;
    NSMutableArray *errors;
}

@property (nonatomic, readonly) id sourceObject;
@property (nonatomic, assign) id targetObject;
@property (nonatomic, readonly) RKObjectMappingProvider *mappingProvider;
@property (nonatomic, assign) RKObjectMappingProviderContext context;
@property (nonatomic, assign) id<RKObjectMapperDelegate> delegate;
@property (nonatomic, readonly) NSArray *errors;

+ (id)mapperWithObject:(id)object mappingProvider:(RKObjectMappingProvider *)mappingProvider;
- (id)initWithObject:(id)object mappingProvider:(RKObjectMappingProvider *)mappingProvider;

// Primary entry point for the mapper. Examines the type of object and processes it appropriately...
- (RKObjectMappingResult *)performMapping;
- (NSUInteger)errorCount;

@end


text:
package org.assertj.core.extension;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.util.AssertionsUtil.assertThatAssertionErrorIsThrownBy;

import org.assertj.core.api.SoftAssertions;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.assertj.core.api.junit.jupiter.SoftlyExtension;
import org.assertj.core.error.ShouldNotBeNull;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

@SuppressWarnings("deprecation")
@ExtendWith(SoftlyExtension.class)
@DisplayName("SoftlyExtension hasInstance")
class SoftlyExtensionInstanceTest {

  // private SoftAssertions softlyNotAnnotated;

  private SoftAssertions softly;

  @Test
  void should_pass_if_not_null() {
    // GIVEN/WHEN/THEN
    assertThat(softly).isNotNull();
  }

  @Test
  void should_pass_if_not_null2() {
    // GIVEN/WHEN/THEN
    assertThat(softly).isNotNull();
  }

  @Test
  void should_fail_if_null() {
    // GIVEN/WHEN
    String s = null;
    ThrowingCallable code = () -> assertThat(s).isNotNull();

    // THEN
    assertThatAssertionErrorIsThrownBy(code).withMessage(ShouldNotBeNull.shouldNotBeNull().create());
  }

  @Nested
  @ExtendWith(SoftlyExtension.class)
  @DisplayName("SoftlyExtension Nested Should hasInstance")
  class SoftlyNestedMethodLifecycle {

    private SoftAssertions softlyInner;

    @Test
    void should_pass_if_inner_field_has_instance() {
      // GIVEN/WHEN/THEN
      assertThat(softlyInner).isNotNull();
    }

    @Test
    void should_pass_if_parent_field_has_instance() {
      // GIVEN/WHEN/THEN
      assertThat(softly).isNotNull();
    }
  }
}