text:
package org.apache.geode.internal.cache;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionDestroyedException;
import org.apache.geode.cache.Scope;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.AsyncInvocation;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;

public class ConcurrentDestroySubRegionDUnitTest extends JUnit4CacheTestCase {

  @Override
  public final void postSetUp() throws Exception {
    // this test expects to be able to create a region named "region"
    // but other tests seem to leave regions around, so we need
    // to create a new cache
    disconnectAllFromDS();
  }

  public ConcurrentDestroySubRegionDUnitTest() {
    super();
  }

  @Test
  public void test() throws Throwable {
    final Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);

    for (int i = 0; i < 200; i++) {
      final SerializableRunnable createParent = new SerializableRunnable() {

        @Override
        public void run() {
          Cache cache = getCache();
          AttributesFactory af = new AttributesFactory();
          af.setScope(Scope.DISTRIBUTED_ACK);
          af.setDataPolicy(DataPolicy.REPLICATE);
          Region region = cache.createRegion("region", af.create());
        }
      };

      vm0.invoke(createParent);
      vm1.invoke(createParent);

      final SerializableRunnable createChild = new SerializableRunnable() {

        @Override
        public void run() {
          Cache cache = getCache();
          Region region = cache.getRegion("region");
          if (region != null) {
            AttributesFactory af = new AttributesFactory();
            af.setScope(Scope.DISTRIBUTED_ACK);
            af.setDataPolicy(DataPolicy.REPLICATE);
            Region subregion = region.createSubregion("subregion", af.create());
          }

        }
      };
      vm0.invoke(createChild);

      final SerializableRunnable destroyParent = new SerializableRunnable() {

        @Override
        public void run() {
          Cache cache = getCache();
          Region region = cache.getRegion("/region");
          region.destroyRegion();
        }
      };

      AsyncInvocation future = vm0.invokeAsync(destroyParent);
      try {
        vm1.invoke(createChild);
      } catch (Exception e) {
        if (!(e.getCause() instanceof RegionDestroyedException)) {
          Assert.fail("Wrong exception", e);
        }
        RegionDestroyedException rde = (RegionDestroyedException) e.getCause();
        assertEquals("Error on loop " + i, "/region", rde.getRegionFullPath());
      }
      future.getResult(60 * 1000);
    }
  }

  @Test
  public void testPartitionedRegion() throws Throwable {
    final Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);

    for (int i = 0; i < 50; i++) {
      final SerializableRunnable createParent = new SerializableRunnable() {

        @Override
        public void run() {
          Cache cache = getCache();
          AttributesFactory af = new AttributesFactory();
          af.setScope(Scope.DISTRIBUTED_ACK);
          af.setDataPolicy(DataPolicy.REPLICATE);
          Region region = cache.createRegion("region", af.create());
        }
      };

      vm0.invoke(createParent);
      vm1.invoke(createParent);

      final SerializableRunnable createChild = new SerializableRunnable() {

        @Override
        public void run() {
          Cache cache = getCache();
          Region region = cache.getRegion("region");
          if (region != null) {
            AttributesFactory af = new AttributesFactory();
            af.setDataPolicy(DataPolicy.PARTITION);
            Region subregion = region.createSubregion("subregion", af.create());
          }

        }
      };
      vm0.invoke(createChild);

      final SerializableRunnable destroyParent = new SerializableRunnable() {

        @Override
        public void run() {
          Cache cache = getCache();
          Region region = cache.getRegion("/region");
          region.destroyRegion();
        }
      };

      AsyncInvocation future = vm0.invokeAsync(destroyParent);
      try {
        vm1.invoke(createChild);
      } catch (Exception e) {
        if (!(e.getCause() instanceof RegionDestroyedException)) {
          Assert.fail("Wrong exception", e);
        }
        RegionDestroyedException rde = (RegionDestroyedException) e.getCause();
        assertEquals("Error on loop " + i, "/region", rde.getRegionFullPath());
      }
      future.getResult(60 * 1000);
    }
  }

}


text:
package com.example.sqlbrite.todo.ui;

import android.database.Cursor;
import auto.parcel.AutoParcel;
import com.example.sqlbrite.todo.db.Db;
import com.example.sqlbrite.todo.db.TodoItem;
import com.example.sqlbrite.todo.db.TodoList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import rx.functions.Func1;

import static com.squareup.sqlbrite.SqlBrite.Query;

@AutoParcel
abstract class ListsItem {
  private static String ALIAS_LIST = "list";
  private static String ALIAS_ITEM = "item";

  private static String LIST_ID = ALIAS_LIST + "." + TodoList.ID;
  private static String LIST_NAME = ALIAS_LIST + "." + TodoList.NAME;
  private static String ITEM_COUNT = "item_count";
  private static String ITEM_ID = ALIAS_ITEM + "." + TodoItem.ID;
  private static String ITEM_LIST_ID = ALIAS_ITEM + "." + TodoItem.LIST_ID;

  public static Collection<String> TABLES = Arrays.asList(TodoList.TABLE, TodoItem.TABLE);
  public static String QUERY = ""
      + "SELECT " + LIST_ID + ", " + LIST_NAME + ", COUNT(" + ITEM_ID + ") as " + ITEM_COUNT
      + " FROM " + TodoList.TABLE + " AS " + ALIAS_LIST
      + " LEFT OUTER JOIN " + TodoItem.TABLE + " AS " + ALIAS_ITEM + " ON " + LIST_ID + " = " + ITEM_LIST_ID
      + " GROUP BY " + LIST_ID;

  abstract long id();
  abstract String name();
  abstract int itemCount();

  static Func1<Query, List<ListsItem>> MAP = new Func1<Query, List<ListsItem>>() {
    @Override public List<ListsItem> call(Query query) {
      Cursor cursor = query.run();
      try {
        List<ListsItem> values = new ArrayList<>(cursor.getCount());
        while (cursor.moveToNext()) {
          long id = Db.getLong(cursor, TodoList.ID);
          String name = Db.getString(cursor, TodoList.NAME);
          int itemCount = Db.getInt(cursor, ITEM_COUNT);
          values.add(new AutoParcel_ListsItem(id, name, itemCount));
        }
        return values;
      } finally {
        cursor.close();
      }
    }
  };
}

redpajama_set_name: RedPajamaGithub


text:
package jwt

import (
	"bytes"
	"encoding/json"
	"reflect"
)

var (
	// tokenSep is the token separator.
	tokenSep = []byte{'.'}
)

// Decode decodes a serialized JWT in buf into obj, and verifies the JWT
// signature using the Algorithm and Signer.
//
// If the token or signature is invalid, ErrInvalidToken or ErrInvalidSignature
// will be returned, respectively. Otherwise, any other errors encountered
// during token decoding will be returned.
func Decode(alg Algorithm, signer Signer, buf []byte, obj interface{}) error {
	var err error

	// split token
	ut := UnverifiedToken{}
	err = DecodeUnverifiedToken(buf, &ut)
	if err != nil {
		return err
	}

	// verify signature
	sig, err := signer.Verify(buf[:len(ut.Header)+len(tokenSep)+len(ut.Payload)], ut.Signature)
	if err != nil {
		return ErrInvalidSignature
	}

	// b64 decode header
	headerBuf, err := b64.DecodeString(string(ut.Header))
	if err != nil {
		return err
	}

	// json decode header
	header := Header{}
	err = json.Unmarshal(headerBuf, &header)
	if err != nil {
		return err
	}

	// verify alg matches header algorithm
	if alg != header.Algorithm {
		return ErrInvalidAlgorithm
	}

	// set header in the provided obj
	err = decodeToObjOrFieldWithTag(headerBuf, obj, "header", &header)
	if err != nil {
		return err
	}

	// b64 decode payload
	payloadBuf, err := b64.DecodeString(string(ut.Payload))
	if err != nil {
		return err
	}

	// json decode payload
	payload := Claims{}
	err = json.Unmarshal(payloadBuf, &payload)
	if err != nil {
		return err
	}

	// set payload in the provided obj
	err = decodeToObjOrFieldWithTag(payloadBuf, obj, "payload", &payload)
	if err != nil {
		return err
	}

	// set sig in the provided obj
	field := getFieldWithTag(obj, "signature")
	if field != nil {
		field.Set(reflect.ValueOf(sig))
	}

	return nil
}

// Encode encodes a JWT using the Algorithm and Signer, returning the URL-safe
// encoded token or any errors encountered during encoding.
func Encode(alg Algorithm, signer Signer, obj interface{}) ([]byte, error) {
	var err error

	// grab encode targets
	headerObj, payloadObj, err := encodeTargets(alg, obj)
	if err != nil {
		return nil, err
	}

	// json encode header
	header, err := json.Marshal(headerObj)
	if err != nil {
		return nil, err
	}

	// b64 encode playload
	headerEnc := make([]byte, b64.EncodedLen(len(header)))
	b64.Encode(headerEnc, header)

	// json encode payload
	payload, err := json.Marshal(payloadObj)
	if err != nil {
		return nil, err
	}

	// b64 encode playload
	payloadEnc := make([]byte, b64.EncodedLen(len(payload)))
	b64.Encode(payloadEnc, payload)

	// allocate result
	var buf bytes.Buffer

	// add header
	_, err = buf.Write(headerEnc)
	if err != nil {
		return nil, err
	}

	// add 1st separator
	_, err = buf.Write(tokenSep)
	if err != nil {
		return nil, err
	}

	// add payload
	_, err = buf.Write(payloadEnc)
	if err != nil {
		return nil, err
	}

	// sign
	sig, err := signer.Sign(buf.Bytes())
	if err != nil {
		return nil, err
	}

	// add 2nd separator
	_, err = buf.Write(tokenSep)
	if err != nil {
		return nil, err
	}

	// add sig
	_, err = buf.Write(sig)
	if err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}

// PeekHeaderField extracts the specified field from the serialized JWT buf's
// header. An error will be returned if the field is not present in the decoded
// header.
func PeekHeaderField(buf []byte, field string) (string, error) {
	return peekField(buf, field, tokenPositionHeader)
}

// PeekPayloadField extracts the specified field from the serialized JWT buf's
// payload (ie, the token claims). An error will be returned if the field is
// not present in the decoded payload.
func PeekPayloadField(buf []byte, field string) (string, error) {
	return peekField(buf, field, tokenPositionPayload)
}

// PeekAlgorithm extracts the signing algorithm listed in the "alg" field of
// the serialized JWT buf's header and attempts to unmarshal it into an
// Algorithm. An error will be returned if the alg field is not specified in
// the JWT header, or is otherwise invalid.
func PeekAlgorithm(buf []byte) (Algorithm, error) {
	alg := NONE

	// get alg
	algVal, err := PeekHeaderField(buf, "alg")
	if err != nil {
		return NONE, err
	}

	// decode alg
	err = (&alg).UnmarshalText([]byte(algVal))
	if err != nil {
		return NONE, err
	}

	return alg, nil
}

// PeekAlgorithmAndIssuer extracts the signing algorithm listed in the "alg"
// field and the issuer from the "iss" field of the serialized JWT buf's header
// and payload, attempting to unmarshal alg to Algorithm and iss to a string.
// An error will be returned if the Algorithm or Issuer fields are not
// specified in the JWT header and payload, or are otherwise invalid.
func PeekAlgorithmAndIssuer(buf []byte) (Algorithm, string, error) {
	var err error

	// get algorithm
	alg, err := PeekAlgorithm(buf)
	if err != nil {
		return NONE, "", err
	}

	// get issuer
	issuer, err := PeekPayloadField(buf, "iss")
	if err != nil {
		return NONE, "", err
	}

	return alg, issuer, nil
}


text:
<?php

/**
 * @file
 * Contains \Drupal\system\Controller\SystemInfoController.
 */

namespace Drupal\system\Controller;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\system\SystemManager;

/**
 * Returns responses for System Info routes.
 */
class SystemInfoController implements ContainerInjectionInterface {

  /**
   * System Manager Service.
   *
   * @var \Drupal\system\SystemManager
   */
  protected $systemManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('system.manager')
    );
  }

  /**
   * Constructs a SystemInfoController object.
   *
   * @param \Drupal\system\SystemManager $systemManager
   *   System manager service.
   */
  public function __construct(SystemManager $systemManager) {
    $this->systemManager = $systemManager;
  }

  /**
   * Displays the site status report.
   *
   * @return string
   *   The current status of the Drupal installation.
   */
  public function status() {
    $requirements = $this->systemManager->listRequirements();
    return array('#theme' => 'status_report', '#requirements' => $requirements);
  }

  /**
   * Returns the contents of phpinfo().
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   A response object to be sent to the client.
   */
  public function php() {
    if (function_exists('phpinfo')) {
      ob_start();
      phpinfo();
      $output = ob_get_clean();
    }
    else {
      $output = t('The phpinfo() function has been disabled for security reasons. For more information, visit Enabling and disabling phpinfo() handbook page.', array(':phpinfo' => 'https://www.drupal.org/node/243993'));
    }
    return new Response($output);
  }

}


text:
{% extends "base.html" %}

{% block title %}Collected Urls{% endblock %}

{% block head %}
    {{ super() }}
{% endblock %}

{% block content %}

Hosts

{{ host }}

{{ host }}

Path Analysis

www.example.com/test/path?a=parameter.

Parameter Analysis

www.example.com/test/path?a=parameter.

Form Analysis

Analyse collected forms and parameters

Cookie Analysis

Track changes in cookies

{% endblock %}


text:
/*global console: true */
/*global Modernizr: true */
/*global $: true */

/**
 *  WIDGET NAME
 *
 *  @description description here
 *  @example
 *      var myWidget = new NAMESPACE.Widget(param1, param2, param2);
 *
 *  @author
 *  @version 0.0.0
 *  @requires
 *      - jQuery 1.8
 */

var NAMESPACE = NAMESPACE || {};

NAMESPACE.Widget = function(target){

	this.target = target;

	this.init();
};

NAMESPACE.Widget.prototype = {

	init: function(){

		// el refs

		// shared properties

		// event listeners

		// setup
	}

};


text:
//Copyright(c) 2001-2021 Aspose Pty Ltd.All rights reserved.
//https://github.com/aspose-barcode/Aspose.BarCode-for-.NET
using Aspose.BarCode.Generation;

namespace Aspose.BarCode.Examples.CSharp.BarcodeGeneration
{
    internal class Pdf417RowColumns : TwoDBase
    {
		public static void Run()
        {
            string path = GetFolder();
            System.Console.WriteLine("Pdf417RowColumns:");

            BarcodeGenerator gen = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©");
            gen.Parameters.Barcode.XDimension.Pixels = 2;
            //set 2 columns
            gen.Parameters.Barcode.Pdf417.Columns = 2;
            gen.Save($"{path}Pdf417Columns2.png", BarCodeImageFormat.Png);
            //set 3 rows
            gen.Parameters.Barcode.Pdf417.Columns = 0;
            gen.Parameters.Barcode.Pdf417.Rows = 6;
            gen.Save($"{path}Pdf417Row6.png", BarCodeImageFormat.Png);
            //set 4 columns 9 rows
            gen.Parameters.Barcode.Pdf417.Columns = 4;
            gen.Parameters.Barcode.Pdf417.Rows = 9;
            gen.Save($"{path}Pdf417Row9Columns4.png", BarCodeImageFormat.Png);
        }
    }
}


text:
<?php
require_once dirname( __FILE__ ) . '/vendor/autoload.php';
use \Slim\Slim;
use \Slim\LogWriter;
use \Config\Database\DbHandler;
use \Config\SecureSessionHandler;

\Slim\Slim::registerAutoloader();

$_ENV['SLIM_MODE'] = APP_ENV;

$app = new \Slim\Slim();
$app->setName( 'LQ_API' );

// Only invoked if mode is "production"
$app->configureMode( 'production', function () use ( $app ) {
	$app->config( array(
		'log.enable' => true,
		'debug' => false
	));
	$handle = fopen( 'debug.log', 'w' );
	$app->log->setWriter( new \Slim\LogWriter( $handle ) );
});

// Only invoked if mode is "development"
$app->configureMode( 'development', function () use ( $app ) {
	$app->config( array(
		'log.enable' => false,
		'debug' => true
	));
});

/**
 * Perform an API get status
 * This is not much than a ping on the API server
 */
$app->get(
	'/status', function() {
		$response['status'] = 'ok';
		echoRespnse( 200, $response );
		exit;
	}
);

/**
 * Try to perform a user log in
 * If the user is authenticated, then start the session cookie
 */
$app->post(
	'/login', function() use ( $app ) {
		// Dev only
		// Sleep 3 seconds before processing the request
		// to display the loader
		sleep(1);

		// check for required params
		verify_required_params( array( 'email', 'password' ) );

		// reading post params
		$email    = $app->request()->post( 'email' );
		$password = $app->request()->post( 'password' );
		$response = array(
			'request' => 'login'
		);

		// Sanitize data
		$email    = filter_var(  $email, FILTER_SANITIZE_EMAIL );
		$password = filter_var( $password, FILTER_SANITIZE_STRING );

		// Validate data
		if ( ! ( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) ) {
			$response['error'] = true;
			$response['msg']   = 'Input data not valid.';
			echoRespnse( 401, $response );
			$app->stop();
		}

		$db = new DbHandler();

		// check for correct email and password
		if ( $db_uid = $db->checkUserExisits( $email ) ) {
			// Check the brute force
			if ( $db->checkBrute( $db_uid ) ) {
				// Account is locked
				$response['error'] = true;
				$response['msg']   = 'Accout locked.';
				echoRespnse( 401, $response );
				$app->stop();
			}

			if ( $db->userLogin( $email, $password ) ) {
				$response['error'] = false;
				$response['login'] = true;
				$response['msg']   = 'User logged in.';
				echoRespnse( 200, $response );
				$app->stop();
			}
			else {
				$response['error'] = true;
				$response['msg']   = 'Password wrong.';
				echoRespnse( 401, $response );
				$app->stop();
			}
		}
		else {
			$response['error'] = true;
			$response['msg']   = 'User not found.';
			echoRespnse( 401, $response );
			$app->stop();
		}
	}
);

/**
 * Register a new user
 */
$app->post(
	'/register', function() use ( $app ) {
		// Dev only
		// Sleep 3 seconds before processing the request
		// to display the loader
		sleep(2);

		// check for required params
		verify_required_params( array(
			'name',
			'email',
			'email_confirm',
			'password',
			'password_confirm',
			'language'
		));

		// reading post params
		$user = array(
			'name'             => $app->request()->post( 'name' ),
			'email'            => $app->request()->post( 'email' ),
			'email_confirm'    => $app->request()->post( 'email_confirm' ),
			'password'         => $app->request()->post( 'password' ),
			'password_confirm' => $app->request()->post( 'password_confirm' ),
			'language'         => $app->request()->post( 'language' ),
		);

		// prepare the answer
		$response = array(
			'request' => 'register'
		);

		// Sanitize data
		$user['name']             = filter_var(  $user['name'], FILTER_SANITIZE_STRING );
		$user['email']            = filter_var(  $user['email'], FILTER_SANITIZE_EMAIL );
		$user['email_confirm']    = filter_var(  $user['email_confirm'], FILTER_SANITIZE_EMAIL );
		$user['password']         = filter_var( $user['password'], FILTER_SANITIZE_STRING );
		$user['password_confirm'] = filter_var( $user['password_confirm'], FILTER_SANITIZE_STRING );
		$user['language']         = filter_var( $user['language'], FILTER_SANITIZE_STRING );

		//Make sure the 2 emails are the same
		if ( $user['email'] !== $user['email_confirm'] ) {
			$response['error'] = true;
			$response['msg']   = 'Email verification failed.';
			echoRespnse( 401, $response );
			$app->stop();
		}

		//Make sure the 2 passwords are the same
		if ( $user['password'] !== $user['password_confirm'] ) {
			$response['error']   = true;
			$response['msg']     = 'Password verification failed.';
			echoRespnse( 401, $response );
			$app->stop();
		}

		//Make sure the user has selected a language
		if ( $user['language'] === 'undefined' || $user['language'] === '' ) {
			$response['error']   = true;
			$response['msg']     = 'The language is missing.';
			echoRespnse( 401, $response );
			$app->stop();
		}

		// Validate data
		if ( ! ( filter_var( $user['email'], FILTER_VALIDATE_EMAIL ) ) ) {
			$response['error'] = true;
			$response['msg']   = 'Email not valid.';
			echoRespnse( 401, $response );
			$app->stop();
		}

		$db = new DbHandler();

		// Try to register a new user
		if ( $db->userRegister( $user ) ) {
			$response['error']    = false;
			$response['register'] = true;

			// Log the user in
			if ( $db->userLogin( $user['email'], $user['password'] ) ) {
				$response['error'] = false;
				$response['login'] = true;
				$response['msg']   = 'User correctly registered.';
				echoRespnse( 200, $response );
				$app->stop();
			}
			else {
				$response['error'] = true;
				$response['msg']   = 'Username or passeord wrong.';
				echoRespnse( 401, $response );
				$app->stop();
			}
		}
		else {
			$response['error'] = true;
			$response['msg']   = 'Another user with the same email already exists in the database.';
			echoRespnse( 401, $response );
			$app->stop();
		}
	}
);

$app->post(
	'/user/:userid', 'authenticate', function( $userUID ) use ( $app ) {
		sleep(2);
		$response = array(
			'request' => 'user'
		);
		$user = array();
		$db   = new DbHandler();

		$user = $db->getUser( $userUID );

		if ( !empty( $user ) ) {
			$response['error'] = false;
			$response['user']  = $user;
			$response['msg']   = 'User found.';
			echoRespnse( 200, $response );
			$app->stop();
		}

		$response['error'] = true;
		$response['msg']   = 'The user is not present in the database.';
		echoRespnse( 400, $response );
		$app->stop();
});

$app->get(
	'/user/:userid/profile', 'authenticate', function( $userUID ) use ( $app ) {
		sleep(2);
		$response = array(
			'request' => 'profile'
		);

		$user = array();
		$db   = new DbHandler();

		$profile = $db->getUserProfile( $userUID );

		if ( !empty( $profile ) ) {
			$response['error']   = false;
			$response['profile'] = $profile;
			$response['msg']     = 'Profile information updated.';
			echoRespnse( 200, $response );

			$app->stop();
		}

		$response['error'] = true;
		$response['msg']   = 'Impossible to retrieve the user information.';
		echoRespnse( 400, $response );
		$app->stop();
});

$app->post(
	'/user/:userid/profile', 'authenticate', function() use ( $app ) {
		sleep(2);
		// check for required params
		verify_required_params( array(
			'username',
			'email'
		));

		// reading post params
		$user = array(
			'name'             => $app->request()->post( 'username' ),
			'email'            => $app->request()->post( 'email' ),
			'old_password'     => $app->request()->post( 'old_password' ),
			'password'         => $app->request()->post( 'password' ),
			'password_confirm' => $app->request()->post( 'password_confirm' ),
		);

		// prepare the answer
		$response = array(
			'request' => 'profile'
		);

		// Sanitize data
		$user['name']  = filter_var(  $user['name'], FILTER_SANITIZE_STRING );
		$user['email'] = filter_var(  $user['email'], FILTER_SANITIZE_EMAIL );

		$db      = new DbHandler();
		$userUID = $app->getCookie( 'lq_user_id' );

		// Try to update the user details
		if ( $db->updateUserProfile( $userUID, $user['name'], $user['email'] ) ) {
			$response['error'] = false;
		}
		else {
			$response['error'] = true;
			$response['msg']   = 'Impossible to update the user profile.';
			echoRespnse( 401, $response );
			$app->stop();
		}
		// If the user sent a password, reset that as well
		if ( isset( $user['old_password'] ) || isset( $user['password'] ) || isset( $user['password_confirm'] ) ) {
			verify_required_params( array(
				'old_password',
				'password',
				'password_confirm',
			));

			$user['old_password']     = filter_var( $user['old_password'], FILTER_SANITIZE_STRING );
			$user['password']         = filter_var( $user['password'], FILTER_SANITIZE_STRING );
			$user['password_confirm'] = filter_var( $user['password_confirm'], FILTER_SANITIZE_STRING );

			//Make sure the 2 passwords are the same
			if ( $user['password'] !== $user['password_confirm'] ) {
				$response['error']   = true;
				$response['msg']     = 'Password verification failed.';
				echoRespnse( 401, $response );
				$app->stop();
			}

			if ( $db->updateUserPassword( $userUID, $user['email'], $user['old_password'], $user['password'], $user['password_confirm'] ) ) {
				$response['error'] = false;
				$response['msg']   = 'User information saved.';
				echoRespnse( 200, $response );
				$app->stop();
			}
			else {
				$response['error'] = true;
				$response['msg']   = 'Impossible to update the user password.';
				echoRespnse( 401, $response );
				$app->stop();
			}
		}
		else {
			$response['msg'] = 'User information saved.';
			echoRespnse( 200, $response );
			$app->stop();
		}
});

$app->get(
	'/user/:userid/profile/avatar', 'authenticate', function( $userUID ) use ( $app ) {
		sleep(2);
		$response = array(
			'request' => 'get_avatar'
		);
		$user = array();
		$db   = new DbHandler();

		$profile = $db->getUserAvatar( $userUID );

		if ( ! empty( $profile ) ) {
			$response['error']   = false;
			$response['profile'] = $profile;
			$response['msg']     = 'Avatar updated.';
			echoRespnse( 200, $response );

			$app->stop();
		}

		$response['error'] = true;
		$response['msg']   = 'Impossible to retrieve the user avatar.';
		echoRespnse( 400, $response );
		$app->stop();
});

$app->post(
	'/user/:userid/profile/avatar', 'authenticate', function() use ( $app ) {
		// prepare the answer
		$response = array(
			'request' => 'avatar'
		);

		if ( empty( $_FILES['file'] ) ) {
			$response['error'] = true;
			$response['msg']   = 'File information missing or wrong.';
			echoRespnse( 400, $response );
			$app->stop();
		}

		if ( 0 < $_FILES['file']['error'] ) {
			$response['error'] = true;
			$response['msg']   = 'Impossible to read the image file.';
			echoRespnse( 400, $response );
			$app->stop();
		}

		$mime_types = array(
			'image/png'  => '.png',
			'image/gif'  => '.gif',
			'image/jpeg' => '.jpeg',
			'image/png'  => '.png',
			'image/tiff' => '.tif',
		);

		// $file_ext = array_search( $_FILES['file']['type'], $file_types );
		$userUID   = $app->getCookie( 'lq_user_id' );
		$file      = $_FILES['file'];
		$file_type = $_FILES['file']['type'];

		if ( ! array_key_exists( $file_type, $mime_types ) ) {
			$response['error'] = true;
			$response['msg']   = 'File format not valid.';
			echoRespnse( 400, $response );
			$app->stop();
		}

		$file_ext = $mime_types[$file_type];
		$name     = 'avatar-' . $userUID;
		move_uploaded_file( $file['tmp_name'], '../img/avatars/' . $name );

		// Sanitize data
		$db = new DbHandler();

		// Try to update the user details
		$file_path = APP_DIR . 'img/avatars/' . $name;

		if ( $db->updateUserAvatar( $file_path, $userUID ) ) {
			$response['error'] = false;
			$response['profile']['avatar'] = $file_path;
			$response['msg']   = 'Avatar saved successfully.';
			echoRespnse( 200, $response );
			$app->stop();
		}

		$response['error'] = true;
		$response['msg']   = 'Impossible to save the new avatar.';
		echoRespnse( 400, $response );
		$app->stop();
});

$app->get(
	'/user/:userid/collections/', 'authenticate', function( $userid ) use ( $app ) {
		sleep(2);
		$page     = $app->request()->get( 'page' );
		$page     = isset( $page ) ? $page : 0;
		$db       = new DbHandler();
		$response = array(
			'request' => 'collections'
		);

		$collections = $db->getCollections( 0, $userid, $page );

		if ( ! empty( $collections['collections'] ) ) {
			$response['error']       = false;
			$response['collections'] = $collections['collections'];
			$response['loadMore']    = $collections['loadMore'];
			$response['msg']         = 'Collections correctly fetched.';
			echoRespnse( 200, $response );
			$app->stop();
		}

		$response['error']    = true;
		$response['loadMore'] = $collections['loadMore'];
		$response['msg']      = 'Cannot retrieve new collections.';
		echoRespnse( 200, $response );
		$app->stop();
});

/**
 * Log out
 * terminate the current session
 */
$app->get(
	'/logout', function() use ( $app ) {
		// Dev only
		sleep(1);

		$user_session = isset( $_COOKIE["LQ_session"] ) ? $_COOKIE["LQ_session"] : '';
		$db           = new DbHandler();

		$response = array(
			'request' => 'logout'
		);

		// If the session cookie is not set
		// terminate the request
		if ( $user_session === '' ) {
			$response['error']      = true;
			$response['logged_out'] = true;
			$response['msg']        = 'Impossible to get the required user information to perform a log out.';

			echoRespnse( 200, $response );
			$app->stop();
		}

		$db->logOut( $user_session );
		$response['error']      = false;
		$response['logged_out'] = true;
		$response['msg']        = 'User logged out.';
		echoRespnse( 200, $response );
		$app->stop();

	}
);

/**
 * Verifying required params posted or not
 */
function verify_required_params( $required_fields ) {
	$error          = false;
	$error_fields   = '';
	$request_params = array();
	$request_params = $_REQUEST;

	// Handling PUT request params
	if ( $_SERVER['REQUEST_METHOD'] === 'PUT' ) {
		$app = \Slim\Slim::getInstance();
		parse_str( $app->request()->getBody(), $request_params );
	}
	foreach ( $required_fields as $field ) {
		if ( !isset( $request_params[$field] ) || strlen( trim( $request_params[$field] ) ) <= 0 ) {
			$error         = true;
			$error_fields .= $field . ', ';
		}
	}

	if ( $error ) {
		// Required field(s) are missing or empty
		// echo error json and stop the app
		$response            = array();
		$app                 = \Slim\Slim::getInstance();
		$response['error'] = true;
		$response['msg']   = 'Required field(s) ' . substr( $error_fields, 0, -2 ) . ' is missing or empty.';

		echoRespnse( 401, $response );
		$app->stop();
	}
}

/**
 * Adding Middle Layer to authenticate every request
 * Checking if the request has valid api key in the 'Authorization' header
 */
function authenticate( \Slim\Route $route ) {
	// Getting request headers
	$headers  = apache_request_headers();
	$response = array();
	$app = \Slim\Slim::getInstance();

	$user = array();
	$db   = new DbHandler();

	$userSession = $app->getCookie( 'LQ_session' );
	$userUID     = $app->getCookie( 'lq_user_id' );

	$header  = array_change_key_case( $headers, CASE_UPPER );
	$api_key = isset( $header['LQ-API-KEY'] ) ? $header['LQ-API-KEY'] : '';

	if ( isset( $api_key ) ) {
	// 	// get the api key
	// 	// validating api key
		if ( $api_key !== '406cc6ed2c7471d7593461264c0db966' ) {
	// 		// api key is not present in users table
			$response['error'] = true;
			$response['msg']   = 'Access Denied. Invalid Api key.';
			echoRespnse( 401, $response );
			$app->stop();
		}
		if ( ! $db->authenticate( $userUID, $userSession ) ) {
			// authentication failed
			$response['error'] = true;
			$response['msg']   = 'Authentication failed.';
			echoRespnse( 401, $response );
			$app->stop();
		}
	}
	else {
		// api key is missing in header
		$response['error'] = true;
		$response['msg']   = 'Api key is misssing.';
		echoRespnse( 401, $response );
		$app->stop();
	}
}

/**
 * Echoing json response to client
 * @param String $status_code Http response code
 * @param Int $response Json response
 */
function echoRespnse( $status_code, $response ) {
	$app = \Slim\Slim::getInstance();

	// Http response code
	$app->status( $status_code );

	// setting response content type to json
	$app->contentType( 'application/json' );

	echo json_encode( $response );
}

$app->run();
?>


text:
namespace rime {

class EchoTranslator : public Translator {
 public:
  EchoTranslator(const Ticket& ticket);

  virtual an<Translation> Query(const string& input,
                                        const Segment& segment);
};

}  // namespace rime

#endif  // RIME_ECHO_TRANSLATOR_H_


text:
package com.croconaut.ratemebuddy.data.pojo;

import java.io.Serializable;

public class VoteUp implements Serializable {
    private static final long serialVersionUID = 5L;

    private final String profileName;
    private final String statusId;
    private final String profileId;

    private String crocoId;
    private boolean seen;

    private VoteUp(Builder builder) {
        this.profileName = builder.name;
        this.statusId = builder.statusId;
        this.profileId = builder.profileId;
        this.crocoId = builder.crocoId;
        this.seen = builder.seen;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof VoteUp)) return false;

        VoteUp that = (VoteUp) o;

        if (!getStatusId().equals(that.getStatusId())) return false;
        return getProfileId().equals(that.getProfileId());

    }

    @Override
    public int hashCode() {
        int result = 31 + getStatusId().hashCode();
        result = 31 * result + getProfileId().hashCode();
        return result;
    }

    public void setSeen(boolean seen){
        this.seen = seen;
    }

    public String getProfileName() {
        return profileName;
    }

    public String getStatusId() {
        return statusId;
    }

    public String getProfileId() {
        return profileId;
    }

    public boolean isSeen() {
        return seen;
    }

    public String getCrocoId() {
        return crocoId;
    }

    public static class Builder {
        private final String name;
        private final String statusId;
        private final String profileId;

        private String crocoId;
        private boolean seen = false;

        public Builder(String name, String statusId, String profileId) {
            this.name = name;
            this.statusId = statusId;
            this.profileId = profileId;
        }

        public Builder(VoteUp voteUp) {
            this.name = voteUp.profileName;
            this.statusId = voteUp.statusId;
            this.profileId = voteUp.profileId;
            this.crocoId = voteUp.crocoId;
            this.seen = voteUp.seen;
        }

        public Builder seen(boolean seen) {
            this.seen = seen;
            return this;
        }

        public Builder crocoId(String crocoId) {
            this.crocoId = crocoId;
            return this;
        }

        public VoteUp build() {
            return new VoteUp(this);
        }
    }
}


text:
JustinMortonLabTest
===================

GameAILabTest


text:
namespace cutl_details_boost{

BOOST_TT_AUX_TYPE_TRAIT_DEF1(add_lvalue_reference,T,typename cutl_details_boost::add_reference<T>::type)

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
BOOST_TT_AUX_TYPE_TRAIT_PARTIAL_SPEC1_1(typename T,add_lvalue_reference,T&&,T&)
#endif

}

#include <cutl/details/boost/type_traits/detail/type_trait_undef.hpp>

#endif  // BOOST_TYPE_TRAITS_EXT_ADD_LVALUE_REFERENCE__HPP


text:
class Activity < LazyLoggingModel
  establish_connection("#{Rails.env}_logging")

  CACHE_ALL_ROWS = true
  uses_translations

  has_many :activity_logs
  has_many :curator_activity_logs
  has_many :translated_activities

  # NOTE - assumes Language.english exists.  You'll get weird results otherwise.
  # NOTE - These are only activities THAT GET LOGGED.  ...for now.
  # NOTE - The tense is inconsistent, but doesn't *really* matter.  Keep the ones you see as-is (since they are in
  # the DB... but as you add new ones, try to use the verb's present tense ("take", not "taken" or "took").
  # TODO - many of these are not used yet.  Add them to the code in the appropriate place
  def self.create_defaults
    %w(create update delete trusted untrusted show hide inappropriate rate unreviewed add_association
       remove_association choose_exemplar_image choose_exemplar_article add_common_name remove_common_name
       preferred_classification curate_classifications split_classifications merge_classifications trust_common_name
       untrust_common_name inappropriate_common_name unreview_common_name unlock unlock_with_error crop add_editor
       bulk_add create collect remove remove_all create delete join leave add_collection change_description
       change_name change_icon add_manager).each do |action|
      Activity.find_or_create(action)
    end
    Activity.count
  end

  def self.find_or_create(key_sym)
    key = key_sym.to_s
    act = Activity.cached_find_translated(:name, key)
    unless act
      act = Activity.new()
      act.save! # NOTE: #create wasn't working; the ID wasn't being set correctly.
      if transact = TranslatedActivity.find_by_language_id_and_name(Language.english.id, key)
        transact.update_attributes(:activity_id => act.id)
      else
        # Doing this with raw sql to override the LoggingModel's default of using INSERT DELAYED
        TranslatedActivity.connection.execute(ActiveRecord::Base.sanitize_sql_array(
          ['INSERT INTO translated_activities (name, activity_id, language_id) VALUES (?, ?, ?)',
            key, act.id, Language.english.id]
        ))
      end
      act = Activity.cached_find_translated(:name, key)
    end
    act
  end

  def self.synonym_activity_ids
    @@synonym_activity_ids ||= cached("synonym_activity_ids") do
      [Activity.add_common_name.id, Activity.remove_common_name.id, Activity.trust_common_name.id,
        Activity.unreview_common_name.id, Activity.untrust_common_name.id, Activity.inappropriate_common_name.id]
    end
  end

  def self.method_missing(name, *args, &block)
    @@activity_local_cache ||= {}
    @@activity_local_cache[name] ||= cached("activity_method_missing_#{name}") do
      # TODO - this should be cached, but since we're in method_missing, that's tricky.
      transact = TranslatedActivity.find(:first, :conditions => ["name = ? AND language_id = ?", name.to_s,
                                    Language.english.id])
      if transact
        transact.activity
      else
        super
      end
    end
  end

  # Since create is normally a reserved word, the method missing won't work for it (all the time):
  def self.create
    act = self.cached_find_translated(:name, 'create')
  end

  # Since delete is normally a reserved word, the method missing won't work for it (all the time):
  def self.delete
    act = self.cached_find_translated(:name, 'delete')
  end

  # Since create is normally a reserved word, the method missing won't work for it (all the time):
  def self.update
    act = self.cached_find_translated(:name, 'update')
  end

  # Helper to provide consistent calculation of curator actions when using curator_activity_logs_on_data_objects
  # association
  def self.raw_curator_action_ids
        [ trusted.id,
          untrusted.id,
          show.id,
          hide.id,
          inappropriate.id,
          unreviewed.id ]
  end

end


text:
namespace ThorsAnvil
{
    namespace Nisse
    {
        namespace Core
        {
            namespace Utility
            {

template<typename... Args>
void print(std::ostream& s, Args&... args)
{
    using Expander = int[];
    Expander ignore{ 0, (s << args, 0)...};
    (void)ignore; // Cast to ignore to avoid compiler warnings.
}

template<typename... Args>
std::string buildStringFromParts(Args const&... args)
{
    std::stringstream msg;
    print(msg, args...);
    return msg.str();
}

// @function
template<typename... Args>
std::string buildErrorMessage(char const*, char const*, Args const&... args)
{
    return buildStringFromParts(args...);
}

inline std::string errnoToName()
{
    switch (errno)
    {
#define  THOR_CASE(x)  case x: return #x " "
        THOR_CASE( EACCES );
        THOR_CASE( EADDRINUSE );
        THOR_CASE( EADDRNOTAVAIL );
        THOR_CASE( EAFNOSUPPORT );
        THOR_CASE( EAGAIN );
        // TODO );
        //THOR_CASE( EWOULDBLOCK );
        THOR_CASE( EBADF );
        THOR_CASE( ECONNABORTED );
        THOR_CASE( ECONNRESET );
        THOR_CASE( EDESTADDRREQ );
        THOR_CASE( EDQUOT );
        THOR_CASE( EEXIST );
        THOR_CASE( EFAULT );
        THOR_CASE( EFBIG );
        THOR_CASE( EINTR );
        THOR_CASE( EINVAL );
        THOR_CASE( EIO );
        THOR_CASE( EISDIR );
        THOR_CASE( ELOOP );
        THOR_CASE( EMFILE );
        THOR_CASE( ENAMETOOLONG );
        THOR_CASE( ENETDOWN );
        THOR_CASE( ENETUNREACH );
        THOR_CASE( ENFILE );
        THOR_CASE( ENOBUFS );
        THOR_CASE( ENOENT );
        THOR_CASE( ENOMEM );
        THOR_CASE( ENOSPC );
        THOR_CASE( ENOTCONN );
        THOR_CASE( ENOTDIR );
        THOR_CASE( ENOTSOCK );
        THOR_CASE( ENXIO );
        THOR_CASE( EOPNOTSUPP );
        THOR_CASE( EPIPE );
        THOR_CASE( EPROTONOSUPPORT );
        THOR_CASE( EPROTOTYPE );
        THOR_CASE( EROFS );
        THOR_CASE( ESPIPE );
        THOR_CASE( ETIMEDOUT );
        THOR_CASE( EALREADY );
        THOR_CASE( ECONNREFUSED );
        THOR_CASE( EHOSTUNREACH );
        THOR_CASE( EINPROGRESS );
        THOR_CASE( EISCONN );
#undef THOR_CASE
    }
    return "Unknown: ";
}

// @function
inline
std::string systemErrorMessage()
{
    std::string result = errnoToName();
    result += std::strerror(errno);
    return result;
}

            }
        }
    }
}

#endif


text:
Для установки гема и запуска интерактивной консоли необходимо выполнить следующие команды:

```
git clone git://github.com/maxsbelt/sandptest.git
cd sandptest
bin/console
```

Каждая задача реализована в своем пространстве имен, соответствующему номеру задачи. Например, метод `palindrom?` для решения первой задачи находится в пространстве имен `Sandptest::Task1`.

Задачи реализовывалить с использованием методологии TDD, т.е. сначала функциональные требования описывались тестами, после чего программировалась логика задачи. При выборе инструмента тестирования рассматривались следующие варианты:
* [rspec](http://rspec.info/)
* [minitest](https://github.com/seattlerb/minitest)

В результате был выбран гем `minitest` ввиду его легкости (меньшим количеством зависимостей).

Для запуска теста необходимо выполнить команду:
```
bundle exec rake test
```

Код гема опубликован под лицензией [MIT License](http://opensource.org/licenses/MIT).


text:
/**
 * core.spec.ts
 *
 * There are a number of message types and interactions which prepare the
 * roster, clients, and instances. These have various caveats and edge cases,
 * and can also be received in different orders. This file lays out these
 * requirement and ensures consistency.
 */

import * as freedomMocker from '../lib/freedom/mocks/mock-freedom-in-module-env';

import * as freedom_mocks from '../mocks/freedom-mocks';
declare var freedom: freedom.FreedomInModuleEnv;
freedom = freedomMocker.makeMockFreedomInModuleEnv({
  'core.online': () => { return new freedom_mocks.MockFreedomOnline(); },
  'core.storage': () => { return new freedom_mocks.MockFreedomStorage(); },
  'loggingcontroller': () => { return new freedom_mocks.MockLoggingController(); },
  'metrics': () => { return new freedom_mocks.MockMetrics(); },
  'pgp': () => { return new freedom_mocks.PgpProvider() },
  'portControl': () => { return new Object },
});

import * as globals from './globals';
import * as social from '../interfaces/social';
import * as social_network from './social';
import * as remote_user from './remote-user';
import * as local_instance from './local-instance';
import * as remote_instance from './remote-instance';
import * as uproxy_core_api from '../interfaces/uproxy_core_api';
import * as uproxy_core from './uproxy_core';

describe('Core', () => {

  // Set up a fake network -> roster -> user -> instance chain.
  var network = <social.Network><any>jasmine.createSpy('network');
  network.getUser = null;
  network.getStorePath = function() { return 'network-store-path'; };
  network['login'] = (loginType :uproxy_core_api.LoginType) => {
    return Promise.resolve();
  };
  network['myInstance'] =
            new local_instance.LocalInstance(network, 'localUserId');
  var user = new remote_user.User(network, 'fake-login');
  user.getInstance = null;
  user.notifyUI = () => {};
  user.getLocalInstanceId = () => { return 'fake/userpath'; };
  var alice = new remote_instance.RemoteInstance(user, 'instance-alice');
  // Mock out the probeProtocolSupport function.
  globals.portControl.probeProtocolSupport = () => {
    return Promise.resolve({'natPmp': false, 'pcp': false, 'upnp': false});
  };
  var core = new uproxy_core.uProxyCore();

  beforeEach(() => {
    spyOn(console, 'log');
  });

  it('passes modifyConsent to the correct user', () => {
    spyOn(social_network, 'getNetwork').and.callFake(() => {
      return network;
    });
    spyOn(network, 'getUser').and.callFake(() => {
      return user;
    });
    spyOn(user, 'modifyConsent');
    var command :uproxy_core_api.ConsentCommand = {
      path: {
        network: {
          name: 'fake-network',
          userId: 'fake-login'
        },
        userId: 'user-alice'
      },
      action: uproxy_core_api.ConsentUserAction.REQUEST
    };
    core.modifyConsent(command);
    expect(user.modifyConsent).toHaveBeenCalledWith(uproxy_core_api.ConsentUserAction.REQUEST);
  });

  it('login fails for invalid network', (done) => {
    core.login({network: 'nothing',
                loginType: uproxy_core_api.LoginType.INITIAL}).catch(() => {
      done();
    });
  });

  it('login continues to call login on correct network', (done) => {
    social_network.networks['mockNetwork'] = {};
    spyOn(social_network, 'FreedomNetwork').and.callFake(() => {
      network.myInstance = new local_instance.LocalInstance(network, 'fakeUser');
      return network;
    });

    // Login promise is not resolved so network object stays in pending logins
    var loginSpy = spyOn(network, 'login');
    loginSpy.and.returnValue(new Promise(() => {}));
    core.login({network: 'mockNetwork',
                loginType: uproxy_core_api.LoginType.INITIAL});
    expect(loginSpy).toHaveBeenCalled();

    // Core login will envoke login method on the same network object
    // This time it succeeds, so network object is moved from pending logins
    // to social_network.networks.
    loginSpy.and.returnValue(Promise.resolve());
    core.login({network: 'mockNetwork',
                loginType: uproxy_core_api.LoginType.INITIAL}).then(() => {
      // should have called login on the same spy twice and only constructed
      // one network
      expect(loginSpy.calls.count()).toEqual(2);
      expect((<any>(social_network.FreedomNetwork)).calls.count()).toEqual(1);
    }).then(done);
  });
});


text:
<META http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Unit Test Classes: org.apache.poi.hslf.model</title>
<link title="Style" type="text/css" rel="stylesheet" href="../../../../../stylesheet.css">

org.apache.poi.hslf.model

Classes

TestBackground

TestFreeform

TestHyperlink

TestImagePainter

TestLine

TestOleEmbedding

TestPicture

TestPPFont

TestPPGraphics2D

TestSetBoldItalic

TestShapes

TestSheet

TestSlideChangeNotes

TestSlideMaster

TestSlides

TestTextRun

TestTextRunReWrite

TestTextShape


text:
<!doctype html>

  <meta charset="utf-8">
  <title>IBM Bluemix Object Storage demo</title>
  <meta name="description" content="Cloud Foundry demo">
  <link rel="stylesheet" href="/css/home.min.css" />
  <link rel="stylesheet" href="/css/common.min.css" />

			IBM Bluemix Object Storage demo

Fork


text:
<!DOCTYPE html>

  <meta property="og.image" content="https://github.com/tedszy/tedszy.github.io/tree/master/assets/img/love_math.png" />

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

  <title>Gallery</title>
  <meta name="description" content="mathematics and computer science teaching">

    <link href='//fonts.googleapis.com/css?family=Lato:400,400italic' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" type="text/css" href="/css/tufte.css">

  <link rel="canonical" href="http://localhost:4000/page/gallery">

  <link rel="alternate" type="application/rss+xml" title="tedszy" href="http://localhost:4000/feed.xml" />

		      Creative Math!

		      blog

		      start

		      code

		      Docs

		      Training

		      videos

		      Gallery

		      contact

GALLERY

Brilliant work done by my students.

Beautiful group theory notes by grade 8 girl.

Highlight of an incredible combinatorics test paper. Grade 7

The layout and organization of this number theory computation
is a model of mathematical handwriting beauty. Grade 8 girl.

Proof of Ptolemy's second theorem on cyclic quadrilaterals. Grade 8.

Ruler-compass construction of huge polygon by grade 6 boy.

Visualization of 4D hypercube by grade 7 girl.

    Gallery - ted szylowiec

© 2020   TED SZYLOWIEC

This site created with the Tufte theme for math and informatics  in Jekyll.


text:
/** @stable */
export declare const platformBrowserDynamic: (extraProviders?: Provider[]) => PlatformRef;

/** @experimental */
export declare const RESOURCE_CACHE_PROVIDER: Provider[];


text:
package org.tuxdevelop.notification.system.demo.notifier.domain;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class FinancialDepartmentRequest extends CommonRequest {

	private String sourceSystem;
	private Double amount;
	private String employeeName;
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Contractual.Configuration;

namespace Contractual.MetaClient
{
    public class RestResourcesConfiguration : SerializeableConfigurationSection
    {
        public const string SectionName = "restResources";

        public override string ConfigSectionName { get { return SectionName; } }

        [ConfigurationProperty("", IsDefaultCollection = true)]
        [ConfigurationCollection(typeof(Host), AddItemName = "host")]
        public ConfigurationElementCollection<Host, RestResourcesConfiguration> Hosts
        {
            get
            {
                var collection = (ConfigurationElementCollection<Host, RestResourcesConfiguration>)base[""];
                collection.ParentElement = this;
                return collection;
            }
            //set { base[""] = value; }
        }

        [ConfigurationProperty("defaultAddress")]
        public string DefaultAddress
        {
            get { return (string)base["defaultAddress"]; }
            set { base["defaultAddress"] = value; }
        }

        [ConfigurationProperty("disableClientCertificates")]
        public bool DisableClientCertificates
        {
            get { return (bool)base["disableClientCertificates"]; }
            set { base["disableClientCertificates"] = value; }
        }
    }

    public class Host : ConfigurationElement<RestResourcesConfiguration>
    {
        [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
        public string Name
        {
            get { return (string)base["name"]; }
            set { base["name"] = value; }
        }

        [ConfigurationProperty("address", IsKey = true, IsRequired = true)]
        public string Address
        {
            get { return (string)base["address"]; }
            set { base["address"] = value; }
        }

        [ConfigurationProperty("certificate", IsKey = true, IsRequired = false)]
        public string Certificate
        {
            get
            {
                return Parent.DisableClientCertificates ? "" : (string)base["certificate"];
            }
            set { base["certificate"] = value; }
        }

        [ConfigurationProperty("flags", IsRequired = false)]
        public string Flags
        {
            get { return (string)base["flags"]; }
            set { base["flags"] = value; }
        }

        [ConfigurationProperty("jsonFormatter", IsRequired = false)]
        public string JsonFormatter
        {
            get { return (string)base["jsonFormatter"]; }
            set { base["jsonFormatter"] = value; }
        }

        /// <summary>
        /// A convenience flag tester used by DelegatingHandlers.
        /// </summary>
        /// <param name="flag">A keyword recognized by a DelegatingHandler</param>
        /// <returns></returns>
        public bool HasFlag(string flag)
        {
            return !String.IsNullOrWhiteSpace(Flags) && Flags.Split(',').Any(f => f == flag);
        }

        [ConfigurationProperty("", IsDefaultCollection = true)]
        [ConfigurationCollection(typeof(Resource), AddItemName = "resource")]
        public ConfigurationElementCollection<Resource> Mappings
        {
            get { return base[""] as ConfigurationElementCollection<Resource>; }
            //set { base[""] = value; }
        }

        public override bool IsReadOnly()
        {
            return false;
        }
    }

    public class Resource : ConfigurationElement
    {
        [ConfigurationProperty("map", IsKey = true, IsRequired = true)]
        public string Map
        {
            get { return (string)base["map"]; }
            //set { base["serialNum"] = value; }
        }
    }

}


text:
autoscaling = Aws::AutoScaling::Client.new

# stub Group
autoscaling.stub_responses(
  :describe_auto_scaling_groups,
  auto_scaling_groups: [{
    auto_scaling_group_name: 'test-group',
    created_time: Time.new,
    launch_configuration_name: 'test-config',
    min_size: 2,
    max_size: 4,
    desired_capacity: 2,
    default_cooldown: 300,
    availability_zones: ['us-east-1a', 'us-east-1b'],
    load_balancer_names: ['test-elb'],
    health_check_type: 'EC2',
    health_check_grace_period: 300,
    instances: [{
      instance_id: 'i-aabbccdd',
      availability_zone: 'us-east-1a',
      lifecycle_state: 'InService',
      health_status: 'Healthy',
      launch_configuration_name: 'test-config',
      protected_from_scale_in: false
    }],
    suspended_processes: [{
      process_name: 'AZRebalance',
      suspension_reason: 'User suspended at 2015-05-25T00:00:00Z'
    }],
    placement_group: 'test-placement-group',
    vpc_zone_identifier: 'subnet-aabbccdd,subnet-ddccbbaa',
    enabled_metrics: [{
      metric: 'GroupTotalInstances',
      granularity: '1Minute'
    }],
    status: nil,
    tags: [{
      resource_id: 'test-group',
      resource_type: 'auto-scaling-group',
      key: 'Name',
      value: 'test-group',
      propagate_at_launch: true
    }],
    termination_policies: %w[
      OldestLaunchConfiguration
      ClosestToNextInstanceHour
    ]
  }]
)

# stub Policies (which are exposed by Group anyway)
autoscaling.stub_responses(
  :describe_policies,
  scaling_policies: [
    {
      auto_scaling_group_name: 'test-group',
      policy_name: 'scale-on-high-cpu',
      scaling_adjustment: 2,
      adjustment_type: 'ChangeInCapacity',
      min_adjustment_step: 0,
      cooldown: 300,
      policy_arn: 'arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:'\
        'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:autoScalingGroupName/test-group:'\
        'policyName/scale-on-high-cpu',
      alarms: [{
        alarm_name: 'cpu-utilization',
        alarm_arn: 'arn:aws:cloudwatch:us-east-1:000000000000:alarm:'\
          'cpu-utilization'
      }]
    }
  ]
)

RSpec.describe group = AutoScaling::Group.new('test-group', autoscaling) do
  its(:to_s) { is_expected.to eq 'AutoScaling Group: test-group' }
  its(:launch_configuration) { is_expected.to eq 'test-config' }
  its(:min_size) { is_expected.to eq 2 }
  its(:max_size) { is_expected.to eq 4 }
  its(:desired_capacity) { is_expected.to eq 2 }
  its(:default_cooldown) { is_expected.to eq 300 }
  its(:availability_zones) { is_expected.to eq ['us-east-1a', 'us-east-1b'] }
  its(:load_balancer_names) { is_expected.to eq ['test-elb'] }
  its(:health_check_type) { is_expected.to eq 'EC2' }
  its(:health_check_grace_period) { is_expected.to eq 300 }

  # inconsistent with the above values, but the purpose is to do testing
  its(:instances) do
    instance = group.instances[0]
    expect(instance.instance_id).to eq 'i-aabbccdd'
    expect(instance.availability_zone).to eq 'us-east-1a'
    expect(instance.lifecycle_state).to eq 'InService'
    expect(instance.health_status).to eq 'Healthy'
    expect(instance.launch_configuration_name).to eq 'test-config'
  end

  its(:instance_count) { is_expected.to eq 1 }

  its(:suspended_processes) do
    sp = group.suspended_processes[0]
    expect(sp.process_name).to eq 'AZRebalance'
    expect(sp.suspension_reason).to eq 'User suspended at 2015-05-25T00:00:00Z'
  end

  its(:placement_group) { is_expected.to eq 'test-placement-group' }
  its(:vpc_subnets) { is_expected.to eq ['subnet-aabbccdd', 'subnet-ddccbbaa'] }

  its(:enabled_metrics) do
    em = group.enabled_metrics[0]
    expect(em.metric).to eq 'GroupTotalInstances'
    expect(em.granularity).to eq '1Minute'
  end

  its(:status) { is_expected.to eq nil }

  its(:tags) do
    tag = group.tags[0]
    expect(tag.resource_id).to eq 'test-group'
    expect(tag.resource_type).to eq 'auto-scaling-group'
    expect(tag.value).to eq 'test-group'
    expect(tag.propagate_at_launch).to eq true
  end

  its(:termination_policies) do
    is_expected.to eq %w[OldestLaunchConfiguration ClosestToNextInstanceHour]
  end

  its(:scaling_policies) do
    sp = group.scaling_policies[0]
    expect(sp.auto_scaling_group_name).to eq 'test-group'
    expect(sp.policy_name).to eq 'scale-on-high-cpu'
    expect(sp.scaling_adjustment).to eq 2
    expect(sp.adjustment_type).to eq 'ChangeInCapacity'
    expect(sp.cooldown).to eq 300
    expect(sp.policy_arn).to eq 'arn:aws:autoscaling:us-east-1:000000000000'\
      ':scalingPolicy:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee:'\
      'autoScalingGroupName/test-group:policyName/scale-on-high-cpu'
    expect(sp.min_adjustment_step).to eq 0

    alarm = sp.alarms[0]
    expect(alarm.alarm_name).to eq 'cpu-utilization'
    expect(alarm.alarm_arn).to eq 'arn:aws:cloudwatch:us-east-1:000000000000'\
      ':alarm:cpu-utilization'
  end
end


text:
var parse = require('../../lib/parser');

describe('parser', function() {
  it('parses arguments and params', function() {
    var program = {
      path: 'some/where',
      args: ['model', 'user', 'name:string']
    };
    parse(program);
    program.loom.should.eql({
      args: ['user'],
      name: 'model',
      paths: ['some/where'],
      params: { name: 'string' }
    });
  });
});


text:
CargarCarreras
==============

Cargar carreras de la web al servidor


text:
package org.apereo.cas.ticket;

import org.apereo.cas.authentication.Authentication;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.time.ZonedDateTime;
import java.util.Optional;

/**
 * Abstract implementation of a ticket that handles all ticket state for
 * policies. Also incorporates properties common among all tickets. As this is
 * an abstract class, it cannot be created. It is recommended that
 * implementations of the Ticket interface extend the AbstractTicket as it
 * handles common functionality amongst different ticket types (such as state
 * updating).
 * <p>
 * AbstractTicket does not provide a logger instance to
 * avoid instantiating many such Loggers at runtime (there will be many instances
 * of subclasses of AbstractTicket in a typical running CAS server).  Instead
 * subclasses should use static Logger instances.
 *
 * @author Scott Battaglia
 * @since 3.0.0
 */
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
@JsonIgnoreProperties(ignoreUnknown = true)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode(of = "id")
@Setter
@Slf4j
public abstract class AbstractTicket implements Ticket, TicketState {

    private static final long serialVersionUID = -8506442397878267555L;

    /**
     * The {@link ExpirationPolicy} this ticket is associated with.
     **/
    @Getter
    private ExpirationPolicy expirationPolicy;

    /**
     * The unique identifier for this ticket.
     */
    @Getter
    private String id;

    /**
     * The last time this ticket was used.
     */
    @Getter
    private ZonedDateTime lastTimeUsed;

    /**
     * The previous last time this ticket was used.
     */
    @Getter
    private ZonedDateTime previousTimeUsed;

    /**
     * The time the ticket was created.
     */
    @Getter
    private ZonedDateTime creationTime;

    /**
     * The number of times this was used.
     */
    @Getter
    private int countOfUses;

    /**
     * Flag to enforce manual expiration.
     */
    private Boolean expired = Boolean.FALSE;

    protected AbstractTicket(final String id, final ExpirationPolicy expirationPolicy) {
        this.id = id;
        this.creationTime = ZonedDateTime.now(expirationPolicy.getClock());
        this.lastTimeUsed = this.creationTime;
        this.expirationPolicy = expirationPolicy;
    }

    @Override
    public void update() {
        updateTicketState();
        updateTicketGrantingTicketState();
    }

    @Override
    public boolean isExpired() {
        return this.expirationPolicy.isExpired(this) || isExpiredInternal();
    }

    @Override
    public int compareTo(final Ticket o) {
        return getId().compareTo(o.getId());
    }

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

    @Override
    public Authentication getAuthentication() {
        val ticketGrantingTicket = getTicketGrantingTicket();
        return Optional.ofNullable(ticketGrantingTicket)
            .map(TicketGrantingTicket::getAuthentication)
            .orElse(null);
    }

    @Override
    public TicketGrantingTicket getTicketGrantingTicket() {
        return null;
    }

    @Override
    public void markTicketExpired() {
        this.expired = Boolean.TRUE;
    }

    /**
     * Update ticket granting ticket state.
     */
    protected void updateTicketGrantingTicketState() {
        val ticketGrantingTicket = getTicketGrantingTicket();
        if (ticketGrantingTicket != null && !ticketGrantingTicket.isExpired()) {
            val state = TicketState.class.cast(ticketGrantingTicket);
            state.update();
        }
    }

    /**
     * Update ticket state.
     */
    @SuppressWarnings("FromTemporalAccessor")
    protected void updateTicketState() {
        LOGGER.trace("Before updating ticket [{}]\n\tPrevious time used: [{}]\n\tLast time used: [{}]\n\tUsage count: [{}]",
            getId(), this.previousTimeUsed, this.lastTimeUsed, this.countOfUses);

        this.previousTimeUsed = ZonedDateTime.from(this.lastTimeUsed);
        this.lastTimeUsed = ZonedDateTime.now(this.expirationPolicy.getClock());
        this.countOfUses++;

        LOGGER.trace("After updating ticket [{}]\n\tPrevious time used: [{}]\n\tLast time used: [{}]\n\tUsage count: [{}]",
            getId(), this.previousTimeUsed, this.lastTimeUsed, this.countOfUses);
    }

    @JsonIgnore
    protected boolean isExpiredInternal() {
        return this.expired;
    }
}


text:
package concurrent

import (
	"github.com/dropbox/godropbox/container/lrucache"
	"sync"
)

// A thread-safe version of LRUCache
type LRUCache interface {
	// Retrieves multiple items from the cache
	GetMultiple(keys []string) []CacheResult
	// Retrieves a single item from the cache and whether it exists
	Get(key string) (v interface{}, found bool)
	// Sets a single item in the cache
	Set(key string, v interface{})
	// Sets multiple items in the cache
	SetMultiple(keyValues map[string]interface{})
	// Deletes one or more keys
	Delete(keys ...string)
	// Clears the cache
	Clear()
	// Retrieves the maximum size of the cache
	MaxSize() int
}

// Represents value in cache and whether it exists or not
type CacheResult struct {
	// Result value
	V interface{}
	// Indicates whether it exists in the cache or not
	Found bool
}

type concurrentLruCacheImp struct {
	cache *lrucache.LRUCache
	lock  sync.RWMutex
}

func NewLRUCache(size int) LRUCache {
	cache := lrucache.New(size)

	return &concurrentLruCacheImp{
		cache: cache,
	}
}

func (p *concurrentLruCacheImp) Get(key string) (v interface{}, found bool) {
	res := p.GetMultiple([]string{key})

	return res[0].V, res[0].Found
}

func (p *concurrentLruCacheImp) GetMultiple(keys []string) []CacheResult {
	p.lock.RLock()
	defer p.lock.RUnlock()

	res := make([]CacheResult, len(keys))

	for i, key := range keys {
		val, found := p.cache.Get(key)
		res[i].V = val
		res[i].Found = found
	}

	return res
}

func (p *concurrentLruCacheImp) Set(key string, value interface{}) {
	p.lock.Lock()
	defer p.lock.Unlock()

	p.cache.Set(key, value)
}

func (p *concurrentLruCacheImp) SetMultiple(keyValues map[string]interface{}) {
	p.lock.Lock()
	defer p.lock.Unlock()

	for key, value := range keyValues {
		p.cache.Set(key, value)
	}
}

func (p *concurrentLruCacheImp) Delete(keys ...string) {
	p.lock.Lock()
	defer p.lock.Unlock()

	for _, key := range keys {
		p.cache.Delete(key)
	}
}

func (p *concurrentLruCacheImp) Clear() {
	p.lock.Lock()
	defer p.lock.Unlock()

	// there is no way to clear the cache. So, just create a new one
	p.cache = lrucache.New(p.cache.MaxSize())
}

func (p *concurrentLruCacheImp) MaxSize() int {
	p.lock.RLock()
	defer p.lock.RUnlock()

	return p.cache.MaxSize()
}


text:
package exempluTemplate;

public class TestTemplate {

	public static void main(String[] args) {

		TestareNUnit nUnit = new TestareNUnit();
		TestareJUnit jUnit = new TestareJUnit();

		nUnit.testeaza();
		jUnit.testeaza();
	}

}


text:
package com.netflix.atlas.core.validation

import com.netflix.atlas.core.util.SmallHashMap
import com.typesafe.config.Config

/**
 * Verifies that the tags contain a specified key. Sample config:
 *
 * ```
 * key = name
 * ```
 */
class HasKeyRule(config: Config) extends Rule {
  private val key = config.getString("key")

  def validate(tags: SmallHashMap[String, String]): ValidationResult = {
    if (tags.contains(key)) ValidationResult.Pass else failure(s"missing '$key': ${tags.keys}")
  }
}


text:
package schema

import (
	"fmt"
	"sort"

	"github.com/cihangir/stringext"
)

// propertyOrderedKey attaches the methods of Interface, sorting in increasing order.
type propertyOrderedKey struct {
	key           string
	propertyOrder int
}

type propertyOrderedKeys []propertyOrderedKey

func (p propertyOrderedKeys) Len() int           { return len(p) }
func (p propertyOrderedKeys) Less(i, j int) bool { return p[i].propertyOrder < p[j].propertyOrder }
func (p propertyOrderedKeys) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

func (p propertyOrderedKeys) prependKeysTo(to []string) []string {
	newSlice := make([]string, 0)
	for _, k := range p {
		newSlice = append(newSlice, k.key)
	}

	return append(newSlice, to...)
}

// Required checks if the given n is a required property
func Required(n string, def *Schema) bool {
	return stringext.Contains(n, def.Required)
}

// SortedSchema sorts given map[string]Schema and returns a slice of Schema
// using SortedKeys function
func SortedSchema(m map[string]*Schema) []*Schema {
	keys := SortedKeys(m)
	ss := make([]*Schema, len(m))
	for i, k := range keys {
		ss[i] = m[k]
	}

	return ss
}

// SortedKeys sorts given schema map according to PropertyOrder property, 0
// valued properties are sort with strings.Sort
func SortedKeys(m map[string]*Schema) (keys []string) {
	unorderedKeys := make([]string, 0)
	orderedProperties := propertyOrderedKeys{}

	for key := range m {
		if m[key].PropertyOrder == 0 {
			unorderedKeys = append(unorderedKeys, key)
		} else {
			orderedProperties = append(orderedProperties, propertyOrderedKey{
				key:           key,
				propertyOrder: m[key].PropertyOrder,
			})
		}
	}

	// sort unordered keys first
	sort.Strings(unorderedKeys)

	// sort order given properties
	sort.Sort(orderedProperties)

	// conbine them
	return orderedProperties.prependKeysTo(unorderedKeys)
}

// Argumentize returns a string that can be used as an argument into a function
func Argumentize(s interface{}) string {
	switch s.(type) {
	case *Schema:
		sc := s.(*Schema)
		switch sc.Type {
		case arrayConst:
			if len(sc.Items) == 1 {
				switch sc.Items[0].Type {
				case objectConst:
					return fmt.Sprintf("[]*models.%s", sc.Items[0].Title)
				case numberConst:
					return fmt.Sprintf("[]%s", sc.Items[0].Format)
				case stringConst:
					return fmt.Sprintf("[]%s", stringConst)
				case booleanConst:
					return fmt.Sprintf("[]%s", "bool")
				default:
					panic(fmt.Sprintf("unsupported argumentize format: %+v", sc))
				}
			} else {
				return "[]interface{}"
			}
		case numberConst:
			return sc.Format
		case stringConst:
			return stringConst
		case booleanConst:
			return boolConst
		default:
			return fmt.Sprintf("models.%s", sc.Title)
		}
	case *bool:
		return "bool"
	case *int64:
		return "int64"
	}
	panic("unknown type") // todo return interface instead
}

const (
	arrayConst   = "array"
	booleanConst = "boolean"
	boolConst    = "bool"
	numberConst  = "number"
	objectConst  = "object"
	stringConst  = "string"
	integerConst = "integer"
	intConst     = "int"
)


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

import com.facebook.presto.SessionRepresentation;
import com.facebook.presto.execution.QueryInfo;
import com.facebook.presto.execution.QueryState;
import com.facebook.presto.spi.ErrorCode;
import com.facebook.presto.spi.ErrorType;
import com.facebook.presto.spi.PrestoWarning;
import com.facebook.presto.spi.QueryId;
import com.facebook.presto.spi.memory.MemoryPoolId;
import com.facebook.presto.spi.resourceGroups.QueryType;
import com.facebook.presto.spi.resourceGroups.ResourceGroupId;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;

import java.net.URI;
import java.util.List;
import java.util.Optional;

import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.Objects.requireNonNull;

/**
 * Lightweight version of QueryInfo. Parts of the web UI depend on the fields
 * being named consistently across these classes.
 */
@Immutable
public class BasicQueryInfo
{
    private final QueryId queryId;
    private final SessionRepresentation session;
    private final Optional<ResourceGroupId> resourceGroupId;
    private final QueryState state;
    private final MemoryPoolId memoryPool;
    private final boolean scheduled;
    private final URI self;
    private final String query;
    private final BasicQueryStats queryStats;
    private final ErrorType errorType;
    private final ErrorCode errorCode;
    private final Optional<QueryType> queryType;
    private final List<PrestoWarning> warnings;

    @JsonCreator
    public BasicQueryInfo(
            @JsonProperty("queryId") QueryId queryId,
            @JsonProperty("session") SessionRepresentation session,
            @JsonProperty("resourceGroupId") Optional<ResourceGroupId> resourceGroupId,
            @JsonProperty("state") QueryState state,
            @JsonProperty("memoryPool") MemoryPoolId memoryPool,
            @JsonProperty("scheduled") boolean scheduled,
            @JsonProperty("self") URI self,
            @JsonProperty("query") String query,
            @JsonProperty("queryStats") BasicQueryStats queryStats,
            @JsonProperty("errorType") ErrorType errorType,
            @JsonProperty("errorCode") ErrorCode errorCode,
            @JsonProperty("queryType") Optional<QueryType> queryType,
            @JsonProperty("warnings") List<PrestoWarning> warnings)
    {
        this.queryId = requireNonNull(queryId, "queryId is null");
        this.session = requireNonNull(session, "session is null");
        this.resourceGroupId = requireNonNull(resourceGroupId, "resourceGroupId is null");
        this.state = requireNonNull(state, "state is null");
        this.memoryPool = memoryPool;
        this.errorType = errorType;
        this.errorCode = errorCode;
        this.scheduled = scheduled;
        this.self = requireNonNull(self, "self is null");
        this.query = requireNonNull(query, "query is null");
        this.queryStats = requireNonNull(queryStats, "queryStats is null");
        this.queryType = requireNonNull(queryType, "queryType is null");
        this.warnings = requireNonNull(warnings, "warnings is null");
    }

    public BasicQueryInfo(QueryInfo queryInfo)
    {
        this(queryInfo.getQueryId(),
                queryInfo.getSession(),
                queryInfo.getResourceGroupId(),
                queryInfo.getState(),
                queryInfo.getMemoryPool(),
                queryInfo.isScheduled(),
                queryInfo.getSelf(),
                queryInfo.getQuery(),
                new BasicQueryStats(queryInfo.getQueryStats()),
                queryInfo.getErrorType(),
                queryInfo.getErrorCode(),
                queryInfo.getQueryType(),
                queryInfo.getWarnings());
    }

    @JsonProperty
    public QueryId getQueryId()
    {
        return queryId;
    }

    @JsonProperty
    public SessionRepresentation getSession()
    {
        return session;
    }

    @JsonProperty
    public Optional<ResourceGroupId> getResourceGroupId()
    {
        return resourceGroupId;
    }

    @JsonProperty
    public QueryState getState()
    {
        return state;
    }

    @JsonProperty
    public MemoryPoolId getMemoryPool()
    {
        return memoryPool;
    }

    @JsonProperty
    public boolean isScheduled()
    {
        return scheduled;
    }

    @JsonProperty
    public URI getSelf()
    {
        return self;
    }

    @JsonProperty
    public String getQuery()
    {
        return query;
    }

    @JsonProperty
    public BasicQueryStats getQueryStats()
    {
        return queryStats;
    }

    @Nullable
    @JsonProperty
    public ErrorType getErrorType()
    {
        return errorType;
    }

    @Nullable
    @JsonProperty
    public ErrorCode getErrorCode()
    {
        return errorCode;
    }

    @JsonProperty
    public Optional<QueryType> getQueryType()
    {
        return queryType;
    }

    @JsonProperty
    public List<PrestoWarning> getWarnings()
    {
        return warnings;
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .add("queryId", queryId)
                .add("state", state)
                .toString();
    }
}


text:
var webpack = require('webpack')
var config = require('./webpack.prod.conf.js')
var chalk = require('chalk')
var ora = require('ora')

var spinner = ora('building for production...')
spinner.start()

webpack(config, function (err, stats) {
  spinner.stop()
  if (err) throw err
  process.stdout.write(stats.toString({
    colors: true,
    modules: false,
    children: false,
    chunks: false,
    chunkModules: false
  }) + '\n\n')

  console.log(chalk.cyan('  Build complete.\n'))
  console.log(chalk.yellow(
    '  Tip: built files are meant to be served over an HTTP server.\n' +
    '  Opening index.html over file:// won\'t work.\n'
  ))
})


text:
package sec.geo.shape;

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

import sec.geo.GeoPoint;

public abstract class APath extends AExtrusion {
	protected final List<GeoPoint> points;

	public APath() {
		points = new ArrayList<GeoPoint>();
	}

	public void addPoint(GeoPoint point) {
		points.add(point);
		shapeChanged();
	}

	public void addPoints(List<GeoPoint> points) {
		this.points.addAll(points);
		shapeChanged();
	}
}


text:
import ws from "ws";
import assert from "assert";
import ARIWebSocket from "../../src/events/ARIWebSocket";
const WebSocketServer = ws.Server;

describe("ARIWebSocket", () => {
  let ws;
  let server;

  beforeEach(() => {
    server = new WebSocketServer({ port: 8088 });
  });

  afterEach(() => {
    // important to close client first so it does not try
    // to reconnect and cause issues in subsequent tests
    if (ws) ws.close();
    server.close();
  });

  it('passes non-"message" events along without parsing', (done) => {
    ws = new ARIWebSocket({ url: "ws://localhost:8088" });

    ws.once("open", () => {
      ws.once("bugaboo", (message) => {
        assert.strictEqual(message, "bugaloo");
        done();
      });

      ws.emit("bugaboo", "bugaloo");
    });
  });

  it('passes "message" events without a payload along without parsing', (done) => {
    ws = new ARIWebSocket({ url: "ws://localhost:8088" });

    server.once("connection", (conn) => {
      ws.on("message", (message) => {
        assert.deepEqual(message, new Uint8Array(0));
        done();
      });

      conn.send();
    });
  });

  it('passes "message" events that are not string along without parsing', (done) => {
    ws = new ARIWebSocket({ url: "ws://localhost:8088" });
    const buf = Buffer.from("string");

    server.once("connection", (conn) => {
      ws.once("message", (message) => {
        assert.strictEqual(message.toString("utf-8"), buf.toString("utf-8"));
        done();
      });

      conn.send(buf);
    });
  });

  it('passes string "message" events that cannot be parsed as JSON along as-is', (done) => {
    ws = new ARIWebSocket({ url: "ws://localhost:8088" });

    server.once("connection", (conn) => {
      ws.once("message", (message) => {
        assert.strictEqual(message, "hidey ho");
        done();
      });

      conn.send("hidey ho");
    });
  });

  it('parses JSON "message" payloads before triggering the event', (done) => {
    ws = new ARIWebSocket({ url: "ws://localhost:8088" });

    server.once("connection", (conn) => {
      ws.once("message", (message) => {
        assert.deepEqual(message, { foo: "bar" });
        done();
      });

      conn.send('{"foo": "bar"}');
    });
  });
});


text:
@class ZLPhotoPickerGroup;

@interface ZLPhotoPickerAssetsViewController : UIViewController

@property (weak , nonatomic) ZLPhotoPickerGroupViewController *groupVc;
@property (nonatomic , assign) PickerViewShowStatus status;
@property (nonatomic , strong) ZLPhotoPickerGroup *assetsGroup;
@property (nonatomic , assign) NSInteger maxCount;
// 需要记录选中的值的数据
@property (strong,nonatomic) NSArray *selectPickerAssets;
// 置顶展示图片
@property (assign,nonatomic) BOOL topShowPhotoPicker;
// 是否显示Camera
@property (assign,nonatomic) BOOL isShowCamera;
@end


text:
set -e
dbname='tsadmdevdb'
dbversion=$(echo 'SELECT `dbversion` FROM `tsadm`;' | mysql -BN ${dbname})
echo "dbversion ${dbversion}"
for upversion in $(ls upgrade/ | cut -d'.' -f1 | sort -u)
do
    if test ${dbversion} -lt ${upversion}
    then
        echo -n "upgrade to ${upversion}, using "
        if test -s upgrade/${upversion}.bash
        then
            echo -n "bash"
            bash upgrade/${upversion}.bash | mysql -BN ${dbname}
        elif test -s upgrade/${upversion}.sql
        then
            echo -n "sql"
            mysql -BN ${dbname} <upgrade/${upversion}.sql
        fi
        echo " done!"
    fi
done


text:
function [samples, stats] = probitSampleWinbugs(X, y, Sigma, Nsamples, mu, useLogistic)
% Draw samples from beta ~ p(beta|X,y)
% where p(beta) = N(beta,mu,Sigma)
% and p(y|X(i,:)=x, beta) = Bernoulli(Phi(beta'*x))
% where Phi is the cumulative Gaussian.
% If logistic=1, we use logit instead.
% We use Winbugs.
% Probit does not work well - often the chains don't mix.

[n p] = size(X);
if nargin < 5,  mu = zeros(p,1); end
if nargin < 6, useLogistic = 0;  end

dataStruct = struct('p', p, 'n', n, 'X', X, 'y', y, ...
                   'mu', mu, 'precMat', inv(Sigma));

Nchains = 5;

% we initialize the params randomly - probably a bad idea
clear initStructs
for i=1:Nchains
  %S.beta = mvnrnd(mu, Sigma);
  S.beta = mvnrnd(mu, eye(p));
  initStructs(i) = S;
end

if useLogistic
  fname = which('logitRegressionModel.txt');
else
  fname = which('probitRegressionModel.txt');
end

[samples, stats] = matbugs(dataStruct, fname, ...
		'init', initStructs, ...
		'view', 1, 'nburnin', 10000, 'nsamples', Nsamples, ...
		'thin', 1, 'nChains', Nchains, ...
		'monitorParams', {'beta'}, ...
		'Bugdir', 'C:/Program Files/WinBUGS14');

end


text:
package org.apache.hadoop.hbase.client;

import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;

/**
 * Enum describing the durability guarantees for tables and {@link Mutation}s
 * Note that the items must be sorted in order of increasing durability
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public enum Durability {
  /* Developer note: Do not rename the enum field names. They are serialized in HTableDescriptor */
  /**
   * If this is for tables durability, use HBase's global default value (SYNC_WAL).
   * Otherwise, if this is for mutation, use the table's default setting to determine durability.
   * This must remain the first option.
   */
  USE_DEFAULT,
  /**
   * Do not write the Mutation to the WAL
   */
  SKIP_WAL,
  /**
   * Write the Mutation to the WAL asynchronously
   */
  ASYNC_WAL,
  /**
   * Write the Mutation to the WAL synchronously.
   * The data is flushed to the filesystem implementation, but not necessarily to disk.
   * For HDFS this will flush the data to the designated number of DataNodes.
   * See HADOOP-6313
   */
  SYNC_WAL,
  /**
   * Write the Mutation to the WAL synchronously and force the entries to disk.
   * (Note: this is currently not supported and will behave identical to {@link #SYNC_WAL})
   * See HADOOP-6313
   */
  FSYNC_WAL
}


text:
/* globals module */
/**
 * @module baasicArticleSettingsService
 * @description Baasic Article Settings Service provides an easy way to consume Baasic Article Settings REST API end-points. In order to obtain needed routes `baasicArticleSettingsService` uses `baasicArticleSettingsRouteService`.
*/
(function (angular, module, undefined) {
    'use strict';
    module.service('baasicArticleSettingsService', ['baasicApiHttp', 'baasicApiService', 'baasicConstants', 'baasicArticleSettingsRouteService',
        function (baasicApiHttp, baasicApiService, baasicConstants, articleSettingsRouteService) {
            return {
                 /**
                 * Returns a promise that is resolved once the get action has been performed. Success response returns the article settings.
                 * @method
                 * @example
baasicArticleSettingsService.get()
.success(function (data) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
                **/
                get: function (options) {
                    return baasicApiHttp.get(articleSettingsRouteService.get.expand(baasicApiService.getParams(options)));
                },
                 /**
                 * Returns a promise that is resolved once the update article settings action has been performed; this action updates article settings. This route uses HAL enabled objects to obtain routes and therefore it doesn't apply `baasicArticleSettingsRouteService` route template. Here is an example of how a route can be obtained from HAL enabled objects:
```
var params = baasicApiService.removeParams(articleSettings);
var uri = params['model'].links('put').href;
```
                 * @method
                 * @example
// articleSettings is a resource previously fetched using get action.
articleSettings.allowArchive = true;
baasicArticleSettingsService.update(articleSettings)
.success(function (data) {
  // perform success action here
})
.error(function (response, status, headers, config) {
  // perform error handling here
});
				**/
                update: function (data) {
                    var params = baasicApiService.updateParams(data);
                    return baasicApiHttp.put(params[baasicConstants.modelPropertyName].links('put').href, params[baasicConstants.modelPropertyName]);
                },
                /**
                * Provides direct access to `baasicArticleSettingsRouteService`.
                * @method
                * @example baasicArticleSettingsService.routeService.get.expand(expandObject);
                **/
                routeService: articleSettingsRouteService
            };
        }]);
}(angular, module));
/**
 * @copyright (c) 2017 Mono Ltd
 * @license MIT
 * @author Mono Ltd
 * @overview
 ***Notes:**
 - Refer to the [Baasic REST API](http://dev.baasic.com/api/reference/home) for detailed information about available Baasic REST API end-points.
 - All end-point objects are transformed by the associated route service.
*/


text:
            <button class="btn btn-primary" (click)="onAddMessage()">Message</button>

                    {{message.content}}
                    <input [(ngModel)]="message.content" placeholder="name">

My id - {{mypeerid}}

            <input type="text" [(ngModel)]="anotherid">
            <button (click)="connect()">Connect</button>
            <button (click)="videoconnect()">VideoChat</button>
            <video #myvideo></video>


text:
require "spec_helper"
require 'active_record_test'

require "#{File.dirname(__FILE__)}/autoload"

Estate = DuePayments::Estate

RSpec.describe "Estates database" do

  before :all do
    DuePayments::Core.silence_stdout { start_by_initiatng_database }
    puts "Database created and loaded ..."
  end

  context "Creation" do
    context "create_object method" do
      it "create_object method create new instance DuePayment::Estate" do
        result = Estate.create_object
        expect(result).not_to be_nil
        expect(result).to be_instance_of(DuePayments::Estate)
      end

      it "create_object method set default values" do

        result = Estate.create_object

        expect(result.name).not_to be_nil
        expect(result.price_per_acre).not_to be_nil
        expect(result.landlord_id).not_to be_nil
        expect(result.acre).not_to be_nil
        expect(result.zip_code).not_to be_nil
        expect(result.address).not_to be_nil
        expect(result.geolocalisation).not_to be_nil
        expect(result.coordinate_points).not_to be_nil
        expect(result.description).not_to be_nil
        expect(result.total_price).not_to be_nil

        expect(result.name).to be_instance_of(String)
        expect(result.price_per_acre).to be_instance_of(BigDecimal)
        expect(result.landlord_id).to be_instance_of(Fixnum)
        expect(result.acre).to be_instance_of(Fixnum)
        expect(result.zip_code).to be_instance_of(String)
        expect(result.address).to be_instance_of(String)
        expect(result.geolocalisation).to be_instance_of(String)
        expect(result.coordinate_points).to be_instance_of(String)
        expect(result.description).to be_instance_of(String)
        expect(result.total_price).to be_instance_of(BigDecimal)

      end
    end

    context "create method" do
      it "create method returns a DuePayment::Estate" do
        #TODO : finish this method
      end

      it "create method create a data on the database" do
        #TODO : finish this method
      end
    end

  end

  after :all do
    finish_by_delete_database
    puts "Database deleted ..."
  end

end


text: Codes, scripts and everything else for CS838 big data final project


text:
package org.jboss.weld.tests.interceptors.weld459.fccl;

@FooBinding
public final class FinalClassClassLevelMissile {
    public void fire() {
    }
}


text:
import sbt.Keys._
import sbt._

import sbtrelease.{ ReleaseStateTransformations, Version }

object Release {
  import sbtrelease.ReleasePlugin.autoImport._

  private val gitRemote = "origin"

  private def createLocalBranch(f: (String, String) => String) = Def.setting {
    val vcs = releaseVcs.value.get
    val ver = version.value
    val next = Version(_: String).map(_.withoutQualifier.string).getOrElse(???)
    val releaseBranch = f(ver, next(ver))

    ReleaseStep(action = { st =>
      if ((vcs.cmd("checkout", "-b", releaseBranch) ! st.log) == 0) {
        vcs.cmd("push", "-u", gitRemote, releaseBranch) !! st.log
        // Need to push for the plugin checks
      }

      st
    })
  }

  // Create a local `release/$releaseVer` branch
  private val createReleaseBranch =
    createLocalBranch { (_, ver) => s"release/$ver" }

  // Create a local `bump/$releaseVer` branch
  private val createBumpBranch = createLocalBranch { (_, ver) => s"bump/$ver" }

  private val pushCurrentBranch = Def.setting {
    val vcs = releaseVcs.value.get

    ReleaseStep(action = { st =>
      vcs.cmd("push", gitRemote, vcs.currentBranch) !! st.log

      st
    })
  }

  // 1. Prepare the release the SNAPSHOT from develop to master, with a branch
  private val releaseMaster = Def.setting {
    Seq[ReleaseStep](
      createReleaseBranch.value, // Create a release branch
      ReleaseStateTransformations.checkSnapshotDependencies,
      ReleaseStateTransformations.inquireVersions,
      ReleaseStateTransformations.setReleaseVersion,
      ReleaseStateTransformations.commitNextVersion,
      pushCurrentBranch.value
    )
  }

  // No tracking branch is set up -> set upstream

  // 2. Validate the pushed release branch with CI
  // 3. Merge the branch on master
  // 4. Add a tag

  // 5. Prepare the coming release
  private val bumpMaster = Def.setting {
    Seq[ReleaseStep](
      createBumpBranch.value, // Create a bump branch
      ReleaseStateTransformations.checkSnapshotDependencies,
      ReleaseStateTransformations.inquireVersions,
      ReleaseStateTransformations.setNextVersion,
      ReleaseStateTransformations.commitNextVersion,
      pushCurrentBranch.value
    )
  }

  val major = Def.setting[String] {
    Version(version.value) match {
      case Some(Version(maj, Seq(min, _), _)) => s"${maj}.${min}"
      case _ => sys.error(s"Invalid version: ${version.value}")
    }
  }

  val settings = Seq(
    releaseVersion := { ver =>
      Version(ver)
        .map(_.withoutQualifier.string)
        .getOrElse(sbtrelease.versionFormatError(ver))
    },
    releaseNextVersion := { ver =>
      // e.g. 1.2 => 1.3-SNAPSHOT
      Version(ver)
        .map(_.bumpBugfix.asSnapshot.string)
        .getOrElse(sbtrelease.versionFormatError(ver))
    },
    releaseCommitMessage := {
      val ver = (ThisBuild / version).value

      if (ver endsWith "-SNAPSHOT") {
        // Prepare the release the SNAPSHOT from master, with a release branch
        s"Bump $ver"
      } else {
        // Bump for the next coming sprint, on develop
        s"Release to $ver"
      }
    },
    releaseProcess := {
      if (version.value endsWith "-SNAPSHOT") releaseMaster.value
      else bumpMaster.value
    }
  )
}