text:
// Copyright 2016, 2015, 2014 Matthias Koch
//
// 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.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;

namespace TestFx.Utilities.Collections
{
  public static partial class EnumerableExtensions
  {
    [DebuggerNonUserCode]
    [DebuggerStepThrough]
    [DebuggerHidden]
    public static IDictionary<TKey, TValue> ToDictionary<T, TKey, TValue> (
        this IEnumerable<T> enumerable,
        [InstantHandle] Func<T, TKey> keySelector,
        [InstantHandle] Func<T, TValue> valueSelector,
        IEqualityComparer<TKey> comparer = null,
        Func<ArgumentException, TKey, Exception> exceptionFactory = null)
    {
      var list = enumerable.ToList();
      var dictionary = new Dictionary<TKey, TValue>(list.Count, comparer);

      foreach (var item in list)
      {
        var key = keySelector(item);
        try
        {
          dictionary.Add(key, valueSelector(item));
        }
        catch (ArgumentException exception)
        {
          exceptionFactory = exceptionFactory ?? ((ex, k) => ex);
          throw exceptionFactory(exception, key);
        }
      }

      return dictionary;
    }
  }
}


text:
/* SPDX-License-Identifier: BSD-3-Clause */

#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

#include "log.h"
#include "tpm2.h"
#include "tpm2_capability.h"

#define APPEND_CAPABILITY_INFORMATION(capability, field, subfield, max_count) \
    if (fetched_data->data.capability.count > max_count - property_count) { \
        fetched_data->data.capability.count = max_count - property_count; \
    } \
\
    memmove(&(*capability_data)->data.capability.field[property_count], \
            fetched_data->data.capability.field, \
            fetched_data->data.capability.count * sizeof(fetched_data->data.capability.field[0])); \
    property_count += fetched_data->data.capability.count; \
\
    (*capability_data)->data.capability.count = property_count; \
\
    if (more_data && property_count < count && fetched_data->data.capability.count) { \
        property = (*capability_data)->data.capability.field[property_count - 1]subfield + 1; \
    } else { \
        more_data = false; \
    }

tool_rc tpm2_capability_get(ESYS_CONTEXT *ectx, TPM2_CAP capability,
        UINT32 property, UINT32 count, TPMS_CAPABILITY_DATA **capability_data) {

    TPMI_YES_NO more_data;
    UINT32 property_count = 0;
    *capability_data = NULL;

    do {

        /* fetch capability info */
        TPMS_CAPABILITY_DATA *fetched_data = NULL;
        tool_rc rc = tpm2_get_capability(ectx, ESYS_TR_NONE, ESYS_TR_NONE,
                ESYS_TR_NONE, capability, property, count - property_count,
                &more_data, &fetched_data);
        LOG_INFO("GetCapability: capability: 0x%x, property: 0x%x", capability,
                property);

        if (rc != tool_rc_success) {
            if (*capability_data) {
                free(*capability_data);
                *capability_data = NULL;
            }
            return rc;
        }

        if (fetched_data->capability != capability) {
            LOG_ERR("TPM returned different capability than requested: 0x%x != "
                    "0x%x", fetched_data->capability, capability);
            free(fetched_data);
            if (*capability_data) {
                free(*capability_data);
                *capability_data = NULL;
            }
            return tool_rc_general_error;
        }

        if (*capability_data == NULL) {
            /* reuse the TPM's result structure */
            *capability_data = fetched_data;

            if (!more_data) {
                /* there won't be another iteration of the loop, just return the result unmodified */
                return tool_rc_success;
            }
        }

        /* append the TPM's results to the initial structure, as long as there is still space left */
        switch (capability) {
        case TPM2_CAP_ALGS:
            APPEND_CAPABILITY_INFORMATION(algorithms, algProperties, .alg,
                    TPM2_MAX_CAP_ALGS);
            break;
        case TPM2_CAP_HANDLES:
            APPEND_CAPABILITY_INFORMATION(handles, handle,,
                    TPM2_MAX_CAP_HANDLES);
            break;
        case TPM2_CAP_COMMANDS:
            APPEND_CAPABILITY_INFORMATION(command, commandAttributes,,
                    TPM2_MAX_CAP_CC);
            /* workaround because tpm2-tss does not implement attribute commandIndex for TPMA_CC */
            property &= TPMA_CC_COMMANDINDEX_MASK;
            break;
        case TPM2_CAP_PP_COMMANDS:
            APPEND_CAPABILITY_INFORMATION(ppCommands, commandCodes,,
                    TPM2_MAX_CAP_CC);
            break;
        case TPM2_CAP_AUDIT_COMMANDS:
            APPEND_CAPABILITY_INFORMATION(auditCommands, commandCodes,,
                    TPM2_MAX_CAP_CC);
            break;
        case TPM2_CAP_PCRS:
            APPEND_CAPABILITY_INFORMATION(assignedPCR, pcrSelections, .hash,
                    TPM2_NUM_PCR_BANKS);
            break;
        case TPM2_CAP_TPM_PROPERTIES:
            APPEND_CAPABILITY_INFORMATION(tpmProperties, tpmProperty, .property,
                    TPM2_MAX_TPM_PROPERTIES);
            break;
        case TPM2_CAP_PCR_PROPERTIES:
            APPEND_CAPABILITY_INFORMATION(pcrProperties, pcrProperty, .tag,
                    TPM2_MAX_PCR_PROPERTIES);
            break;
        case TPM2_CAP_ECC_CURVES:
            APPEND_CAPABILITY_INFORMATION(eccCurves, eccCurves,,
                    TPM2_MAX_ECC_CURVES);
            break;
        case TPM2_CAP_VENDOR_PROPERTY:
            APPEND_CAPABILITY_INFORMATION(intelPttProperty, property,,
                    TPM2_MAX_PTT_PROPERTIES);
            break;
        default:
            LOG_ERR("Unsupported capability: 0x%x\n", capability);
            if (fetched_data != *capability_data) {
                free(fetched_data);
            }
            free(*capability_data);
            *capability_data = NULL;
            return tool_rc_general_error;
        }

        if (fetched_data != *capability_data) {
            free(fetched_data);
        }
    } while (more_data);

    return tool_rc_success;
}

tool_rc tpm2_capability_find_vacant_persistent_handle(ESYS_CONTEXT *ctx,
        bool is_platform, TPMI_DH_PERSISTENT *vacant) {

    TPMS_CAPABILITY_DATA *capability_data;
    bool handle_found = false;
    tool_rc rc = tpm2_capability_get(ctx, TPM2_CAP_HANDLES,
            TPM2_PERSISTENT_FIRST, TPM2_MAX_CAP_HANDLES, &capability_data);
    if (rc != tool_rc_success) {
        return rc;
    }

    UINT32 count = capability_data->data.handles.count;
    if (count == 0) {
        /* There aren't any persistent handles, so use the first */
        *vacant = is_platform ? TPM2_PLATFORM_PERSISTENT : TPM2_PERSISTENT_FIRST;
        handle_found = true;
    } else if (count == TPM2_MAX_CAP_HANDLES) {
        /* All persistent handles are already in use */
        goto out;
    } else if (count < TPM2_MAX_CAP_HANDLES) {
        /*
         * iterate over used handles to ensure we're selecting
         * the next available handle.
         *
         * Platform handles start at a higher hange
         */
        UINT32 i;
        for (i = is_platform ? TPM2_PLATFORM_PERSISTENT : TPM2_PERSISTENT_FIRST;
                i <= (UINT32) TPM2_PERSISTENT_LAST; ++i) {
            bool inuse = false;
            UINT32 c;
            for (c = 0; c < count; ++c) {
                if (capability_data->data.handles.handle[c] == i) {
                    inuse = true;
                    break;
                }
            }

            if (!is_platform && i >= TPM2_PLATFORM_PERSISTENT) {
                break;
            }

            if (!inuse) {
                *vacant = i;
                handle_found = true;
                break;
            }
        }
    }

out:
    free(capability_data);
    return handle_found ? tool_rc_success : tool_rc_general_error;
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Juno\Controller;

use Config\Helper\Utils;
use Config\Library\CommonController;
use Config\Service\User as UserService;
use Config\Mapper\User as UserMapper;
use Config\Mapper\RelUserPermission as RelUserPermissionMapper;
use Config\Entity\User as UserEntity;
use Config\Entity\RelUserPermission as RelUserPermissionEntity;
use Juno\Form\User as UserForm;
use Zend\Http\Request;
use Zend\View\Model\ViewModel;

class UserController extends CommonController {
	public function init() {
		/**
		 * @todo: security checks
		 */
	}

    public function indexAction() {
	    /**
	     * @var UserService $service
	     */
	    $service = $this->getServiceLocator()->get('UserService');
	    $result = $service->getCompanyUsers($this->getCompanyId());

	    return new ViewModel([
		    'data' => $result,
	    ]);
    }

	public function addAction() {
		/**
		 * @var Request $request
		 * @var UserMapper $mapper
		 * @var RelUserPermissionMapper $permissionMapper
		 * @var UserEntity|bool $result
		 */
		$request = $this->getRequest();

		$mapper = $this->getServiceLocator()->get('UserMapper');
		$permissionMapper = $this->getServiceLocator()->get('RelUserPermissionMapper');

		$form = new UserForm($this->getServiceLocator(), $this->url()->fromRoute('user/add'));
		$form->prepare();

		if ($request->isPost()) {
			$form->setData($request->getPost());

			if ($form->isValid()) {
				$entity = new UserEntity();
				$entity->setName($request->getPost('name'));
				$entity->setEmail($request->getPost('email'));
				$entity->setLogin($request->getPost('login'));
				$entity->setCompanyId($this->getCompanyId());
				$entity->setIsPrimary(0);
				$entity->setPassword(
					Utils::generateHash($request->getPost('password'))
				);

				$mapper->beginTransaction();

				try {
					$mapper->insert($entity);
					$userId = $mapper->lastInsertValue;

					// Manage permissions
					$permissionMapper->delete(['user_id' => $userId]);

					if (count($request->getPost('permission'))) {
						$permissionEntity = new RelUserPermissionEntity();

						foreach ($request->getPost('permission') as $role) {
							$permissionEntity->setPermissionId($role);
							$permissionEntity->setUserId($userId);
							$permissionMapper->insert($permissionEntity);
						}
					}

					$mapper->commit();
					$this->flashMessenger()->addSuccessMessage('User successfully added!');
					$this->redirect()->toRoute('user/manage', ['id' => $userId]);
					return $this->getResponse();
				} catch (\Exception $ex) {
					$mapper->rollback();
					$this->flashMessenger()->addErrorMessage('Something went wrong. Please try again later!');
				}
			} else {
				$this->flashMessenger()->addErrorMessage('Form is not valid!');
				$form->populateValues($request->getPost());
			}

			$this->redirect()->toRoute('user/add');
		}

		return new ViewModel([
			'form' => $form,
			'error' => isset($error) ? $error : false,
		]);
	}

	public function manageAction() {
		/**
		 * @var Request $request
		 * @var UserMapper $mapper
		 * @var RelUserPermissionMapper $permissionMapper
		 * @var UserEntity|bool $result
		 */
		$request = $this->getRequest();
		$userId = $this->params()->fromRoute('id');

		$mapper = $this->getServiceLocator()->get('UserMapper');
		$permissionMapper = $this->getServiceLocator()->get('RelUserPermissionMapper');
		$result = $mapper->fetchOne([
			'id' => $userId,
		]);
		$permissionResult = $permissionMapper->fetchAll([
			'user_id' => $userId,
		]);

		$form = new UserForm($this->getServiceLocator(), $this->url()->fromRoute('user/manage', [
			'id' => $userId,
		]));
		$form->prepare();

		if ($request->isPost()) {
			$form->setData($request->getPost());

			if ($form->isValid()) {
				$entity = new UserEntity();
				$entity->setName($request->getPost('name'));
				$entity->setEmail($request->getPost('email'));
				$entity->setLogin($request->getPost('login'));

				$password = $request->getPost('password');
				if (!empty($password)) {
					$entity->setPassword(
						Utils::generateHash($request->getPost('password'))
					);
				}

				$mapper->beginTransaction();

				try {
					$mapper->update($entity, ['id' => $userId]);

					// Manage permissions
					$permissionMapper->delete(['user_id' => $userId]);

					if (count($request->getPost('permission'))) {
						$permissionEntity = new RelUserPermissionEntity();

						foreach ($request->getPost('permission') as $role) {
							$permissionEntity->setPermissionId($role);
							$permissionEntity->setUserId($userId);
							$permissionMapper->insert($permissionEntity);
						}
					}

					$mapper->commit();
					$this->flashMessenger()->addSuccessMessage($request->getPost('name') . ' has been successfully modified!');
				} catch (\Exception $ex) {
					$mapper->rollback();
					$this->flashMessenger()->addErrorMessage('Something went wrong. Please try again later!');
				}

			} else {
				$this->flashMessenger()->addErrorMessage('Form is not valid!');
				$form->populateValues($request->getPost());
			}

			$this->redirect()->toRoute('user/manage', ['id' => $userId]);
		} else {
			// Hide sensitive data
			$result->setPassword('');

			$form->populateValues(
				array_merge_recursive(
					$result->exchangeArray(), [
						'permission' => array_map(function($item) {
							return $item['permission_id'];
						}, $permissionResult->toArray())
					]
				)
			);
		}

		return new ViewModel([
			'form' => $form,
			'id' => $userId,
			'isPrimaryUser' => $result->getIsPrimary(),
		]);
	}

	public function suspendAction() {
		/**
		 * @var UserMapper $mapper
		 */
		$mapper = $this->getServiceLocator()->get('UserMapper');
		$entity = new UserEntity();
		$entity->setIsActive(0);

		try {
			$mapper->update($entity, ['id' => $this->params()->fromRoute('id')]);

			$this->flashMessenger()->addSuccessMessage('User has been successfully suspended!');
		} catch (\Exception $ex) {
			$this->flashMessenger()->addErrorMessage('Something went wrong. Please try again later!');
		}

		$this->redirect()->toRoute('user');

		return new ViewModel([
			'id' => $this->params()->fromRoute('id'),
		]);
	}

	public function activateAction() {
		/**
		 * @var UserMapper $mapper
		 */
		$mapper = $this->getServiceLocator()->get('UserMapper');
		$entity = new UserEntity();
		$entity->setIsActive(1);

		try {
			$mapper->update($entity, ['id' => $this->params()->fromRoute('id')]);

			$this->flashMessenger()->addSuccessMessage('User has been successfully activated!');
		} catch (\Exception $ex) {
			$this->flashMessenger()->addErrorMessage('Something went wrong. Please try again later!');
		}

		$this->redirect()->toRoute('user');

		return new ViewModel([
			'id' => $this->params()->fromRoute('id'),
		]);
	}

	public function deleteAction() {
		/**
		 * @var UserMapper $mapper
		 * @var RelUserPermissionMapper $permissionMapper
		 */
		$mapper = $this->getServiceLocator()->get('UserMapper');
		$permissionMapper = $this->getServiceLocator()->get('RelUserPermissionMapper');
		$entity = new UserEntity();
		$entity->setIsRemoved(1);

		$mapper->beginTransaction();

		try {
			$mapper->update($entity, ['id' => $this->params()->fromRoute('id')]);
			$permissionMapper->delete(['user_id' => $this->params()->fromRoute('id')]);
			$mapper->commit();

			$this->flashMessenger()->addSuccessMessage('User has been successfully removed!');
		} catch (\Exception $ex) {
			$mapper->rollback();
			$this->flashMessenger()->addErrorMessage('Something went wrong. Please try again later!');
		}

		$this->redirect()->toRoute('user');

		return new ViewModel([
			'id' => $this->params()->fromRoute('id'),
		]);
	}
}


text:
import { IterableX } from '../../iterable/iterablex';
import { onErrorResumeNext as onErrorResumeNextStatic } from '../../iterable/onerrorresumenext';

/** @nocollapse */
IterableX.onErrorResumeNext = onErrorResumeNextStatic;

declare module '../../iterable/iterablex' {
  // eslint-disable-next-line no-shadow
  namespace IterableX {
    export let onErrorResumeNext: typeof onErrorResumeNextStatic;
  }
}


text:
<?php

namespace DCS\LikeBundle\Model;

interface ThreadManagerInterface
{
    /**
     * Returns the thread fully qualified class name
     *
     * @return string
     */
    public function getClass();

    /**
     * Create new thread instance
     *
     * @param mixed $id
     * @return ThreadInterface
     */
    public function create($id = null);

    /**
     * Save a thread
     *
     * @param ThreadInterface $thread
     * @return void
     */
    public function save(ThreadInterface $thread);

    /**
     * Update a thread
     *
     * @param ThreadInterface $thread
     * @return void
     */
    public function patch(ThreadInterface $thread);

    /**
     * Finds one thread by id
     *
     * @param mixed $id
     * @return ThreadInterface|null
     */
    public function findOneById($id);

    /**
     * Finds one thread by the given criteria
     *
     * @param array $criteria
     * @return ThreadInterface|null
     */
    public function findOneBy(array $criteria);
}


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

{% block main-container %}

    {% if request.user.is_authenticated %}

                {% block controller-content %}{% endblock %}

    {% else %}

    {% endif %}
{% endblock %}

{% block js-onpage %}
{{block.super}}
// Configure the current user
var app = angular.module('cloudfuzzy.api');

app.factory('AuthUser', function() {
    return {
        username: "{{ request.user.username|default:''|escapejs }}"
    }
});

{% endblock js-onpage %}


text:
namespace Atata.WebDriverExtras.Tests;

[TestFixture]
public class SearchOptionsTests
{
    [Test]
    public void SearchOptions_ToString()
    {
        SearchOptions options = new SearchOptions
        {
            Visibility = Visibility.Visible,
            IsSafely = false,
            Timeout = TimeSpan.FromSeconds(10.5),
            RetryInterval = TimeSpan.FromMilliseconds(750)
        };

        string expected = $"{{Visibility=Visible, Timeout={options.Timeout.ToShortIntervalString()}, RetryInterval={options.RetryInterval.ToShortIntervalString()}, IsSafely=False}}";

        Assert.That(options.ToString(), Is.EqualTo(expected));
    }
}


text:
declare namespace nunjucks {
	export function render(name: string, context?: Object): string;
	export function render(name: string, context?: Object, callback?: (err: any, res: string) => any): void;

	export function renderString(src: string, context: Object): string;
	export function renderString(src: string, context: Object, callback?: (err: any, res: string) => any): void;

	export function compile(src: string, env?: Environment): Template;
	export function compile(src: string, env?: Environment, callback?: (err: any, res: Template) => any): Template;

	export function precompile(path: string, opts?: PrecompileOptions): string;
	export function precompileString(src: string, opts?: PrecompileOptions): string;

	export interface PrecompileOptions {
		name?: string;
		asFunction?: boolean;
		force?: boolean;
		env?: Environment;
		include?: string[];
		exclude?: string[];
		wrapper?(templates: { name: string, template: string }, opts: PrecompileOptions): string;
	}

	export class Template {
		constructor(src: string, env?: Environment, eagerCompile?: boolean);
		render(context?: Object): string;
		render(context?: Object, callback?: (err: any, res: string) => any): void;
	}

	export function configure(options: ConfigureOptions): Environment;
	export function configure(path: string, options?: ConfigureOptions): Environment;

	export interface ConfigureOptions {
		autoescape?: boolean;
		throwOnUndefined?: boolean;
		trimBlocks?: boolean;
		lstripBlocks?: boolean;
		watch?: boolean;
		noCache?: boolean;
		web?: {
			useCache?: boolean,
			async?: boolean
		};
		express?: Object;
		tags?: {
			blockStart?: string,
			blockEnd?: string,
			variableStart?: string,
			variableEnd?: string,
			commentStart?: string,
			commentEnd?: string
		};
	}

	export class Environment {
		options: {
			autoescape: boolean;
		};

		constructor(loader: ILoader, opts?: ConfigureOptions);
		constructor(loaders: ILoader[], opts?: ConfigureOptions);

		render(name: string, context?: Object): string;
		render(name: string, context?: Object, callback?: (err: any, res: string) => any): void;

		renderString(name: string, context: Object): string;
		renderString(name: string, context: Object, callback?: (err: any, res: string) => any): void;

		addFilter(name: string, func: (...args: any[]) => any, async?: boolean): void;
		getFilter(name: string): void;

		addExtension(name: string, ext: Extension): void;
		removeExtension(name: string): void;
		getExtension(name: string): Extension;
		hasExtension(name: string): void;

		addGlobal(name: string, value: any): void;

		getTemplate(name: string, eagerCompile?: boolean): Template;
		getTemplate(name: string, eagerCompile?: boolean, callback?: (err: any, templ: Template) => Template): void;

		express(app: Object): void;
	}

	export interface Extension {
		tags: string[];
		// Parser API is undocumented it is suggested to check the source: https://github.com/mozilla/nunjucks/blob/master/src/parser.js
		parse(parser: any, nodes: any, lexer: any): any;
	}

	export function installJinjaCompat(): void;

	export interface ILoader {
		async?: boolean;
		getSource(name: string): LoaderSource;
		extend?(extender: ILoader): ILoader;
	}

	// Needs both Loader and ILoader since nunjucks uses a custom object system
	// Object system is also responsible for the extend methods
	export class Loader {
		on(name: string, func: (...args: any[]) => any): void;
		emit(name: string, ...args: any[]): void;
		resolve(from: string, to: string): string;
		isRelative(filename: string): boolean;
		extend(toExtend: ILoader): ILoader;
	}

	export interface LoaderSource {
		src: string;
		path: string;
		noCache: boolean;
	}

	export class FileSystemLoader extends Loader implements ILoader {
		init(searchPaths: string[], opts: any): void;
		getSource(name: string): LoaderSource;
	}

	export class PrecompiledLoader extends Loader implements ILoader {
		init(searchPaths: string[], opts: any): void;
		getSource(name: string): LoaderSource;
	}
}

declare module "nunjucks" {
	export = nunjucks;
}


text:
import { CanActivate, Component } from "../core/component-decorators";
import { NavigationActionCreator } from "./navigation.actions";

@Component({
    templateUrl: "wwwroot/navigation/navigation.component.html",
    selector: "navigation",
    providers: ["navigationActionCreator"]
})
export class NavigationComponent {
    constructor(private navigationActionCreator: NavigationActionCreator) { }

}


text:
<?php
/**
 * Created by Kutuzov Alexey Konstantinovich <lexus.1995@mail.ru>.
 * Author: Kutuzov Alexey Konstantinovich <lexus.1995@mail.ru>
 * Project: jungle
 * IDE: PhpStorm
 * Date: 13.10.2016
 * Time: 22:54
 */

$q = isset($_GET['query'])?$_GET['query']:'max_age';
switch($q){
	case 'max_age':
		header("Cache-Control: max-age=15");
		echo 'Content';
		break;
	case 'etag':
		header("ETag: \"sdfdsf4523sdfweDWasa\"");
		echo 'Content';
		break;
	case 'expired':
		$datetime = date(DATE_RFC2822, time() + 15);
		header("Last-Modified: {$datetime}");
		echo 'Content';
		break;
	case 'last_modified':
		$datetime = date(DATE_RFC2822, time() + 15);
		header("Last-Modified: {$datetime}");
		echo 'Content';
		break;

	default:

		echo 'Use the query parameter in url with key "query" (example: query=max_age)
allowed values:
 [max_age || etag || last_modified || expired]';
		break;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace WSMCTuristic_CentroHistorico.DAO
{
    public class SitioDAO
    {
        SqlCommand cmd;
        Conexion conn;
        BO.SitioBO oSitio;
        public int AgregarSitio(object obj)
        {
            cmd = new SqlCommand();
            conn = new Conexion();
            oSitio = (BO.SitioBO)obj;

            cmd.Connection = conn.Establecer();
            cmd.CommandText = "insertar_sitio";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add("@Nombre", SqlDbType.VarChar).Value = oSitio.NombreSitio;
            cmd.Parameters.Add("@Descripcion", SqlDbType.VarChar).Value = oSitio.DescripcionSitio;
            cmd.Parameters.Add("@Historia", SqlDbType.VarChar).Value = oSitio.Historia;
            cmd.Parameters.Add("@Direccion", SqlDbType.VarChar).Value = oSitio.Direccion;
            cmd.Parameters.Add("@Longitud", SqlDbType.Decimal).Value = oSitio.LongitudSitio;
            cmd.Parameters.Add("@Latitud", SqlDbType.Decimal).Value = oSitio.LatitudSitio;
            cmd.Parameters.Add("@Foto", SqlDbType.Image).Value = oSitio.FotoSitio;
            cmd.Parameters.Add("@SucesosImp", SqlDbType.VarChar).Value = oSitio.SucesoImportante;
            cmd.Parameters.Add("@idTipoSitio", SqlDbType.Int).Value = oSitio.IdTipoSitio;

            conn.Abrir();
            int retorno = cmd.ExecuteNonQuery();

            if (retorno <= 0)
            {
                retorno = 0;
            }
            else
            {
                retorno = 1;
            }

            return retorno;
        }

        public int ActualizarSitio(object obj)
        {
            cmd = new SqlCommand();
            conn = new Conexion();
            oSitio = (BO.SitioBO)obj;

            cmd.Connection = conn.Establecer();
            cmd.CommandText = "actualizar_sitio";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add("@IdSitio", SqlDbType.Int).Value = oSitio.IdSitio;
            cmd.Parameters.Add("@Nombre", SqlDbType.VarChar).Value = oSitio.NombreSitio;
            cmd.Parameters.Add("@Descripcion", SqlDbType.VarChar).Value = oSitio.DescripcionSitio;
            cmd.Parameters.Add("@Historia", SqlDbType.VarChar).Value = oSitio.Historia;
            cmd.Parameters.Add("@Direccion", SqlDbType.VarChar).Value = oSitio.Direccion;
            cmd.Parameters.Add("@Longitud", SqlDbType.Decimal).Value = oSitio.LongitudSitio;
            cmd.Parameters.Add("@Latitud", SqlDbType.Decimal).Value = oSitio.LatitudSitio;
            cmd.Parameters.Add("@Foto", SqlDbType.Image).Value = oSitio.FotoSitio;
            cmd.Parameters.Add("@SucesosImp", SqlDbType.VarChar).Value = oSitio.SucesoImportante;
            cmd.Parameters.Add("@idTipoSitio", SqlDbType.Int).Value = oSitio.IdTipoSitio;

            conn.Abrir();
            int retorno = cmd.ExecuteNonQuery();

            if (retorno <= 0)
            {
                retorno = 0;
            }
            else
            {
                retorno = 1;
            }

            return retorno;
        }

        public int EliminarSitio(object obj)
        {
            cmd = new SqlCommand();
            conn = new Conexion();
            oSitio = (BO.SitioBO)obj;

            cmd.Connection = conn.Establecer();
            cmd.CommandText = "eliminar_sitio";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add("@IdSitio", SqlDbType.Int).Value = oSitio.IdSitio;

            conn.Abrir();
            int retorno = cmd.ExecuteNonQuery();

            if (retorno <= 0)
            {
                retorno = 0;
            }
            else
            {
                retorno = 1;
            }

            return retorno;
        }
        //Agregue el dataset y el arreglo de byte de esta tabla. Diosemir Nah
        public DataSet SitioDS()
        {
            conn = new Conexion();
            string sql;
            sql = "EXEC ver_Sitios";
            return conn.TablaDS(sql);
        }
    }
}


text:
<?php

namespace Concrete\Core\Summary\Category\Driver;

use Concrete\Core\Summary\Category\CategoryMemberInterface;
use Concrete\Core\Summary\Template\RenderableTemplateInterface;

defined('C5_EXECUTE') or die("Access Denied.");

interface DriverInterface
{

    public function getCategoryMemberFromIdentifier($identifier): ?CategoryMemberInterface;

    public function getMemberSummaryTemplate($templateID): ?RenderableTemplateInterface;

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!-- add by freeeyes -->
<!-- 在这里定义程序中需要用到的宏类型 -->
<!-- 亦可定义相关的枚举 -->
<configer ProcName="DBTest" DB="mysql">
	<define srcType="unsigned char" tagType="uint8" desc="uint8" />
	<define srcType="unsigned short" tagType="uint16" desc="uint16" />
	<define srcType="unsigned int" tagType="uint32" desc="uint32" />
	<enum name="ItemType">
		<Info name="STRONGE" />
		<Info name="AGILE" />
	</enum>
</configer>


text:
<?php

class ControllerApi extends Controller
{
    /**
     * convert array to json
     * @param array $data
     */
    public function renderJson($data, $encode=true) {
        $this->layout = false;
        header('Content-Type: application/json');
		if($encode)
        	echo CJSON::encode($data);
		else
			echo $data;
        Yii::app()->end();
    }

	private function _sendResponse($status = 200, $body = '', $content_type = 'text/html') {
		// set the status
		$status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);
		header($status_header);
		// and the content type
		header('Content-type: ' . $content_type);

		// pages with body are easy
		if ($body != '') {
			// send the body
			echo $body;
		}
		// we need to create the body if none is passed
		else {
			// create some body messages
			$message = '';
			switch ($status) {
				case 401:
					$message = 'You must be authorized to view this page.';
					break;
				case 404:
					$message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
					break;
				case 500:
					$message = 'The server encountered an error processing your request.';
					break;
				case 501:
					$message = 'The requested method is not implemented.';
					break;
			}

			// servers don't always have a signature turned on
			// (this is an apache directive "ServerSignature On")
			$signature = ($_SERVER['SERVER_SIGNATURE'] == '') ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];

			// this should be templated in a real-world solution
			$body = '
	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<title>' . $status . ' ' . $this->_getStatusCodeMessage($status) . '</title>

' . $this->_getStatusCodeMessage($status) . '

' . $message . '

		<address>' . $signature . '</address>

	';

			echo $body;
		}
		Yii::app()->end();
	}

	private function _getStatusCodeMessage($status) {
		// these could be stored in a .ini file and loaded
		// via parse_ini_file()... however, this will suffice
		// for an example
		$codes = Array(
			200 => 'OK',
			400 => 'Bad Request',
			401 => 'Unauthorized',
			402 => 'Payment Required',
			403 => 'Forbidden',
			404 => 'Not Found',
			500 => 'Internal Server Error',
			501 => 'Not Implemented',
		);
		return (isset($codes[$status])) ? $codes[$status] : '';
	}

}


text:
@implementation NSObject (CYLTabBarControllerExtention)

- (BOOL)cyl_isForceLandscape {
    NSNumber *isForceLandscapeObject = objc_getAssociatedObject(self, @selector(cyl_isForceLandscape));
    return [isForceLandscapeObject boolValue];
}

- (void)cyl_setIsForceLandscape:(BOOL)isForceLandscape {
    NSNumber *isForceLandscapeObject = @(isForceLandscape);
    objc_setAssociatedObject(self, @selector(cyl_isForceLandscape), isForceLandscapeObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIResponder<UIApplicationDelegate> *)cyl_sharedAppDelegate {
     id<UIApplicationDelegate> appDelegate = [UIApplication sharedApplication].delegate;
    return (UIResponder<UIApplicationDelegate> *)appDelegate;
}

- (void)cyl_forceUpdateInterfaceOrientation:(UIInterfaceOrientation)orientation {
    UIResponder<UIApplicationDelegate> *appDelegate = [self cyl_sharedAppDelegate];
    BOOL isForceLandscape = (UIInterfaceOrientationLandscapeLeft == orientation) || (UIInterfaceOrientationLandscapeRight == orientation);
    appDelegate.cyl_isForceLandscape = isForceLandscape;
    if ([appDelegate respondsToSelector:@selector(application:supportedInterfaceOrientationsForWindow:)]) {
        [appDelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:UIApplication.sharedApplication.keyWindow];
    }
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        NSNumber *num = [[NSNumber alloc]initWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] performSelector:@selector(setOrientation:)withObject:(id)num];
        [UIViewController attemptRotationToDeviceOrientation];
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val  = [@(orientation) intValue];
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

+ (UIViewController * __nullable)cyl_topmostViewController {
    UIViewController *topViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];

    if (topViewController == nil) {
        return nil;
    }

    while (true) {
        if (topViewController.presentedViewController != nil) {
            topViewController = topViewController.presentedViewController;
        } else if ([topViewController isKindOfClass:[UINavigationController class]]) {
            UINavigationController *navi = (UINavigationController *)topViewController;
            topViewController = navi.topViewController;
        } else if ([topViewController isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tab = (UITabBarController *)topViewController;
            topViewController = tab.selectedViewController;
        } else {
            break;
        }
    }

    return topViewController;
}

+ (UINavigationController * __nullable)cyl_currentNavigationController {
    return [[UIViewController cyl_topmostViewController] navigationController];
}

+ (void)cyl_dismissAll:(void (^ __nullable)(void))completion {
    UIViewController *topViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];

    if (topViewController == nil) {
        !completion ?: completion();
        return;
    }

    NSMutableArray *list = [NSMutableArray new];

    while (true) {
        if (topViewController.presentedViewController != nil) {
            topViewController = topViewController.presentedViewController;
            [list addObject:topViewController];
        } else if ([topViewController isKindOfClass:[UINavigationController class]]) {
            UINavigationController *navi = (UINavigationController *)topViewController;
            topViewController = navi.topViewController;
        } else if ([topViewController isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tab = (UITabBarController *)topViewController;
            topViewController = tab.selectedViewController;
        } else {
            break;
        }
    }

    if (list.count == 0) {
        if (completion) {
            completion();
        }
        return;
    }

    for (NSInteger i = list.count - 1; i >=0 ; i--) {

        UIViewController *vc = list[i];
        if (i == 0) {
            if ([vc isKindOfClass:[UINavigationController class]]) {
                [(UINavigationController *)vc popToRootViewControllerAnimated:NO];
            }
            [vc dismissViewControllerAnimated:NO completion:completion];
        } else {
            if ([vc isKindOfClass:[UINavigationController class]]) {
                [(UINavigationController *)vc popToRootViewControllerAnimated:NO];
            }
            [vc dismissViewControllerAnimated:NO completion:nil];
        }
    }
}

@end


text:
'use strict';

exports.__esModule = true;
exports.BsCheckbox = undefined;

var _dec, _dec2, _desc, _value, _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8;

var _aureliaFramework = require('aurelia-framework');

function _initDefineProp(target, property, descriptor, context) {
  if (!descriptor) return;
  Object.defineProperty(target, property, {
    enumerable: descriptor.enumerable,
    configurable: descriptor.configurable,
    writable: descriptor.writable,
    value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
  });
}

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
  var desc = {};
  Object['ke' + 'ys'](descriptor).forEach(function (key) {
    desc[key] = descriptor[key];
  });
  desc.enumerable = !!desc.enumerable;
  desc.configurable = !!desc.configurable;

  if ('value' in desc || desc.initializer) {
    desc.writable = true;
  }

  desc = decorators.slice().reverse().reduce(function (desc, decorator) {
    return decorator(target, property, desc) || desc;
  }, desc);

  if (context && desc.initializer !== void 0) {
    desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
    desc.initializer = undefined;
  }

  if (desc.initializer === void 0) {
    Object['define' + 'Property'](target, property, desc);
    desc = null;
  }

  return desc;
}

function _initializerWarningHelper(descriptor, context) {
  throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}

var BsCheckbox = exports.BsCheckbox = (_dec = (0, _aureliaFramework.bindable)({ defaultBindingMode: _aureliaFramework.bindingMode.twoWay }), _dec2 = (0, _aureliaFramework.bindable)({ defaultBindingMode: _aureliaFramework.bindingMode.twoWay }), (_class = function () {
  function BsCheckbox() {
    _classCallCheck(this, BsCheckbox);

    _initDefineProp(this, 'name', _descriptor, this);

    _initDefineProp(this, 'value', _descriptor2, this);

    _initDefineProp(this, 'checked', _descriptor3, this);

    _initDefineProp(this, 'model', _descriptor4, this);

    _initDefineProp(this, 'label', _descriptor5, this);

    _initDefineProp(this, 'helptext', _descriptor6, this);

    _initDefineProp(this, 'disabled', _descriptor7, this);

    _initDefineProp(this, 'inline', _descriptor8, this);
  }

  BsCheckbox.prototype.bind = function bind() {
    if (this.checked === 'true' || this.checked === 'checked') {
      this.checked = true;
    }
    if (!this.model) {
      this.model = this.value;
    }
  };

  BsCheckbox.prototype.attached = function attached() {
    if (this.inline) {
      this.lbl.classList.add('checkbox-inline');
    } else {
      this.template.classList.add('checkbox');
    }
    if (this.disabled) {
      this.template.classList.add('disabled');
      this.lbl.classList.add('disabled');
    }
    if (this.helptext) {
      this.input.setAttribute('aria-describedby', this.name + '-help');
    }
  };

  return BsCheckbox;
}(), (_descriptor = _applyDecoratedDescriptor(_class.prototype, 'name', [_aureliaFramework.bindable], {
  enumerable: true,
  initializer: null
}), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, 'value', [_dec], {
  enumerable: true,
  initializer: null
}), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, 'checked', [_dec2], {
  enumerable: true,
  initializer: function initializer() {
    return false;
  }
}), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, 'model', [_aureliaFramework.bindable], {
  enumerable: true,
  initializer: null
}), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, 'label', [_aureliaFramework.bindable], {
  enumerable: true,
  initializer: function initializer() {
    return '';
  }
}), _descriptor6 = _applyDecoratedDescriptor(_class.prototype, 'helptext', [_aureliaFramework.bindable], {
  enumerable: true,
  initializer: function initializer() {
    return '';
  }
}), _descriptor7 = _applyDecoratedDescriptor(_class.prototype, 'disabled', [_aureliaFramework.bindable], {
  enumerable: true,
  initializer: function initializer() {
    return false;
  }
}), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, 'inline', [_aureliaFramework.bindable], {
  enumerable: true,
  initializer: function initializer() {
    return false;
  }
})), _class));


text:
package com.hazelcast.internal.util.comparators;

import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class BinaryValueComparatorTest extends AbstractValueComparatorTest {

    @Override
    void newRecordComparator() {
        comparator = BinaryValueComparator.INSTANCE;
    }
}


text:
layout: post
title: "Weeknotes s2e1"
date: "2020-11-15"
meta: ""
images: ""
categories: ["weeknotes"]
published: true
---

Week commencing 9th November 2020.

New weeknotes format this week, weeknotes were becoming to labour intensive with less and less value so i'm borrowing a format from [Si][si], who in turn borrowed a format [Brian][brian].

## Life
* Youngest child continues to teethe and an alarming rate. No sleep for us. 💤
* Ordered new [LED lighting][govee] for the office because it's now dark most of the time 💡
* Bought a new car 🚗
* Went for a walk in the dark, gave the eldest a torch to go monster hunting 🕵♂
* Visited the [Christmas Tree Farm][welford-christmas] at Welford because we all needed a bit of light at the end of the tunnel 🎄

## Work
* More interviews for Lead Software Engineer (applications are still open if you know someone) 👩💻
* Marked four weeks left in the current job with some handover of work to Kiri, Josie and Will 🎉
* Set up [AWS Control Tower][aws-control-tower] and new accounts for work werk ☁
* First show and tell for the latest project (websites for the new West and North Northamptonshire unitary authorities) 💻
* Visited the new job for [Black Friday launch][bfcm] 🦈

## Side stuff
* Edited some photos I took last week for [Pudding & Bear][pudding-and-bear] 📷
* Built out a website for [Pudding and Bear][pudding-and-bear] to offer online ordering 🥡
* Loved talking with those folks over at [On The Side][ots]
* Worked with [Lauren][redjotter] to prep everything for her latest [UPFRONT course][upfront-bond-3] launch 🟥
* Signed up for a short course with [Ness Labs][ness-labs], starts Monday 👨🎓

## Down time
* We're rewatching [House][house] from the beginning, wrapped up Season 2 this week 🩺
* Picked up [Team Topologies][team-topologies] again 📕
* Caught up with [Lockdown parenting hell][parenting-podcast] podcast 🎙
* Managed to ride 6/7 days with [Peloton][peloton] 🚴♂ (referral code: `PCSC42`)

## Data
* Realised I'm not measuring enough in a way I can easily share 📈
* Started measuring data to share more easily and make better decisions 📏

[pudding-and-bear]: https://www.instagram.com/pudding.and.bear/
[si]: https://twitter.com/si
[ots]: https://ontheside.network/
[redjotter]: https://www.instagram.com/_laurencurrie_
[upfront-bond-3]: https://course.weareupfront.com/bond-3
[brian]: https://twitter.com/briansuda
[bfcm]: https://gymshark.com/
[house]: https://www.amazon.co.uk/gp/video/detail/B00FZV88BC/ref=atv_dp_share_cu_r
[peloton]: https://www.onepeloton.co.uk/
[team-topologies]: https://teamtopologies.com/
[parenting-podcast]: https://open.spotify.com/show/1Zuurv8AZFWti60lSXiDgz
[ness-labs]: https://nesslabs.com
[welford-christmas]:https://www.welfordchristmastreefarm.co.uk/
[govee]: https://www.govee.com/
[aws-control-tower]: https://aws.amazon.com/controltower/

[contact]: /about


text:
class SessionsController < Devise::SessionsController
  def create

  end
end


text:
<?php

namespace TypiCMS\Modules\Pages\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use TypiCMS\Modules\Core\Http\Controllers\BaseAdminController;
use TypiCMS\Modules\Pages\Http\Requests\FormRequest;
use TypiCMS\Modules\Pages\Models\Page;

class AdminController extends BaseAdminController
{
    public function index(): View
    {
        return view('pages::admin.index');
    }

    public function create(): View
    {
        $model = new Page();

        return view('pages::admin.create')
            ->with(compact('model'));
    }

    public function edit(Page $page): View
    {
        return view('pages::admin.edit')
            ->with(['model' => $page]);
    }

    public function store(FormRequest $request): RedirectResponse
    {
        $page = Page::create($request->validated());

        return $this->redirect($request, $page);
    }

    public function update(Page $page, FormRequest $request): RedirectResponse
    {
        $page->update($request->validated());

        return $this->redirect($request, $page);
    }
}


text:
package com.br.pvemira.app.repository;

import com.br.pvemira.app.model.StrawPoll;
import com.br.pvemira.app.model.Vote;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

/**
 * Created by pvmeira on 17/06/17.
 */
public interface VoteRepository extends CrudRepository<Vote, Long> {
    List<Vote> findVotesByPollEquals(StrawPoll poll);
}


text:
/**
 */
package CIM.IEC61970.Wires;

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

import org.eclipse.emf.common.util.Enumerator;

/**
 *
 * A representation of the literals of the enumeration 'Winding Type',
 * and utility methods for working with them.
 *
 * @see CIM.IEC61970.Wires.WiresPackage#getWindingType()
 * @model
 * @generated
 */
public enum WindingType implements Enumerator {
	/**
	 * The 'Tertiary' literal object.
	 *
	 *
	 * @see #TERTIARY_VALUE
	 * @generated
	 * @ordered
	 */
	TERTIARY(0, "tertiary", "tertiary"),

	/**
	 * The 'Quaternary' literal object.
	 *
	 *
	 * @see #QUATERNARY_VALUE
	 * @generated
	 * @ordered
	 */
	QUATERNARY(1, "quaternary", "quaternary"),

	/**
	 * The 'Primary' literal object.
	 *
	 *
	 * @see #PRIMARY_VALUE
	 * @generated
	 * @ordered
	 */
	PRIMARY(2, "primary", "primary"),

	/**
	 * The 'Secondary' literal object.
	 *
	 *
	 * @see #SECONDARY_VALUE
	 * @generated
	 * @ordered
	 */
	SECONDARY(3, "secondary", "secondary");

	/**
	 * The 'Tertiary' literal value.
	 *
	 *

	 * If the meaning of 'Tertiary' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #TERTIARY
	 * @model name="tertiary"
	 * @generated
	 * @ordered
	 */
	public static final int TERTIARY_VALUE = 0;

	/**
	 * The 'Quaternary' literal value.
	 *
	 *

	 * If the meaning of 'Quaternary' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #QUATERNARY
	 * @model name="quaternary"
	 * @generated
	 * @ordered
	 */
	public static final int QUATERNARY_VALUE = 1;

	/**
	 * The 'Primary' literal value.
	 *
	 *

	 * If the meaning of 'Primary' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #PRIMARY
	 * @model name="primary"
	 * @generated
	 * @ordered
	 */
	public static final int PRIMARY_VALUE = 2;

	/**
	 * The 'Secondary' literal value.
	 *
	 *

	 * If the meaning of 'Secondary' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #SECONDARY
	 * @model name="secondary"
	 * @generated
	 * @ordered
	 */
	public static final int SECONDARY_VALUE = 3;

	/**
	 * An array of all the 'Winding Type' enumerators.
	 *
	 *
	 * @generated
	 */
	private static final WindingType[] VALUES_ARRAY =
		new WindingType[] {
			TERTIARY,
			QUATERNARY,
			PRIMARY,
			SECONDARY,
		};

	/**
	 * A public read-only list of all the 'Winding Type' enumerators.
	 *
	 *
	 * @generated
	 */
	public static final List<WindingType> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));

	/**
	 * Returns the 'Winding Type' literal with the specified literal value.
	 *
	 *
	 * @param literal the literal.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static WindingType get(String literal) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			WindingType result = VALUES_ARRAY[i];
			if (result.toString().equals(literal)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Winding Type' literal with the specified name.
	 *
	 *
	 * @param name the name.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static WindingType getByName(String name) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			WindingType result = VALUES_ARRAY[i];
			if (result.getName().equals(name)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Winding Type' literal with the specified integer value.
	 *
	 *
	 * @param value the integer value.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static WindingType get(int value) {
		switch (value) {
			case TERTIARY_VALUE: return TERTIARY;
			case QUATERNARY_VALUE: return QUATERNARY;
			case PRIMARY_VALUE: return PRIMARY;
			case SECONDARY_VALUE: return SECONDARY;
		}
		return null;
	}

	/**
	 *
	 *
	 * @generated
	 */
	private final int value;

	/**
	 *
	 *
	 * @generated
	 */
	private final String name;

	/**
	 *
	 *
	 * @generated
	 */
	private final String literal;

	/**
	 * Only this class can construct instances.
	 *
	 *
	 * @generated
	 */
	private WindingType(int value, String name, String literal) {
		this.value = value;
		this.name = name;
		this.literal = literal;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public int getValue() {
	  return value;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getName() {
	  return name;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getLiteral() {
	  return literal;
	}

	/**
	 * Returns the literal value of the enumerator, which is its string representation.
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		return literal;
	}

} //WindingType


text:
/**
 * Generated by Agitar build: AgitarOne Version 6.0.0.000018 (Build date: Sep 06, 2013) [6.0.0.000018]
 * JDK Version: 1.6.0_14
 *
 * Generated on 2014-3-11 13:27:31
 * Time to generate: 00:12.563 seconds
 *
 *
 * agitar.src.md5=com.huawei.ism.openapi.common.DefaultCommFactory:7b1406a11775affe8c04dda937f137c4
 *
 */

package com.huawei.ism.openapi.common;

import com.agitar.lib.junit.AgitarTestCase;
import com.agitar.lib.mockingbird.Mockingbird;
import com.huawei.ism.openapi.common.commu.rest.RestRequestHandler;
import com.huawei.ism.openapi.common.exception.ApiException;
import com.huawei.ism.openapi.common.exception.ApiMessage;
import com.huawei.ism.openapi.common.handlercfg.HandlerMaps;
import com.huawei.ism.openapi.common.keydeifines.ConstantsDefine;
import com.huawei.ism.openapi.diskpool.DiskPoolHandlerImp;

public class DefaultCommFactoryAgitarTest extends AgitarTestCase {

    public Class getTargetClass()  {
        return DefaultCommFactory.class;
    }

    public void testConstructor() throws Throwable {
        RestRequestHandler restRequestHandler = new RestRequestHandler("testDefaultCommFactoryIp", 100);
        DefaultCommFactory defaultCommFactory = new DefaultCommFactory(restRequestHandler, "testDefaultCommFactoryDeviceID");
        assertEquals("defaultCommFactory.deviceID", "testDefaultCommFactoryDeviceID", getPrivateField(defaultCommFactory, "deviceID"));
        assertSame("defaultCommFactory.restRequestHandler", restRequestHandler, getPrivateField(defaultCommFactory, "restRequestHandler"));
    }

    public void testGetHandler() throws Throwable {
        DefaultCommFactory defaultCommFactory = new DefaultCommFactory(new RestRequestHandler("testDefaultCommFactoryIp", 100), "testDefaultCommFactoryDeviceID");
        DiskPoolHandlerImp result = (DiskPoolHandlerImp) defaultCommFactory.getHandler("DiskPoolHandler");
        assertNotNull("result", result);
    }

    public void testGetHandler1() throws Throwable {
        DefaultCommFactory defaultCommFactory = new DefaultCommFactory(new RestRequestHandler("testDefaultCommFactoryIp", 100), "testDefaultCommFactoryDeviceID");
        Object result = defaultCommFactory.getHandler("testDefaultCommFactoryHandlerName");
        assertNull("result", result);
    }

    public void testGetHandlerThrowsApiExceptionWithAggressiveMocks() throws Throwable {
        storeStaticField(ConstantsDefine.ExceptionConstant.class, "SECURITYEXPMSG");
        DefaultCommFactory defaultCommFactory = (DefaultCommFactory) Mockingbird.getProxyObject(DefaultCommFactory.class, true);
        HandlerMaps handlerMaps = (HandlerMaps) Mockingbird.getProxyObject(HandlerMaps.class);
        Class class2 = (Class) Mockingbird.getProxyObject(Class.class);
        ApiMessage apiMessage = (ApiMessage) Mockingbird.getProxyObject(ApiMessage.class);
        Mockingbird.enterRecordingMode();
        Mockingbird.setReturnValue(HandlerMaps.getHandlerMapsInstance(), handlerMaps);
        setPrivateField(ConstantsDefine.ExceptionConstant.class, "SECURITYEXPMSG", apiMessage);
        Mockingbird.setReturnValue(handlerMaps.getValue(""), class2);
        Mockingbird.setReturnValue(false, Mockingbird.getProxyObject(Throwable.class), "getMessage", "()java.lang.String", "", 1);
        Mockingbird.replaceObjectForRecording(ApiException.class, "<init>(com.huawei.ism.openapi.common.exception.ApiMessage,java.lang.Exception)", Mockingbird.getProxyObject(ApiException.class));
        Mockingbird.enterTestMode(DefaultCommFactory.class);
        try {
            defaultCommFactory.getHandler("");
            fail("Expected ApiException to be thrown");
        } catch (ApiException ex) {
            assertTrue("Test call resulted in expected outcome", true);
        }
    }
}


text:
#import "UIScrollViewAnimation.h"

CGFloat UILinearInterpolation(CGFloat t, CGFloat start, CGFloat end)
{
    if (t <= 0) {
        return start;
    } else if (t >= 1) {
        return end;
    } else {
        return t * end + (1 - t) * start;
    }
}

CGFloat UIQuadraticEaseOut(CGFloat t, CGFloat start, CGFloat end)
{
    if (t <= 0) {
        return start;
    } else if (t >= 1) {
        return end;
    } else {
        return UILinearInterpolation(2 * t - t * t, start, end);
    }
}

@implementation UIScrollViewAnimation

- (id)initWithScrollView:(UIScrollView *)sv
{
    if ((self=[super init])) {
        _scrollView = sv;
        _beginTime = [NSDate timeIntervalSinceReferenceDate];
    }
    return self;
}

- (BOOL)animate
{
    return YES;
}

- (void)momentumScrollBy:(CGPoint)delta
{
    // does nothing
}

@end


text:
package com.greenpepper.maven.runner;

public class Main
{

	public static void main(String... args)
	{
		CommandLineRunner runner = new CommandLineRunner();

		try
		{
			runner.run(args);
		}
		catch (Throwable t)
		{
			System.err.println(t.getMessage());
			System.err.println("Try '--help' for more information.");

			if (t.getCause() != null)
			{
				System.err.println("Caused by:");
				t.getCause().printStackTrace(System.err);
			}

			System.exit(1);
		}

		System.exit(0);
	}
}


text:
define([
  'common/views/visualisations/volumetrics/number',
  'extensions/views/view',
  'extensions/collections/collection'
],
function (VolumetricsNumberView, View, Collection) {
  describe('VolumetricsNumberView', function () {
    var subject, collection;
    beforeEach(function () {
      spyOn(VolumetricsNumberView.prototype, 'render');
      collection = new Collection();
      collection.reset({
        data: [
          { count: 1 },
          { count: 2 },
          { count: 3 },
          { count: 4 },
          { count: null },
          { count: null }
        ]
      }, { parse: true });
      subject = new VolumetricsNumberView({
        collection: collection,
        valueAttr: 'count'
      });
    });

    describe('formatValue', function () {
      it('should call the view format method with the value', function () {
        spyOn(View.prototype, 'format').and.returnValue('456');
        var returnValue;
        returnValue = subject.formatValue('123');
        expect(View.prototype.format).toHaveBeenCalledWith('123', { type: 'number', magnitude: true, pad: true });
        expect(returnValue).toEqual('456');
      });
    });

    describe('getValue', function () {
      it('should call the view format method with the last defined model (valueAttr) on the collection', function () {
        spyOn(VolumetricsNumberView.prototype, 'formatValue');

        subject.getValue();

        expect(VolumetricsNumberView.prototype.formatValue).toHaveBeenCalledWith(4);
      });

      it('should call the view format method with null if there is no last defined models in the collection', function () {
        spyOn(VolumetricsNumberView.prototype, 'formatValue');
        spyOn(Collection.prototype, 'lastDefined').and.returnValue(undefined);

        subject.getValue();

        expect(VolumetricsNumberView.prototype.formatValue).toHaveBeenCalledWith(null);
      });
    });

    describe('getLabel', function () {

      var prefix;

      beforeEach(function () {
        prefix = 'week';
        subject.labelPrefix = prefix;
      });

      describe('should show the last available date in the collection', function () {
        beforeEach(function () {
          collection.reset({
            data: [
              { count: 1, '_timestamp': '2014-07-14T00:00:00+00:00' },
              { count: 2, '_timestamp': '2014-07-14T00:00:00+00:00' },
              { count: 3, '_timestamp': '2014-07-14T00:00:00+00:00' },
              { count: 4, '_timestamp': '2014-07-14T00:00:00+00:00' },
              { count: 5, '_timestamp': '2014-07-14T00:00:00+00:00' },
              { count: 6, '_timestamp': '2014-07-14T00:00:00+00:00' }
            ]
          }, { parse: true });
        });

        it('should return the appropriately formatted label', function () {
          expect(subject.getLabel()).toEqual('14 July 2014');
        });

        it('should return the appropriately formatted label for arbitrary periods', function () {
          spyOn(collection.dataSource, 'get').and.returnValue({period: 'month'});
          expect(subject.getLabel()).toEqual('July 2014');
        });

      });

    });

    describe('getValueSelected', function () {
      it('should call the view format method with the appropriate selectedModel attribute', function () {
        var fakeSelection = {
          selectedModel: collection.at(0)
        };
        spyOn(View.prototype, 'format').and.returnValue('456');
        var returnValue;
        returnValue = subject.getValueSelected(fakeSelection);
        expect(View.prototype.format).toHaveBeenCalledWith(1, { type : 'number', magnitude : true, pad : true });
        expect(returnValue).toEqual('456');
      });
    });

    describe('getLabelSelected', function () {
      it('should call the view formatPeriod method with the appropriate selectedModel attribute', function () {
        var fakeSelection = {
          selectedModel: collection.at(0)
        };
        spyOn(View.prototype, 'formatPeriod').and.returnValue('456');
        var returnValue;
        returnValue = subject.getLabelSelected(fakeSelection);
        expect(View.prototype.formatPeriod).toHaveBeenCalledWith(collection.at(0), 'week');
        expect(returnValue).toEqual('456');
      });
    });

  });
});


text:
#include "cocos2d.h"

USING_NS_CC;

class DRUserDefault
{
public:
    DRUserDefault();
	virtual ~DRUserDefault();

    static DRUserDefault* sharedUserDefault();
    void flush();               //save data

    //round
    void setRoundCount(unsigned int pCount){m_roundCount=pCount;}
    unsigned int getRoundCount(){return m_roundCount;}

    //score
    void setScore(unsigned int pScore){m_score=pScore;}
    unsigned int getScore(){return m_score;}

    //monster
    void setKillMonsterCount(unsigned int pCount){m_killMonsterCount=pCount;}
    unsigned int getKillMonsterCount(){return m_killMonsterCount;}

    //coin
    void setCoin(unsigned int pCount){m_coin=pCount;}
    unsigned int getCoin(){return m_coin;}

    //weapon
    void setWeaponSwitch(bool pSwitch){m_weaponSwitch=pSwitch;}
    bool getWeaponSwitch(){return m_weaponSwitch;}
    void addWeapon(unsigned int pID);
    CCDictionary *getWeaponPackage(){return m_weaponPackage;}

private:
    void writeUserDefault();
    void readUserDefault();

private:
	unsigned int     m_roundCount;
    unsigned int     m_score;
    unsigned int     m_killMonsterCount;
    unsigned int     m_coin;

    bool             m_weaponSwitch;
    CCDictionary     *m_weaponPackage;
};

#endif // __DR_USERDEFAULT_H__


text: <link rel="stylesheet" href="style.css">


text:
package main

// merges multiple frequency count files into one
// this is could use a merge sort and be smart

import (
	"bufio"
	"compress/gzip"
	"flag"
	"fmt"
	"log"
	"os"
	"sort"
	"strconv"
	"strings"
)

// freqCount is mapping of string->count
type freqCount map[string]int

// make a new counter with some minor preallocation
//  each month has about 2.2M uniques
func newFreqCount() freqCount {
	return make(freqCount, 3000000)
}

// LoadCSV loads in a CSV in form of WORD,COUNT
func loadCSV(counts freqCount, fname string) error {
	fi, err := os.Open(fname)
	if err != nil {
		return err
	}
	defer fi.Close()

	fizip, err := gzip.NewReader(fi)
	if err != nil {
		return err
	}
	defer fizip.Close()

	scanner := bufio.NewScanner(fizip)
	for scanner.Scan() {
		line := scanner.Text()
		parts := strings.SplitN(line, ",", 2)
		if len(parts) != 2 {
			return fmt.Errorf("Got extra junk in line: %q", line)
		}
		c, err := strconv.Atoi(parts[1])
		if err != nil {
			return fmt.Errorf("Number conversion failed: %q", line)
		}

		counts[parts[0]] += c
	}
	return scanner.Err()
}

// returns true if any character is repeated more than N times
func repeated(s string, n int) bool {
	slen := len(s)
	if slen < n {
		return false
	}
	ch := s[0]
	count := 1
	for i := 1; i < slen; i++ {
		cnext := s[i]
		if cnext != ch {
			ch = cnext
			count = 1
			continue
		}
		count++
		if count == n {
			return true
		}
	}
	return false
}

// returns true if a haha words.  hahhahahhhahaha, lololo
func haha(s string) bool {
	return strings.Contains(s, "haha") || strings.Contains(s, "lolo")
}

func main() {
	outfile := flag.String("o", "RC-total.csv.gz", "output file name")
	mincount := flag.Int("mincount", 2, "only output if freqcount >=, 0 = all")
	minlen := flag.Int("minlen", 7, "only output if word is >=, 0 = all")
	flag.Parse()
	if *outfile == "" {
		log.Fatalf("Must specificy outfile")
	}
	args := flag.Args()
	counts := newFreqCount()
	for _, arg := range args {
		log.Printf("Loading %s", arg)
		err := loadCSV(counts, arg)
		if err != nil {
			log.Fatalf("%s: %s", arg, err)
		}
	}
	fo, err := os.Create(*outfile)
	if err != nil {
		log.Fatalf("OH NO, unable to write: %s", err)
	}
	fout := gzip.NewWriter(fo)

	keys := make([]string, 0, len(counts))
	total := 0
	for k, v := range counts {
		total += v
		if v >= *mincount && len(k) >= *minlen && !repeated(k, 4) && !haha(k) {
			keys = append(keys, k)
		}
	}
	sort.Strings(keys)
	for _, k := range keys {
		fout.Write([]byte(fmt.Sprintf("%s,%d\n", k, counts[k])))
	}

	fout.Close()
	fo.Close()
	log.Printf("DONE: wrote %s got %d unique words from %d", *outfile, len(keys), total)
}


text:
require 'spec_helper'

describe "user_roles/index.html.erb" do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
.. _development:

Development
===========

While skosprovider is still in development, the basic premise is fairly
stable and the API changes have been fairly minor from version to version. We do
continue to refine the project and make the providers more expressive.

We try to cover as much code as we can with unit tests. You can run them using
tox_ or directly through nose. When providing a pull request, please run the
unit tests first and make sure they all pass. Please provide new unit tests
to maintain 100% coverage.

.. code-block:: bash

    $ tox
    # No coverage
    $ py.test
    # Coverage
    $ py.test --cov skosprovider --cov-report term-missing
    # Only run a subset of the tests
    $ py.test skosprovider/tests/test_registry.py

.. _tox: http://tox.testrun.org


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Module</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.myrobotlab.pickToLight

Class Module

java.lang.Object

org.myrobotlab.pickToLight.Module

public class Module
extends java.lang.Object

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

class
Module.BlinkThread

class
Module.CycleThread

Field Summary

Fields

Modifier and Type
Field and Description

static org.slf4j.Logger
log

static int
MASK_DISPLAY

static int
MASK_LED

static int
MASK_SENSOR

Constructor Summary

Constructors

Constructor and Description

Module(int bus,
      int i2cAddress)

Method Summary

Methods

Modifier and Type
Method and Description

void
blinkOff(java.lang.String msg,
        int blinkNumber,
        int blinkDelay)

void
blinkOn(java.lang.String msg,
       int blinkNumber,
       int blinkDelay)

void
clear()

void
cycle(java.lang.String msg)

void
cycle(java.lang.String msg,
     int delay)

void
cycleStop()

java.lang.String
display(java.lang.String str)

int
getI2CAddress()

int
getI2CBus()

static void
initTranslation()

int
ledOff()

int
ledOn()

void
logByteArray(byte[] data)

void
logByteArray(java.lang.String prefix,
            byte[] data)

int
readSensor()

static byte
translate(char c)

byte[]
writeDisplay(byte[] data)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

log

public static final org.slf4j.Logger log

MASK_DISPLAY

public static final int MASK_DISPLAY

See Also:

Constant Field Values

MASK_LED

public static final int MASK_LED

See Also:

Constant Field Values

MASK_SENSOR

public static final int MASK_SENSOR

See Also:

Constant Field Values

Constructor Detail

Module

public Module(int bus,
      int i2cAddress)

Method Detail

initTranslation

public static void initTranslation()

translate

public static byte translate(char c)

logByteArray

public void logByteArray(byte[] data)

logByteArray

public void logByteArray(java.lang.String prefix,
                byte[] data)

writeDisplay

public byte[] writeDisplay(byte[] data)

display

public java.lang.String display(java.lang.String str)

getI2CAddress

public int getI2CAddress()

getI2CBus

public int getI2CBus()

blinkOff

public void blinkOff(java.lang.String msg,
            int blinkNumber,
            int blinkDelay)

blinkOn

public void blinkOn(java.lang.String msg,
           int blinkNumber,
           int blinkDelay)

cycle

public void cycle(java.lang.String msg,
         int delay)

cycle

public void cycle(java.lang.String msg)

cycleStop

public void cycleStop()

clear

public void clear()

ledOn

public int ledOn()

ledOff

public int ledOff()

readSensor

public int readSensor()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<package>
  <name>graspdb</name>
  <version>1.1.9</version>
  <description>Grasp Training SQL Database Client Library</description>

  <author email="russell.toris@gmail.com">Russell Toris</author>
  <maintainer email="russell.toris@gmail.com">Russell Toris</maintainer>

  <url type="website">http://ros.org/wiki/graspdb</url>
  <url type="bugtracker">https://github.com/GT-RAIL/rail_pick_and_place/issues</url>
  <url type="repository">https://github.com/GT-RAIL/rail_pick_and_place</url>

  <license>BSD</license>

  <buildtool_depend>catkin</buildtool_depend>

  <build_depend>libpqxx-dev</build_depend>
  <build_depend>geometry_msgs</build_depend>
  <build_depend>roscpp</build_depend>
  <build_depend>rail_pick_and_place_msgs</build_depend>
  <build_depend>roscpp_serialization</build_depend>
  <build_depend>sensor_msgs</build_depend>
  <build_depend>tf2</build_depend>

  <run_depend>libpqxx-dev</run_depend>
  <run_depend>geometry_msgs</run_depend>
  <run_depend>roscpp</run_depend>
  <run_depend>rail_pick_and_place_msgs</run_depend>
  <run_depend>roscpp_serialization</run_depend>
  <run_depend>sensor_msgs</run_depend>
  <run_depend>tf2</run_depend>
</package>


text:
export function drink() {
  return 'compote';
}


text:
<?php

use Kris\LaravelFormBuilder\Fields\ChoiceType;
use Kris\LaravelFormBuilder\Fields\SelectType;
use Kris\LaravelFormBuilder\Form;

class ChoiceTypeTest extends FormBuilderTestCase
{
    /** @test */
    public function it_creates_choice_as_select()
    {
        $options = [
            'attr' => ['class' => 'choice-class'],
            'choices' => ['yes' => 'Yes', 'no' => 'No'],
            'selected' => 'yes'
        ];

        $choice = new ChoiceType('some_choice', 'choice', $this->plainForm, $options);

        $choice->render();

        $this->assertEquals(1, count($choice->getChildren()));

        $this->assertEquals('yes', $choice->getOption('selected'));
    }

    /** @test */
    public function it_creates_choice_as_checkbox_list()
    {
        $options = [
            'attr' => ['class' => 'choice-class-something'],
            'choices' => [1 => 'monday', 2 => 'tuesday'],
            'selected' => 'tuesday',
            'multiple' => true,
            'expanded' => true
        ];

        $choice = new ChoiceType('some_choice', 'choice', $this->plainForm, $options);

        $choice->render();

        $this->assertEquals(2, count($choice->getChildren()));

        $this->assertEquals('tuesday', $choice->getOption('selected'));

        $this->assertContainsOnlyInstancesOf('Kris\LaravelFormBuilder\Fields\CheckableType', $choice->getChildren());
    }

    /** @test */
    public function it_creates_choice_as_radio_buttons()
    {
        $options = [
            'attr' => ['class' => 'choice-class-something'],
            'choices' => [1 => 'yes', 2 => 'no'],
            'selected' => 'no',
            'expanded' => true
        ];

        $choice = new ChoiceType('some_choice', 'choice', $this->plainForm, $options);

        $choice->render();

        $this->assertEquals(2, count($choice->getChildren()));

        $this->assertInstanceOf(
            'Kris\LaravelFormBuilder\Fields\CheckableType',
            $choice->getChild(1)
        );

        $this->assertEquals('no', $choice->getOption('selected'));

        $this->assertContainsOnlyInstancesOf('Kris\LaravelFormBuilder\Fields\CheckableType', $choice->getChildren());
    }
}


text:
<?php
/**
 * Fake SOAP controller for unit tests
 * Handle SOAP client requests & generate WSDL.
 *
 * NOTE:
 * This is a fake controller used only for generating WSDL files.
 * Some functionlities are here as an example and may not be fully functional.
 *
 * Sample call:
 *   $client = new SoapClient('http://1.2.3.4/index.php?r=soap');
 *    $response = $client->connect();
 */
class SoapController extends CController implements IWebServiceProvider
{

    const LOGNAME = 'soap';

    public function actions()
    {

        return array(
            // remap default action "index" to be a SOAP action
            'index' => array(
                'class'    => 'WebServiceAction',
                'classMap' => array(
                    'SoapPovCalculationInput',
                    'SoapPovCalculationOutput',
                ),
            ),
        );
    }

    /**
     * Preprocess actions before calling SOAP action.
     * This method must implement interface's abstract method.
     *
     * @param mixed $service
     */
    public function beforeWebMethod($service)
    {

        // do whatever stuff before executing the action ...
        return true;
    }

    /**
     * Postprocess actions after SOAP action executed.
     * This method must implement interface's abstract method.
     *
     * @param mixed $service
     */
    public function afterWebMethod($service)
    {

        // do whatever stuff after executing the action ...
        return true;
    }

    /**
     * Return TRUE if the SOAP user is authorized.
     */
    protected function isAuthorized($user, $passwordHashed, $action)
    {

        // load allowed users..
        $users = array('tester123' => 'passwordHashed123');

        if (isset($users[$user]) && $passwordHashed == $users[$user]) {
            /**
             * @var CHttpRequest
             */
            $request = Yii::app()->request;
            $url     = $request->getHostInfo() . $request->getUrl();
            Log::write('[' . $user . '] => [' . $action . '] Granted access via [' . $url . ']', self::LOGNAME);
            return true;
        }

        Log::write('[' . $user . '] => [' . $action . '] Failed login with [' . $passwordHashed . ']', self::LOGNAME);
        return false;
    }

    /**
     * Check connection to soap server and return current timestamp on success. No authorization required - used simply for seting up the connection via proxy, firewall, http authentication etc...
     *
     * @return string Current timestamp dd.mm.YYYY HH:ii:ss
     * @soap
     */
    public function connect()
    {

        $request = Yii::app()->request;
        $url     = $request->getHostInfo() . $request->getUrl();
        Log::write('[' . __FUNCTION__ . '] OK - Connection succesfull via [' . $url . ']', self::LOGNAME);
        return 'OK - connection succesfull at [' . date('d.m.Y H:i:s') . ']';
    }

    /**
     * Return some calculation results for supplied input parameters.
     *
     * @param string                  Authorized login username
     * @param string                  Authorized login password
     * @param SoapPovCalculationInput Calculation input object
     *
     * @return SoapPovCalculationOutput Calculation output object
     * @soap
     */
    public function calculatePov($user, $password, $input)
    {

        if (!$this->isAuthorized($user, $password, __FUNCTION__)) {
            throw new SoapFault(null, 'Unauthorized access [' . __FUNCTION__ . ']!');
        }

        $calc = new SoapPovCalculation($input);
        $calc->setPartner($user);
        $output = $calc->calculate();

        return $output;
    }

}


text:
<?php
/**
* BaseController.php
* Base controller.
* @version    151123:6
* @author     karminski <code.karminski@outlook.com>
*
* @changelogs
*             151123:6 REFACTORY.
*             151024:5 REFACTORY.
*             150824:4 ADD isProcessNumberOverLimit().
*             150811:3 CHANGE input method.
*             150609:2 ADD debugSwitch().
*             150520:1 INIT baseController.
*/

namespace SaltFish;

/**
 * abstract class BaseController
 */
abstract class BaseController{

    public $_log;
    public $_feedback;

    /**
     * [__construct description]
     */
    public function __construct(){
        $this->debugSwitch();
        $this->initRequirements();
        $this->initLog();
        $this->initFeedback();
    }

    /**
     * [debugSwitch description]
     * This function set debug info.
     * @param  null
     * @return null
     */
    public function debugSwitch(){
        if(!defined(DEBUG)){
            define(DEBUG, false);
        }
        if(DEBUG){
            ini_set('display_errors', 1);
            error_reporting(E_ALL);
        }
    }

    /**
     * [initRequirements description]
     * This function load main config and all necessary files.
     * @param null
     * @return null
     */
    public function initRequirements(){
        // init config
        require(dirname(__FILE__).'/../lib/base/AutoRequire.php');
        $conf = require(dirname(__FILE__).'/../config/main.config.php');
        Config::importMainConfig($conf);
        // load all necessary files
        $class_name = get_class($this);
        $config = AutoRequire::headerArray("{$class_name}.requirements");
        AutoRequire::classes($config);
    }

    /**
     * [initLog description]
     * This function init log address and echo settings.
     * @param  null
     * @return null
     */
    public function initLog(){
        $logConfig = Config::get('log');
        Log::setLogAddress($logConfig['address'], PROCESS_NAME, $logConfig['split']);
        if(DEBUG){
            Log::setEchoSwitch(Log::ECHO_THE_LOG);
        }
    }

    /**
     * [initFeedback description]
     * @return [type] [description]
     */
    public function initFeedback(){
        $this->_feedback = new Feedback();
        $this->_feedback->setOutputFormat($this->output_format);
        return;
    }

    /**
     * [fetchInput description]
     * @param  [type] &$inputException [description]
     * @return [type]                  [description]
     */
    public function fetchInput(&$inputException){
        $inputIsOk = Input::getInputByParams(
            $this->input_method, $this->input_param, $this->input, $inputException
        );
        // check callback
        if(!empty($input['callback'])){
            $this->output_format = Feedback::FORMAT_JSONP;
        }
        // gen feeedback
        if(!$inputIsOk) return false;
        return true;
    }

    /**
     * [run description]
     * @return [type] [description]
     */
    public abstract function run();

}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';

import Button from '../src';

describe('<Button /> component', function() {

  it('should button exist', function() {
    let _instance = ReactTestUtils.renderIntoDocument(<Button />);
    expect(ReactTestUtils.isCompositeComponent(_instance)).toBeTruthy();
  });

});


text:
package org.fusesource.hawtdispatch.netty;

import io.netty.channel.*;
import org.fusesource.hawtdispatch.Dispatch;
import org.fusesource.hawtdispatch.DispatchQueue;
import org.fusesource.hawtdispatch.DispatchSource;

import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Abstract base class for {@link Channel} implementations that use
 * HawtDispatch.
 *
 * @author Norman Maurer
 */
abstract class HawtAbstractChannel extends AbstractChannel {

    protected volatile SelectableChannel ch;

    /**
     * The future of the current connection attempt.  If not null, subsequent
     * connection attempts will fail.
     */
    private ChannelPromise connectPromise;
    private ScheduledFuture<?> connectTimeoutFuture;
    private ConnectException connectTimeoutException;
    /**
     * Creates a new instance.
     *
     * @param id
     *        the unique non-negative integer ID of this channel.
     *        Specify {@code null} to auto-generate a unique negative integer
     *        ID.
     * @param parent
     *        the parent of this channel. {@code null} if there's no parent.
     * @param ch
     *        the {@link SocketChannel} which will handle the IO or {@code null} if not created yet.
     */
    protected HawtAbstractChannel(Channel parent, Integer id, SelectableChannel ch) {
        super(parent, id);
        this.ch = ch;
    }

    @Override
    public InetSocketAddress localAddress() {
        return (InetSocketAddress) super.localAddress();
    }

    @Override
    public InetSocketAddress remoteAddress() {
        return (InetSocketAddress) super.remoteAddress();
    }

    /**
     * Return the underlying {@link SocketChannel}. Be aware this should only be called after it was set as
     * otherwise it will throw an {@link IllegalStateException}.
     */
    protected SelectableChannel javaChannel() {
        if (ch == null) {
            throw new IllegalStateException("Try to access Channel before eventLoop was registered");
        }
        return ch;
    }

    @Override
    public boolean isOpen() {
        if (ch == null) {
            return true;
        }
        return ch.isOpen();
    }

    @Override
    protected boolean isCompatible(EventLoop loop) {
        return loop instanceof HawtEventLoop;
    }

    @Override
    protected AbstractUnsafe newUnsafe() {
        return new HawtUnsafe();
    }

    protected final DispatchSource createSource(int op) {
        return Dispatch.createSource(javaChannel(), op, getDispatchQueue());
    }

    public DispatchQueue getDispatchQueue() {
        return ((HawtEventLoop) eventLoop()).queue();
    }

    /**
     * Connect to the remote peer using the given localAddress if one is specified or {@code null} otherwise.
     */
    protected abstract boolean doConnect(SocketAddress remoteAddress,
            SocketAddress localAddress) throws Exception;

    /**
     * Finish the connect
     */
    protected abstract void doFinishConnect() throws Exception;

    @Override
    protected void doClose() throws Exception {
        if (connectTimeoutFuture != null) {
            connectTimeoutFuture.cancel(false);
        }
    }

    final class HawtUnsafe extends AbstractUnsafe {

        @Override
        public void connect(
                final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) {
            if (eventLoop().inEventLoop()) {
                if (!ensureOpen(promise)) {
                    return;
                }
                try {
                    if (connectPromise != null) {
                        throw new IllegalStateException("connection attempt already made");
                    }

                    boolean wasActive = isActive();
                    if (doConnect(remoteAddress, localAddress)) {
                        promise.setSuccess();
                        if (!wasActive && isActive()) {
                            pipeline().fireChannelActive();
                        }
                    } else {
                        connectPromise = promise;

                        // Schedule connect timeout.
                        int connectTimeoutMillis = config().getConnectTimeoutMillis();
                        if (connectTimeoutMillis > 0) {
                            connectTimeoutFuture = eventLoop().schedule(new Runnable() {
                                @Override
                                public void run() {
                                    if (connectTimeoutException == null) {
                                        connectTimeoutException = new ConnectException("connection timed out");
                                    }
                                    ChannelPromise connectPromise = HawtAbstractChannel.this.connectPromise;
                                    if (connectPromise != null && connectPromise.tryFailure(connectTimeoutException)) {
                                        close(voidFuture());
                                    }
                                }
                            }, connectTimeoutMillis, TimeUnit.MILLISECONDS);
                        }
                    }
                } catch (Throwable t) {
                    promise.setFailure(t);
                    closeIfClosed();
                }
            } else {
                eventLoop().execute(new Runnable() {
                    @Override
                    public void run() {
                        connect(remoteAddress, localAddress, promise);
                    }
                });
            }
        }

        /**
         * Finish connect operation
         */
        public void finishConnect() {
            assert eventLoop().inEventLoop();
            assert connectPromise != null;
            try {
                boolean wasActive = isActive();
                doFinishConnect();
                connectPromise.setSuccess();
                if (!wasActive && isActive()) {
                    pipeline().fireChannelActive();
                }
            } catch (Throwable t) {
                connectPromise.tryFailure(t);
                closeIfClosed();
            } finally {
                connectTimeoutFuture.cancel(false);
                connectPromise = null;
            }
        }
    }
}


text:
layout: layout.pug
navigationTitle:
excerpt:
title: Managing
menuWeight: 60

---

# Updating Configuration

You can make changes to the service after it has been launched. Configuration management is handled by the scheduler process, which in turn handles deploying DC/OS Elastic Service itself.

After making a change, the scheduler will be restarted and will automatically deploy any detected changes to the service, one node at a time. For example, a given change will first be applied to `_NODEPOD_-0`, then `_NODEPOD_-1`, and so on.

Nodes are configured with a "Readiness check" to ensure that the underlying service appears to be in a healthy state before continuing with applying a given change to the next node in the sequence. However, this basic check is not foolproof and reasonable care should be taken to ensure that a given configuration change will not negatively affect the behavior of the service.

Some changes, such as decreasing the number of nodes or changing volume requirements, are not supported after initial deployment. See [Limitations](#limitations).

The instructions below describe how to update the configuration for a running DC/OS service.

## Enterprise DC/OS 1.10

Enterprise DC/OS 1.10 introduces a convenient command line option that allows for easier updates to a service's configuration, as well as allowing users to inspect the status of an update, to pause and resume updates, and to restart or complete steps if necessary.

### Prerequisites

+ Enterprise DC/OS 1.10 or newer.
+ Service with a version greater than 2.0.0-x.
+ [The DC/OS CLI](https://docs.mesosphere.com/latest/cli/install/) installed and available.
+ The service's subcommand available and installed on your local machine.
  + You can install just the subcommand CLI by running `dcos package install --cli beta-elastic`.
  + If you are running an older version of the subcommand CLI that doesn't have the `update` command, uninstall and reinstall your CLI.
    ```bash
    dcos package uninstall --cli beta-elastic
    dcos package install --cli beta-elastic
    ```

### Preparing configuration

If you installed this service with Enterprise DC/OS 1.10, you can fetch the full configuration of a service (including any default values that were applied during installation). For example:

```bash
$ dcos beta-elastic --name="elastic" describe > options.json
```

Make any configuration changes to this `options.json` file.

If you installed this service with a prior version of DC/OS, this configuration will not have been persisted by the the DC/OS package manager. You can instead use the `options.json` file that was used when [installing the service](#initial-service-configuration).

Note: You need to specify all configuration values in the `options.json` file when performing a configuration update. Any unspecified values will be reverted to the default values specified by the DC/OS service. See the "Recreating `options.json`" section below for information on recovering these values.

#### Recreating `options.json` (optional)

If the `options.json` from when the service was last installed or updated is not available, you will need to manually recreate it using the following steps.

First, we'll fetch the default application's environment, current application's environment, and the actual template that maps config values to the environment:

1. Ensure you have [jq](https://stedolan.github.io/jq/) installed.
1. Set the service name that you're using, for example:
```bash
$ SERVICE_NAME=elastic
```
1. Get the version of the package that is currently installed:
```bash
$ PACKAGE_VERSION=$(dcos package list | grep $SERVICE_NAME | awk '{print $2}')
```
1. Then fetch and save the environment variables that have been set for the service:
```bash
$ dcos marathon app show $SERVICE_NAME | jq .env > current_env.json
```
1. To identify those values that are custom, we'll get the default environment variables for this version of the service:
```bash
$ dcos package describe --package-version=$PACKAGE_VERSION --render --app $SERVICE_NAME | jq .env > default_env.json
```
1. We'll also get the entire application template:
```bash
$ dcos package describe $SERVICE_NAME --app > marathon.json.mustache
```

Now that you have these files, we'll attempt to recreate the `options.json`.

1. Use JQ and `diff` to compare the two:
```bash
$ diff <(jq -S . default_env.json) <(jq -S . current_env.json)
```
1. Now compare these values to the values contained in the `env` section in application template:
```bash
$ less marathon.json.mustache
```
1. Use the variable names (e.g. `{{service.name}}`) to create a new `options.json` file as described in [Initial service configuration](#initial-service-configuration).

### Starting the update

Once you are ready to begin, initiate an update using the DC/OS CLI, passing in the updated `options.json` file:

```bash
$ dcos beta-elastic --name="elastic" update start --options=options.json
```

You will receive an acknowledgement message and the DC/OS package manager will restart the Scheduler in Marathon.

See [Advanced update actions](#advanced-update-actions) for commands you can use to inspect and manipulate an update after it has started.

## Open Source DC/OS, Enterprise DC/OS 1.9 and Earlier

If you do not have Enterprise DC/OS 1.10 or later, the CLI commands above are not available. For Open Source DC/OS of any version, or Enterprise DC/OS 1.9 and earlier, you can perform changes from the DC/OS GUI.

To make configuration changes via scheduler environment updates, perform the following steps:
1. Visit <dcos-url> to access the DC/OS web interface.
1. Navigate to `Services` and click on the service to be configured (default `elastic`).
1. Click `Edit` in the upper right. On DC/OS 1.9.x, the `Edit` button is in a menu made up of three dots.
1. Navigate to `Environment` (or `Environment variables`) and search for the option to be updated.
1. Update the option value and click `Review and run` (or `Deploy changes`).
1. The Scheduler process will be restarted with the new configuration and will validate any detected changes.
1. If the detected changes pass validation, the relaunched Scheduler will deploy the changes by sequentially relaunching affected tasks as described above.

To see a full listing of available options, run `dcos package describe --config beta-elastic` in the CLI, or browse the Elastic install dialog in the DC/OS web interface.

# Add a Data/Ingest/Coordinator Node
Increase the `DATA_NODE_COUNT`/`INGEST_NODE_COUNT`/`COORDINATOR_NODE_COUNT` value from the DC/OS dashboard as described in the Configuring section. This creates an update plan as described in that section. An additional node will be added as the last step of that plan.

# Node Info

Comprehensive information is available about every node.  To list all nodes:

```bash
dcos beta-elastic --name=<service-name> pod list
```

To view information about a node, run the following command from the CLI.
```bash
$ dcos beta-elastic --name=<service-name> pod info <node-id>
```

For example:
```bash
$ dcos beta-elastic --name=<service-name> pod info master-0
```

# Node Status
Similarly, the status for any node may also be queried.

```bash
$ dcos beta-elastic --name=<service-name> pod info <node-id>
```

For example:

```bash
$ dcos beta-elastic pod info data-0
```

# Pause a Node

Pausing a node relaunches it in an idle command state. This allows the operator to debug the contents of the node, possibly making changes to fix problems. While these problems are often fixed by just replacing the node, there may be cases where an in-place repair or other operation is needed.

For example:
- A node which crashes immediately upon starting may need additional work to be performed.
- Some services may _require_ that certain repair operations be performed manually when the task itself isn't running.
Being able to put the node in an offline but accessible state makes it easier to resolve these situations.

After the node has been paused, it may be started again, at which point it will be restarted and will resume running task(s) where it left off.

Here is an example session where an `index-1` node is crash looping due to some corrupted data in a persistent volume. The operator pauses the `index-1` node, then uses `task exec` to repair the index. Following this, the operator starts the node and it resumes normal operation:

```bash
$ dcos beta-elastic debug pod pause index-1
{
  "pod": "index-1",
  "tasks": [
    "index-1-agent",
    "index-1-node"
  ]
}

$ dcos beta-elastic pod status
myservice
├─ index
│  ├─ index-0
│  │  ├─ index-0-agent (COMPLETE)
│  │  └─ index-0-node (COMPLETE)
│  └─ index-1
│     ├─ index-1-agent (PAUSING)
│     └─ index-1-node (PAUSING)
└─ data
   ├─ data-0
   │  └─ data-0-node (COMPLETE)
   └─ data-1
      └─ data-1-node (COMPLETE)

... repeat "pod status" until index-1 tasks are PAUSED ...

$ dcos task exec --interactive --tty index-1-node /bin/bash
index-1-node$ ./repair-index && exit

$ dcos beta-elastic debug pod resume index-1
{
  "pod": "index-1",
  "tasks": [
    "index-1-agent",
    "index-1-node"
  ]
}

$ dcos beta-elastic pod status
myservice
├─ index
│  ├─ index-0
│  │  ├─ index-0-agent (RUNNING)
│  │  └─ index-0-node (RUNNING)
│  └─ index-1
│     ├─ index-1-agent (STARTING)
│     └─ index-1-node (STARTING)
└─ data
   ├─ data-0
   │  └─ data-0-node (RUNNING)
   └─ data-1
      └─ data-1-node (RUNNING)

... repeat "pod status" until index-1 tasks are RUNNING ...
```

In the above example, all tasks in the node were being paused and started, but it's worth noting that the commands also support pausing and starting individual tasks within a node. For example, `dcos beta-elastic debug pod pause index-1 -t agent` will pause only the `agent` task within the `index-1` node.

# Upgrading Service Version

The instructions below show how to safely update one version of DC/OS Elastic Service to the next.

## Viewing available versions

The `update package-versions` command allows you to view the versions of a service that you can upgrade or downgrade to. These are specified by the service maintainer and depend on the semantics of the service (i.e. whether or not upgrades are reversal).

For example, run:
```bash
$ dcos beta-elastic update package-versions
```

## Upgrading or downgrading a service

1. Before updating the service itself, update its CLI subcommand to the new version:
```bash
$ dcos package uninstall --cli beta-elastic
$ dcos package install --cli beta-elastic --package-version="1.1.6-5.0.7"
```
1. Once the CLI subcommand has been updated, call the update start command, passing in the version. For example, to update DC/OS Elastic Service to version `1.1.6-5.0.7`:
```bash
$ dcos beta-elastic update start --package-version="1.1.6-5.0.7"
```

If you are missing mandatory configuration parameters, the `update` command will return an error. To supply missing values, you can also provide an `options.json` file (see [Updating configuration](#updating-configuration)):
```bash
$ dcos beta-elastic update start --options=options.json --package-version="1.1.6-5.0.7"
```

See [Advanced update actions](#advanced-update-actions) for commands you can use to inspect and manipulate an update after it has started.

# Advanced update actions

The following sections describe advanced commands that be used to interact with an update in progress.

## Monitoring the update

Once the Scheduler has been restarted, it will begin a new deployment plan as individual pods are restarted with the new configuration. Depending on the high availability characteristics of the service being updated, you may experience a service disruption.

You can query the status of the update as follows:

```bash
$ dcos beta-elastic update status
```

If the Scheduler is still restarting, DC/OS will not be able to route to it and this command will return an error message. Wait a short while and try again. You can also go to the Services tab of the DC/OS GUI to check the status of the restart.

## Pause

To pause an ongoing update, issue a pause command:

```bash
$ dcos beta-elastic update pause
```

You will receive an error message if the plan has already completed or has been paused. Once completed, the plan will enter the `WAITING` state.

## Resume

If a plan is in a `WAITING` state, as a result of being paused or reaching a breakpoint that requires manual operator verification, you can use the `resume` command to continue the plan:

```bash
$ dcos beta-elastic update resume
```

You will receive an error message if you attempt to `resume` a plan that is already in progress or has already completed.

## Force Complete

In order to manually "complete" a step (such that the Scheduler stops attempting to launch a task), you can issue a `force-complete` command. This will instruct to Scheduler to mark a specific step within a phase as complete. You need to specify both the phase and the step, for example:

```bash
$ dcos beta-elastic update force-complete service-phase service-0:[node]
```

## Force Restart

Similar to force complete, you can also force a restart. This can either be done for an entire plan, a phase, or just for a specific step.

To restart the entire plan:
```bash
$ dcos beta-elastic update force-restart
```

Or for all steps in a single phase:
```bash
$ dcos beta-elastic update force-restart service-phase
```

Or for a specific step within a specific phase:
```bash
$ dcos beta-elastic update force-restart service-phase service-0:[node]
```