text:
/*This file is prepared for Doxygen automatic documentation generation.*/
/*! \file *********************************************************************
 *
 * \brief Standard board header file.
 *
 * This file includes the appropriate board header file according to the
 * defined board (parameter BOARD).
 *
 * - Compiler:           IAR EWAVR/IAR EWAVR32 and GNU GCC for AVR or AVR32
 * - Supported devices:  All AVR devices can be used.
 * - AppNote:
 *
 * \author               Atmel Corporation: http://www.atmel.com \n
 *                       Support and FAQ: http://support.atmel.no/
 *
 ******************************************************************************/

/* Copyright (c) 2009 Atmel Corporation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. The name of Atmel may not be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * 4. This software may only be redistributed and used in connection with an Atmel
 * AVR product.
 *
 * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
 *
 */

#ifndef _BOARD_H_
#define _BOARD_H_

#include "compiler.h"

#ifdef __cplusplus
extern "C" {
#endif

/*! \name Base Boards
 */
//! @{
#define EVK1100               1   //!< AT32UC3A EVK1100 board.
#define EVK1101               2   //!< AT32UC3B EVK1101 board.
#define UC3C_EK               3   //!< AT32UC3C UC3C_EK board.
#define EVK1104               4   //!< AT32UC3A3 EVK1104 board.
#define EVK1105               5   //!< AT32UC3A EVK1105 board.
#define STK600_RCUC3L0        6   //!< STK600 RCUC3L0 board.
#define UC3L_EK               7   //!< AT32UC3L-EK board.
#define XPLAIN                8   //!< ATxmega128A1 Xplain board.
#define STK600_RC064X         10  //!< ATxmega256A3 STK600 board.
#define STK600_RC100X         11  //!< ATxmega128A1 STK600 board.
#define AVR_HIFI_AUDIO        12  //!< AT32UC3A AVR HiFi Audio board.
#define UC3_A3_XPLAINED       13  //!< ATUC3A3 UC3-A3 Xplained board.
#define UC3_L0_XPLAINED       15  //!< ATUC3L0 UC3-L0 Xplained board.
#define STK600_RCUC3D         16  //!< STK600 RCUC3D board.
#define STK600_RCUC3C0        17  //!< STK600 RCUC3C board.
#define XMEGA_A1_XPLAINED     19  //!< ATxmega128A1 Xplain-A1 board.
#define UC3_L0_XPLAINED_BC    22  //!< ATUC3L0 UC3-L0 Xplained board controller board
#define MEGA1284P_XPLAINED_BC 23  //!< ATmega1284P-Xplained board controller board
#define STK600_RC044X         24  //!< STK600 with RC044X routing card board.
#define STK600_RCUC3B         25  //!< STK600 RCUC3B board.
#define UC3_L0_QT600          26  //!< QT600 UC3L0 MCU board.
#define USER_BOARD            99  //!< User-reserved board (if any).
#define DUMMY_BOARD          100  //!< Dummy board to support board-independent applications (e.g. bootloader)

//! @}

/*! \name Extension Boards
 */
//! @{
#define EXT1102                      1  //!< AT32UC3B EXT1102 board
#define MC300                        2  //!< AT32UC3 MC300 board
#define SENSORS_XPLAINED_INERTIAL_1  3  //!< Xplained inertial sensor board 1
#define SENSORS_XPLAINED_INERTIAL_2  4  //!< Xplained inertial sensor board 2
#define SENSORS_XPLAINED_PRESSURE_1  5  //!< Xplained pressure sensor board
#define SENSORS_XPLAINED_LIGHT_1     6  //!< Xplained light & proximity sensor board
#define SENSORS_XPLAINED_INERTIAL_A1 7  //!< Xplained inertial sensor board "A"

#define USER_EXT_BOARD              99  //!< User-reserved extension board (if any).
//! @}

#if BOARD == EVK1100
  #include "evk1100/evk1100.h"
#elif BOARD == EVK1101
  #include "evk1101/evk1101.h"
#elif BOARD == UC3C_EK
  #include "uc3c_ek/uc3c_ek.h"
#elif BOARD == EVK1104
  #include "evk1104/evk1104.h"
#elif BOARD == EVK1105
  #include "evk1105/evk1105.h"
#elif BOARD == STK600_RCUC3L0
  #include "stk600/rcuc3l0/stk600_rcuc3l0.h"
#elif BOARD == UC3L_EK
  #include "uc3l_ek/uc3l_ek.h"
#elif BOARD == XPLAIN
  #include "xplain/xplain.h"
#elif BOARD == STK600_RC044X
  #include "stk600/rc044x/stk600_rc044x.h"
#elif BOARD == STK600_RC064X
  #include "stk600/rc064x/stk600_rc064x.h"
#elif BOARD == STK600_RC100X
  #include "stk600/rc100x/stk600_rc100x.h"
#elif BOARD == AVR_HIFI_AUDIO
  #include "avr_hifi_audio/avr_hifi_audio.h"
#elif BOARD == UC3_A3_XPLAINED
  #include "uc3_a3_xplained/uc3_a3_xplained.h"
#elif BOARD == UC3_L0_XPLAINED
  #include "uc3_l0_xplained/uc3_l0_xplained.h"
#elif BOARD == STK600_RCUC3B
  #include "stk600/rcuc3b/stk600_rcuc3b.h"
#elif BOARD == STK600_RCUC3D
  #include "stk600/rcuc3d/stk600_rcuc3d.h"
#elif BOARD == STK600_RCUC3C0
  #include "stk600/rcuc3c0/stk600_rcuc3c0.h"
#elif BOARD == XMEGA_A1_XPLAINED
  #include "xmega_a1_xplained/xmega_a1_xplained.h"
#elif BOARD == UC3_L0_XPLAINED_BC
  #include "uc3_l0_xplained_bc/uc3_l0_xplained_bc.h"
#elif BOARD == MEGA1284P_XPLAINED_BC
  #include "mega1284p_xplained_bc/mega1284p_xplained_bc.h"
#elif BOARD == UC3_L0_QT600
  #include "uc3_l0_qt600/uc3_l0_qt600.h"
#elif BOARD == USER_BOARD
  // User-reserved area: #include the header file of your board here (if any).
  #include "user_board.h"
#elif BOARD == DUMMY_BOARD
  #include "dummy/dummy_board.h"
#else
  #error No known AVR board defined
#endif

#if (defined EXT_BOARD)
  #if EXT_BOARD == MC300
    #include "mc300/mc300.h"
  #elif (EXT_BOARD == SENSORS_XPLAINED_INERTIAL_1)  || \
        (EXT_BOARD == SENSORS_XPLAINED_INERTIAL_2)  || \
        (EXT_BOARD == SENSORS_XPLAINED_INERTIAL_A1) || \
        (EXT_BOARD == SENSORS_XPLAINED_PRESSURE_1)  || \
        (EXT_BOARD == SENSORS_XPLAINED_LIGHT_1)
    #include "sensors_xplained/sensors_xplained.h"
  #elif EXT_BOARD == USER_EXT_BOARD
    // User-reserved area: #include the header file of your extension board here
    // (if any).
  #endif
#endif

#if (defined(__GNUC__) && defined(__AVR32__)) || (defined(__ICCAVR32__) || defined(__AAVR32__))
#ifdef __AVR32_ABI_COMPILER__ // Automatically defined when compiling for AVR32, not when assembling.

/*! \brief This function initializes the board target resources
 *
 * This function should be called to ensure proper initialization of the target
 * board hardware connected to the part.
 */
extern void board_init(void);

#endif  // #ifdef __AVR32_ABI_COMPILER__
#else
/*! \brief This function initializes the board target resources
 *
 * This function should be called to ensure proper initialization of the target
 * board hardware connected to the part.
 */
extern void board_init(void);
#endif

#ifdef __cplusplus
}
#endif

#endif  // _BOARD_H_


text:
<?php get_header(); ?>

            <?php /* The loop */ ?>
            <?php while ( have_posts() ) { the_post(); ?>
            <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                <?php edit_post_link( __( 'Edit', ZEETEXTDOMAIN ), '', '

' ); ?>
                <?php if ( has_post_thumbnail() && ! post_password_required() ) { ?>

                    <?php the_post_thumbnail(); ?>

                <?php } ?>

                    <?php the_content(); ?>
                    <?php zee_link_pages(); ?>

            <?php } ?>

<?php get_footer();

redpajama_set_name: RedPajamaGithub


text:
//-------------------------------------------------------------------------------
// <copyright file="LogLevel.cs" company="frokonet.ch">
//   Copyright (c) 2014-2017
//
//   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.
// </copyright>
//-------------------------------------------------------------------------------

namespace SimpleDomain.Common.Logging
{
    /// <summary>
    /// Defines the supported log levels
    /// </summary>
    public enum LogLevel
    {
        /// <summary>
        /// The Debug level
        /// </summary>
        Debug,

        /// <summary>
        /// The Info level
        /// </summary>
        Info,

        /// <summary>
        /// The Warning level
        /// </summary>
        Warning,

        /// <summary>
        /// The Error level
        /// </summary>
        Error
    }
}


text:
set(CMAKE_BUILD_TYPE DEBUG)

# Set to TRUE if you wish to use GPU
set(USE_GPU FALSE)

# Set to TRUE if you wish to use MPI
set(USE_MPI FALSE)

# Set to TRUE if you wish to use libpng which is needed only by the Halide benchmarks
set(USE_LIBPNG FALSE)

# Set to TRUE if you wish to use libjpeg which is needed only by the Halide benchmarks
set(USE_LIBJPEG FALSE)

# If USE_MPI is true, you need to the MPI_BUILD_DIR and MPI_NODES path
# Note: This assumes you are using your own installed version of MPI. If your system already
# has a version of openmpi installed, you will have to read the docs to see what the appropriate
# way of launching mpi jobs is. For our testing, we use mpirun.
# Examples:
#set(MPI_BUILD_DIR "/data/scratch/jray/Repositories/tiramisu/3rdParty/openmpi-3.1.2/build/")
#set(MPI_NODES "lanka01,lanka02,lanka03,lanka04,lanka05,lanka06,lanka12,lanka13,lanka14,lanka15")
set(MPI_BUILD_DIR "")
set(MPI_NODES "")

# Intel MKL library path. The specified folder should contain the folders
# include and lib.
# Example:
# set(MKL_PREFIX "/data/scratch/baghdadi/libs/intel/mkl/")
set(MKL_PREFIX "")

# LLVM_CONFIG_BIN: Directory containing llvm-config executable.
set(LLVM_CONFIG_BIN "${CMAKE_SOURCE_DIR}/3rdParty/llvm/prefix/bin/")

# ISL paths
set(ISL_INCLUDE_DIRECTORY "3rdParty/isl/build/include/")
set(ISL_LIB_DIRECTORY "3rdParty/isl/build/lib/")

# Halide Paths
set(HALIDE_SOURCE_DIRECTORY "3rdParty/Halide")
set(HALIDE_LIB_DIRECTORY "3rdParty/Halide/lib")


text:
<!doctype html>

<meta charset="utf-8">

<title>Your title</title>

<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

<link rel="stylesheet" href="css/reveal.min.css">
<link rel="stylesheet" href="css/theme/typesafe.css" id="theme">
<link rel="stylesheet" href="lib/css/idea.css">

##Presentation Title

###Full name

Get It and Learn More

akka.io

letitcrash.com

Akka Tutorials

        Follow @akkateam


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
    /// <summary>
    /// Represents a local variable in a method body.
    /// </summary>
    internal abstract class LocalSymbol : Symbol, ILocalSymbolInternal
    {
        protected LocalSymbol()
        {
        }

        internal abstract LocalDeclarationKind DeclarationKind
        {
            get;
        }

        internal abstract SynthesizedLocalKind SynthesizedKind
        {
            get;
        }

        /// <summary>
        /// Syntax node that is used as the scope designator. Otherwise, null.
        /// </summary>
        internal abstract SyntaxNode ScopeDesignatorOpt { get; }

        internal abstract LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax);

        internal abstract bool IsImportedFromMetadata
        {
            get;
        }

        internal virtual bool CanScheduleToStack => !IsConst && !IsPinned;

        internal abstract SyntaxToken IdentifierToken
        {
            get;
        }

        /// <summary>
        /// Gets the type of this local.
        /// </summary>
        public abstract TypeSymbolWithAnnotations Type
        {
            get;
        }

        /// <summary>
        /// WARN WARN WARN: If you access this via the semantic model, things will break (since the initializer may not have been bound).
        ///
        /// Whether or not this local is pinned (i.e. the type will be emitted with the "pinned" modifier).
        /// </summary>
        /// <remarks>
        /// Superficially, it seems as though this should always be the same as DeclarationKind == LocalDeclarationKind.Fixed.
        /// Unfortunately, when we fix a string expression, it is not the declared local (e.g. char*) but a synthesized temp (string)
        /// that is pinned.
        /// </remarks>
        internal abstract bool IsPinned
        {
            get;
        }

        /// <summary>
        /// Returns false because local variable can't be defined externally.
        /// </summary>
        public sealed override bool IsExtern
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Returns false because local variable can't be sealed.
        /// </summary>
        public sealed override bool IsSealed
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Returns false because local variable can't be abstract.
        /// </summary>
        public sealed override bool IsAbstract
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Returns false because local variable can't be overridden.
        /// </summary>
        public sealed override bool IsOverride
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Returns false because local variable can't be virtual.
        /// </summary>
        public sealed override bool IsVirtual
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Returns false because local variable can't be declared as static in C#.
        /// </summary>
        public sealed override bool IsStatic
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute.
        /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet.
        /// </summary>
        internal sealed override ObsoleteAttributeData ObsoleteAttributeData
        {
            get { return null; }
        }

        /// <summary>
        /// Returns 'NotApplicable' because local variable can't be used outside the member body..
        /// </summary>
        public sealed override Accessibility DeclaredAccessibility
        {
            get
            {
                return Accessibility.NotApplicable;
            }
        }

        /// <summary>
        /// Returns value 'Local' of the <see cref="SymbolKind"/>
        /// </summary>
        public sealed override SymbolKind Kind
        {
            get
            {
                return SymbolKind.Local;
            }
        }

        internal sealed override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument)
        {
            return visitor.VisitLocal(this, argument);
        }

        public sealed override void Accept(CSharpSymbolVisitor visitor)
        {
            visitor.VisitLocal(this);
        }

        public sealed override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor)
        {
            return visitor.VisitLocal(this);
        }

        /// <summary>
        /// Returns true if this local variable was declared in a catch clause.
        /// </summary>
        public bool IsCatch
        {
            get
            {
                return this.DeclarationKind == LocalDeclarationKind.CatchVariable;
            }
        }

        /// <summary>
        /// Returns true if this local variable was declared as "const" (i.e. is a constant declaration).
        /// </summary>
        public bool IsConst
        {
            get
            {
                return this.DeclarationKind == LocalDeclarationKind.Constant;
            }
        }

        /// <summary>
        /// Returns true if the local variable is declared in resource-acquisition of a 'using statement';
        /// otherwise false
        /// </summary>
        /// <example>
        /// <code>
        ///     using (var localVariable = new StreamReader("C:\\Temp\\MyFile.txt")) { ... }
        /// </code>
        /// </example>
        public bool IsUsing
        {
            get
            {
                return this.DeclarationKind == LocalDeclarationKind.UsingVariable;
            }
        }

        /// <summary>
        /// Returns true if the local variable is declared in fixed-pointer-initializer (in unsafe context)
        /// </summary>
        public bool IsFixed
        {
            get
            {
                return this.DeclarationKind == LocalDeclarationKind.FixedVariable;
            }
        }

        /// <summary>
        /// Returns true if this local variable is declared as iteration variable
        /// </summary>
        public bool IsForEach
        {
            get
            {
                return this.DeclarationKind == LocalDeclarationKind.ForEachIterationVariable;
            }
        }

        /// <summary>
        /// Returns the syntax node that declares the variable.
        /// </summary>
        /// <remarks>
        /// All user-defined and long-lived synthesized variables must return a reference to a node that is
        /// tracked by the EnC diffing algorithm. For example, for <see cref="LocalDeclarationKind.CatchVariable"/> variable
        /// the declarator is the <see cref="CatchClauseSyntax"/> node.
        ///
        /// The location of the declarator is used to calculate <see cref="LocalDebugId.SyntaxOffset"/> during emit.
        /// </remarks>
        internal abstract SyntaxNode GetDeclaratorSyntax();

        /// <summary>
        /// Describes whether this represents a modifiable variable. Note that
        /// this refers to the variable, not the underlying value, so if this
        /// variable is a ref-local, the writability refers to ref-assignment,
        /// not assignment to the underlying storage.
        /// </summary>
        internal virtual bool IsWritableVariable
        {
            get
            {
                switch (this.DeclarationKind)
                {
                    case LocalDeclarationKind.Constant:
                    case LocalDeclarationKind.FixedVariable:
                    case LocalDeclarationKind.ForEachIterationVariable:
                    case LocalDeclarationKind.UsingVariable:
                        return false;
                    default:
                        return true;
                }
            }
        }

        /// <summary>
        /// Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous.
        /// True otherwise.
        /// </summary>
        public bool HasConstantValue
        {
            get
            {
                if (!this.IsConst)
                {
                    return false;
                }

                ConstantValue constantValue = this.GetConstantValue(null, null, null);
                return constantValue != null && !constantValue.IsBad; //can be null in error scenarios
            }
        }

        /// <summary>
        /// If IsConst returns true, then returns the constant value of the field or enum member. If IsConst returns
        /// false, then returns null.
        /// </summary>
        public object ConstantValue
        {
            get
            {
                if (!this.IsConst)
                {
                    return null;
                }

                ConstantValue constantValue = this.GetConstantValue(null, null, null);
                return constantValue?.Value; //can be null in error scenarios
            }
        }

        /// <summary>
        /// Returns true if the local symbol was compiler generated.
        /// </summary>
        internal abstract bool IsCompilerGenerated
        {
            get;
        }

        internal abstract ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, DiagnosticBag diagnostics = null);

        internal abstract ImmutableArray<Diagnostic> GetConstantValueDiagnostics(BoundExpression boundInitValue);

        public bool IsRef => RefKind != RefKind.None;

        public abstract RefKind RefKind
        {
            get;
        }

        /// <summary>
        /// Returns the scope to which a local can "escape" ref assignments or other form of aliasing
        /// Makes sense only for locals with formal scopes - i.e. source locals
        /// </summary>
        internal abstract uint RefEscapeScope { get; }

        /// <summary>
        /// Returns the scope to which values of a local can "escape" via ordinary assignments
        /// Makes sense only for ref-like locals with formal scopes - i.e. source locals
        /// </summary>
        internal abstract uint ValEscapeScope { get; }

        /// <summary>
        /// When a local variable's type is inferred, it may not be used in the
        /// expression that computes its value (and type). This property returns
        /// the expression where a reference to an inferred variable is forbidden.
        /// </summary>
        internal virtual SyntaxNode ForbiddenZone => null;

        /// <summary>
        /// The diagnostic code to be reported when an inferred variable is used
        /// in its forbidden zone.
        /// </summary>
        internal virtual ErrorCode ForbiddenDiagnostic => ErrorCode.ERR_VariableUsedBeforeDeclaration;

        #region ILocalSymbol Members

        ITypeSymbol ILocalSymbol.Type
        {
            get
            {
                return this.Type.TypeSymbol;
            }
        }

        bool ILocalSymbol.IsFunctionValue
        {
            get
            {
                return false;
            }
        }

        #endregion

        #region ISymbol Members

        public sealed override void Accept(SymbolVisitor visitor)
        {
            visitor.VisitLocal(this);
        }

        public sealed override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
        {
            return visitor.VisitLocal(this);
        }

        #endregion

        #region ILocalSymbolInternal Members

        SynthesizedLocalKind ILocalSymbolInternal.SynthesizedKind
        {
            get
            {
                return this.SynthesizedKind;
            }
        }

        bool ILocalSymbolInternal.IsImportedFromMetadata
        {
            get
            {
                return this.IsImportedFromMetadata;
            }
        }

        SyntaxNode ILocalSymbolInternal.GetDeclaratorSyntax()
        {
            return this.GetDeclaratorSyntax();
        }

        #endregion
    }
}


text:
'use strict';

let moduleStateValue = 'default';

function setModuleStateValue(value) {
  moduleStateValue = value;
}

function getModuleStateValue() {
  return moduleStateValue;
}

exports.getModuleStateValue = getModuleStateValue;
exports.isRealModule = true;
exports.setModuleStateValue = setModuleStateValue;


text:
package com.lithium.flow.vault;

import static com.google.common.base.Preconditions.checkNotNull;

import com.lithium.flow.access.Access;
import com.lithium.flow.access.Prompt;
import com.lithium.flow.access.prompts.DialogPrompt;
import com.lithium.flow.access.prompts.MemoryPrompt;
import com.lithium.flow.access.prompts.NoPrompt;
import com.lithium.flow.access.prompts.SyncPrompt;
import com.lithium.flow.config.Config;
import com.lithium.flow.config.exception.IllegalConfigException;
import com.lithium.flow.ioc.Locator;
import com.lithium.flow.shell.ShellAccess;
import com.lithium.flow.shell.Shells;
import com.lithium.flow.store.FileStore;
import com.lithium.flow.store.MemoryStore;
import com.lithium.flow.store.Store;
import com.lithium.flow.util.Logs;

import java.io.File;
import java.util.Map;

import javax.annotation.Nonnull;

import org.slf4j.Logger;

import com.google.common.collect.Maps;

/**
 * @author Matt Ayres
 */
public class Vaults {
	private static final Logger log = Logs.getLogger();
	private static final Map<String, Store> stores = Maps.newConcurrentMap();

	@Nonnull
	public static Access buildAccess(@Nonnull Locator locator) {
		checkNotNull(locator);
		return buildAccess(locator.getInstance(Config.class), locator.getInstance(Vault.class));
	}

	@Nonnull
	public static Access buildAccess(@Nonnull Config config) {
		return buildAccess(config, buildVault(config));
	}

	@Nonnull
	public static Access buildAccess(@Nonnull Config config, @Nonnull Vault vault) {
		checkNotNull(config);
		checkNotNull(vault);

		if (!config.getBoolean("vault", true)) {
			return Shells.buildAccess(config);
		}

		Prompt prompt = config.getBoolean("vault.prompt", true) ? new DialogPrompt("Vault") : new NoPrompt();
		prompt = new MemoryPrompt(prompt);
		prompt = new VaultPrompt(prompt, vault);
		prompt = new SyncPrompt(prompt);

		Access access = new ShellAccess(config, prompt);
		access = new VaultAccess(access, vault);
		return access;
	}

	@Nonnull
	public static Vault buildVault(@Nonnull Locator locator) {
		checkNotNull(locator);
		return buildVault(locator.getInstance(Config.class));
	}

	@Nonnull
	public static Vault buildVault(@Nonnull Config config) {
		checkNotNull(config);

		String vault = config.getString("vault", "file");
		switch (vault) {
			case "file":
				return buildFileVault(config);

			case "ssm":
				return new AmazonVault(config);

			default:
				throw new IllegalConfigException("vault", vault, "string", null);
		}
	}

	@Nonnull
	private static Vault buildFileVault(@Nonnull Config config) {
		checkNotNull(config);

		String path = config.getString("vault.path", System.getProperty("user.home") + "/.vault");
		File file = new File(path);
		log.info("vault path: {}", path);

		Store store;
		if (file.exists()) {
			store = new FileStore(file);
			if (config.getBoolean("vault.delete", false)) {
				log.info("deleting vault");
				store = new MemoryStore(store);
				if (!file.delete()) {
					throw new RuntimeException("failed to delete vault");
				}
				if (config.getBoolean("vault.memory", false)) {
					stores.put(path, store);
				}
			}
		} else if (stores.containsKey(path)) {
			store = stores.get(path);
		} else {
			store = new FileStore(file);
		}

		Vault vault = new SecureVault(config, store);
		if (config.getBoolean("vault.agent", true)) {
			log.info("starting vault agent");
			vault = new AgentVault(vault, store);
		}
		if (config.getBoolean("vault.env", false)) {
			if (!vault.unlock(System.getenv("VAULT_PASSWORD"))) {
				throw new RuntimeException("failed to unlock vault with env: VAULT_PASSWORD");
			}
		}
		if (config.getBoolean("vault.property", false)) {
			if (!vault.unlock(System.getProperty("vault.password"))) {
				throw new RuntimeException("failed to unlock vault with property: vault.password");
			}
		}
		return vault;
	}
}


text:
package com.velvetPearl.lottery.dataAccess.models;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.TreeMap;

/**
 * Created by Andreas "denDAY" Stensig on 20-Sep-16.
 */
public class Ticket {
    // Entity member fields
    private Object id;
    private String owner;
    private TreeMap<Object, LotteryNumber> lotteryNumbers;

    // Navigational member fields
    private Object lotteryId;

    public Ticket() {
        lotteryNumbers = new TreeMap<>();
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public final ArrayList<LotteryNumber> getLotteryNumbers() {
        ArrayList<LotteryNumber> list = new ArrayList<>(lotteryNumbers.size());
        for (Object key : lotteryNumbers.keySet()) {
            list.add(lotteryNumbers.get(key));
        }
        return list;
    }

    public void removeLotteryNumber(LotteryNumber number){
        if (number == null) {
            return;
        }

        if (number.getId() == null) {
            throw new IllegalArgumentException("Lottery number does not have an ID.");
        }

        lotteryNumbers.remove(number.getId());
    }

    public void addLotteryNumber(LotteryNumber number) {
        if (number == null) {
            return;
        }

        if (number.getId() == null) {
            throw new IllegalArgumentException("Lottery number does not have an ID.");
        }

        Prize oldWinningPrize = null;
        if (lotteryNumbers.containsKey(number.getId())) {
            oldWinningPrize = lotteryNumbers.get(number.getId()).getWinningPrize();
        }

        lotteryNumbers.put(number.getId(), number);
        lotteryNumbers.get(number.getId()).setWinningPrize(oldWinningPrize);
    }

    public Object getId() {
        return id;
    }

    public void setId(Object id) {
        this.id = id;
    }

    public Object getLotteryId() {
        return lotteryId;
    }

    public void setLotteryId(Object lotteryId) {
        this.lotteryId = lotteryId;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || obj.getClass() != this.getClass()) {
            return false;
        }

        Ticket other = (Ticket) obj;
        if (other.id == null) {
            return false;
        }

        return id.equals(other.id);
    }
}


text:
title:  Do Only What God Gave You
date:   02/02/2018
---

**Exploration**: Colossians 1

**Conclude**

Stewardship is not taking on everything in the world. It is about using our gifts, talents, and resources to be a blessing in the areas at which we excel. As Christians, we are called to do things without partiality and with excellence. When we awake each morning, our main accountability supervisor is God. We pursue life, love, and happiness based on His standards. Therefore, we see all things—wealth, education, and abilities—as tools to be used in His service. We are driven by the need to open others' understanding to live a more fulfilling life—a life abiding in Christ.

**Consider**

- Doing a survey of your gifts and talents by asking friends, relatives, and peers for their opinions of what your strengths are.
- Reading or watching autobiographies of legendary Christians who used their gifts to transform lives—George Müller, for example.
- Surfing the Internet to find projects in your local community, in which your talents and gifts would be very beneficial, and joining those projects.
- Making a poster or picture of motivational quotes and hanging it on a wall in your home as a reminder of your duties as a good steward.
- Creating a blog or vlog tracking how you have been using your talents and gifts for one month. Share how that has been a blessing to you.
- Inviting your friends out for an evening of fun. Try to have games that explore the gifts and talents of various genres, for example, singing, cooking, poetry, and art.

**Connect**

1. 1 Corinthians 4:1, 2; 1 Timothy 3:9, 16; 1 Peter 4:10.
2. Ellen G. White, Counsels on Health, pp. 274–278; Adventist Home, chapter 72, "Hospitality."

_Elaine Thompson, Edmonton, Alberta, Canada_


text:
from pylons import config
from pylonsapp import model
from pylonsapp.lib.base import render
from formalchemy import config as fa_config
from formalchemy import templates
from formalchemy import validators
from formalchemy import fields
from formalchemy import forms
from formalchemy import tables
from formalchemy.ext.fsblob import FileFieldRenderer
from formalchemy.ext.fsblob import ImageFieldRenderer

#if 'storage_path' in config['app_conf']:
#    # set the storage_path if we can find an options in app_conf
#    FileFieldRenderer.storage_path = config['app_conf']['storage_path']
#    ImageFieldRenderer.storage_path = config['app_conf']['storage_path']

fa_config.encoding = 'utf-8'

class TemplateEngine(templates.TemplateEngine):
    def render(self, name, **kwargs):
        return render('/forms/%s.mako' % name, extra_vars=kwargs)
fa_config.engine = TemplateEngine()

class FieldSet(forms.FieldSet):
    pass

class Grid(tables.Grid):
    pass

## Initialize fieldsets

#Foo = FieldSet(model.Foo)
#Reflected = FieldSet(Reflected)

## Initialize grids

#FooGrid = Grid(model.Foo)
#ReflectedGrid = Grid(Reflected)


text:
{{vm.region.name}}

<uib-tabset active="sidebarActiveTab">
  <uib-tab index="0" heading="Population">
    <highlighted-topic
      description="Indigenous"
      region-type="vm.regionType"
      region="vm.region"
      attribute-selector="census2016_proportion_all_persons_indigenous">
    </highlighted-topic>
    <highlighted-topic
      description="Population (Census 2016)"
      region-type="vm.regionType"
      region="vm.region"
      attribute-selector="census2016_all_persons_total">
    </highlighted-topic>
    <topic-breakdown-bar
      description="All persons by age (2016)"
      region-type="vm.regionType"
      region="vm.region"
      attribute-selector="census2016_(aggregate_\d+\w+|\d+plus)_persons_total"
      sorter="vm.sortByAttributeNameNumbers"
      refresh-on="sidebarActiveTab">
    </topic-breakdown-bar>
  </uib-tab>
  <uib-tab index="2" heading="Income">
    <highlighted-topic
      description="Median Household - Indigenous"
      region-type="vm.regionType"
      region="vm.region"
      attribute-selector="census2016_median_weekly_household_income_indigenous">
    </highlighted-topic>
    <topic-breakdown-bar
      description="Indigenous households weekly income (2016)"
      region-type="vm.regionType"
      region="vm.region"
      attribute-selector="census2016_(\d.+)_weekly_household_income_indigenous"
      sorter="vm.sortByAttributeNameNumbers"
      refresh-on="sidebarActiveTab">
    </topic-breakdown-bar>
    <highlighted-topic
      description="Median Household - All"
      region-type="vm.regionType"
      region="vm.region"
      attribute-selector="census2016_median_weekly_household_income_all">
    </highlighted-topic>
    <topic-breakdown-bar
      description="All households weekly income (2016)"
      region-type="vm.regionType"
      region="vm.region"
      attribute-selector="census2016_(\d.+)_weekly_household_income_all"
      sorter="vm.sortByAttributeNameNumbers"
      refresh-on="sidebarActiveTab">
    </topic-breakdown-bar>
  </uib-tab>
</uib-tabset>


text:
<?xml version="1.0"?>
<h:html xmlns="http://www.w3.org/2002/xforms" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:h="http://www.w3.org/1999/xhtml" xmlns:jr="http://openrosa.org/javarosa" xmlns:orx="http://openrosa.org/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <h:head>
    <h:title>Test2</h:title>
    <model>
      <instance>
        <q id="Test2" >
          <PROGRAMME>
            <PROJECT>
              <Partner jr:template="">
                <INFORMATION>
                  <Partner_Name/>
                  <Camp jr:template="">
                    <P_Camps/>
                  </Camp>
                  <PO1_Intervention_budget/>
                </INFORMATION>
              </Partner>
            </PROJECT>
          </PROGRAMME>
          <meta>
            <instanceID/>
          </meta>
        </q>
      </instance>
      <bind calculate="concat('uuid:', uuid())" nodeset="/q/meta/instanceID" readonly="true()" type="string"/>
    </model>
  </h:head>
  <h:body>
    <group ref="/q/PROGRAMME">
      <group ref="/q/PROGRAMME/PROJECT">
        <group ref="/q/PROGRAMME/PROJECT/Partner">

          <repeat nodeset="/q/PROGRAMME/PROJECT/Partner">
            <group ref="/q/PROGRAMME/PROJECT/Partner/INFORMATION">
              PARTNER PROJECT INFORMATION: <output value=" /q/PROGRAMME/PROJECT/Partner/INFORMATION/Partner_Name "/>
              <group ref="/q/PROGRAMME/PROJECT/Partner/INFORMATION/Camp">

                <repeat appearance="W1" nodeset="/q/PROGRAMME/PROJECT/Partner/INFORMATION/Camp">
                  <input ref="/q/PROGRAMME/PROJECT/Partner/INFORMATION/Camp/P_Camps">
                    Camp/Site/Village(s): <output value=" /q/PROGRAMME/PROJECT/Partner/INFORMATION/Partner_Name "/>
                  </input>
                </repeat>
              </group>
            </group>
          </repeat>
        </group>
      </group>
    </group>
  </h:body>
</h:html>


text:
package ar.edu.utn.dds.controller;

import static spark.Spark.get;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import ar.edu.utn.dds.modeloWeb.Model;
import ar.edu.utn.dds.templateEngine.FreeMarkerEngine;
import spark.ModelAndView;

public class Empresas {
	public void init(Model mod) {
	get("/getEmpresas", (request, response) -> {
		response.status(200);
		mod.getEmpresas();
		Map<String, Object> viewObjects = new HashMap<String, Object>();
		viewObjects.put("empresas", mod.sendEmpresas());
		viewObjects.put("templateName", "mostrarEmpresa.ftl");
		return new ModelAndView(viewObjects, "main.ftl");
	}, new FreeMarkerEngine());

	get("/getempresas", (request, response) -> {
		response.status(200);
		return toJSON(mod.sendEmpresas());
	});
}

	private static String toJSON(Object obj) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			mapper.enable(SerializationFeature.INDENT_OUTPUT);
			StringWriter sw = new StringWriter();
			mapper.writeValue(sw, obj);
			return sw.toString();
		} catch (IOException e) {
			System.err.println(e);
		}
		return null;
	}

}


text:
import('GlobalVars')
import('Actions')
import('Conditions')
import('Animation')
import('ObjectLoad')
--import('Math')
import('Scenarios')
import('PrintRecursive')
import('KeyboardControl')
import('PilotAI')
import('Interfaces')
import('PopDownConsole')
import('Camera')
import('Physics')
import('Effects')
import('Proximity')

mdown = false
mrad = MOUSE_RADIUS / cameraRatio.current
aimMethod = "smart"

function init()
    Physics.NewSystem()
    start_time = mode_manager.time()
    realTime = mode_manager.time()
    last_time = mode_manager.time()

    scen = LoadScenario(demoLevel)

	selection.control = scen.playership
	selection.controlId = scen.playerShipId
	selection.target = nil
	selection.targetId = nil

	window.mouse_toggle()
end

function key( k )
    if RELEASE_BUILD ~= true then
        if k == "e" then
            consoleDraw = true
        end
    end
    if k == "escape" then
        menu_display = "esc_menu"
        keyup = escape_keyup
        key = escape_key
    elseif k == "q" then
        mode_manager.switch("Xsera/MainMenu")
    elseif k == "x" then
        aimMethod = aimMethod == "smart" and "dumb" or "smart"
        print(aimMethod)
    elseif k == "f" then
        AddEffects("flash", 1, 0.25,{})
    elseif k == "g" then
        blinkMode = (blinkMode == "triangle" and "flash" or "triangle")
        print(blinkMode)
    elseif k == "/" then
        printTable(scen.playerShip)
    elseif k == "backspace" then
        scen.playerShip.status.health = scen.playerShip.status.health - 1000
        if scen.playerShip.status.health < 0 then
            scen.playerShip.status.health = 0
        end
    else
        KeyActivate(k)
    end
end

function keyup(k)
    KeyDeactivate(k)
end

normal_key = key
normal_keyup = keyup

function update()
    local newTime = mode_manager.time()
    dt = newTime - last_time
    last_time = newTime

    if menu_display == nil and consoleDraw == false then
        if keyboard[4][7].active == true then
            dt = dt * 50
        end

        realTime = realTime + dt
        if cameraSnap == false then
            CameraInterpolate(dt)
        else
            CameraSnap()
            cameraSnap = false
        end

        KeyDoActivated()

        --[[ commenting out due to new physics system (which currently lacks collision detection)
        local cols = physics.collisions()

        for idx, pair in pairs(cols) do
            local a = scen.objects[pair[1] ]
            local b = scen.objects[pair[2] ]

            if a.base.attributes.canCollide == true
            and b.base.attributes.canCollide == true
            and a.ai.owner ~= b.ai.owner then
                Collide(a,b)
            end
        end
        mdown = false--]]

        --It might be better to do this in Physics.UpdateSystem
        for ai, a in pairs(scen.objects) do
            for bi, b in pairs(scen.objects) do
                if ai > bi then
                    if a.base.attributes.canCollide == true
                    and b.base.attributes.canCollide == true
                    and a.ai.owner ~= b.ai.owner
                    and hypot2(a.physics.position, b.physics.position) <= (a.physics.collision_radius + b.physics.collision_radius) then
                        Collide(a,b)
                    end
                end
            end
        end

        for i, o in pairs(scen.objects) do
            if o.type == "beam" then
                --[[
                BITS    HEX    FLAG
                001    0x1    RELATIVE
                010    0x2    STATIC
                100    0x4    BOLT
                --]]
                if o.base.beam.mode == "relative" then
                    local src = o.gfx.source.position
                    local off = o.gfx.offset
                    local rel = o.gfx.relative
                    local a = src;
                    a = a + off
                    a = a + rel
                    o.physics.position = src + off + rel

                elseif o.base.beam.mode == "direct" then
                    local from = o.gfx.offset + o.gfx.source.position
                    local dir = NormalizeVec(o.gfx.target.position - o.gfx.source.position)
                    local len = math.min(o.base.beam.range, hypot2(from,o.gfx.target.position))

                    o.physics.position = dir * len
                end
            end

            if o.status.health <= 0 and o.status.healthMax >= 1 then
                DestroyTrigger(o)
                o.status.dead = true
            end

            if o.status.energy ~= nil then
                if o.status.energy < o.status.energyMax
                and o.status.battery > dt * ENERGY_RECHARGE_RATIO / BASE_RECHARGE_RATE then
                    o.status.energy = o.status.energy + dt * ENERGY_RECHARGE_RATIO / BASE_RECHARGE_RATE
                    o.status.battery = o.status.battery - dt * ENERGY_RECHARGE_RATIO / BASE_RECHARGE_RATE
                end

                if o.status.health ~= nil
                and o.status.health <= o.status.healthMax * SHIELD_RECHARGE_MAX
                and o.status.energy > SHIELD_RECHARGE_RATIO * dt / BASE_RECHARGE_RATE then
                    o.status.health = o.status.health + dt / BASE_RECHARGE_RATE
                    o.status.energy = o.status.energy - SHIELD_RECHARGE_RATIO * dt / BASE_RECHARGE_RATE
                end

                if o.weapons ~= nil then
                    for wid, weap in pairs(o.weapons) do
                        if weap.ammo ~= -1
                        and weap.base.device.restockCost > 0
                        and weap.ammo < weap.base.device.ammo / 2
                        and weap.lastRestock + weap.base.device.restockCost * BASE_RECHARGE_RATE * WEAPON_RESTOCK_RATE / TIME_FACTOR <= realTime
                        and o.status.energy >= weap.base.device.restockCost * WEAPON_RESTOCK_RATIO then
                            o.status.energy = o.status.energy - weap.base.device.restockCost * WEAPON_RESTOCK_RATIO
                            weap.ammo = weap.ammo + 1
                            weap.lastRestock = realTime
                        end
                    end
                end
            end

            --Lifetimer
            if o.age ~= nil then
                if o.age.lifeSpan + o.age.created <= realTime then
                    ExpireTrigger(o)
                    o.status.dead = true
                end
            end

            if o ~= scen.playerShip then
             Think(o)
            end

            if o.triggers.periodic ~= nil
            and o.triggers.periodic.interval ~= 0
            and o.triggers.periodic.next <= realTime then
                ActivateTrigger(o)
                o.triggers.periodic.next = realTime + o.triggers.periodic.interval + math.random(0,o.triggers.periodic.range)
            end

            --Fire weapons
            if o.weapons ~= nil then
                if o.control.pulse == true
                and o.weapons.pulse ~= nil then
                    ActivateTrigger(o.weapons.pulse, o)
                end

                if o.control.beam == true
                and o.weapons.beam ~= nil then
                    ActivateTrigger(o.weapons.beam, o)
                end

                if o.control.special == true
                and o.weapons.special ~= nil then
                    ActivateTrigger(o.weapons.special, o)
                end
            end

--[[------------------
    Movement
------------------]]--
            Warp(o)

            local rvel
            if o.base.attributes.canTurn == true then
                rvel = o.base.rotation.turnRate
            else
                rvel = DEFAULT_ROTATION_RATE
            end

            if o.control.left == true then
                o.physics.angularVelocity = rvel * 2.0
            elseif o.control.right == true then
                o.physics.angularVelocity = -rvel * 2.0
            else
                o.physics.angularVelocity = 0
            end

            if o.warp.stage < WARP_RUNNING then
                if o.control.accel == true then
                    -- apply a forward force in the direction the ship is facing
                    local angle = o.physics.angle
                    local thrust = o.base.thrust * SPEED_FACTOR
                    local force = vec(thrust * math.cos(angle), thrust * math.sin(angle))
                    Physics.ApplyImpulse(o.physics, force)
                end

                if o.control.decel == true
                    or hypot1(o.physics.velocity) >= o.base.maxVelocity * SPEED_FACTOR then
                    -- apply a reverse force in the direction opposite the direction the ship is MOVING
                    local thrust = o.base.thrust * SPEED_FACTOR
                    local force = o.physics.velocity
                    if force.x ~= 0 or force.y ~= 0 then
                        if hypot1(o.physics.velocity) <= 10 then
                            o.physics.velocity = vec(0, 0)
                        else
                            local velocityMag = hypot1(force)
                            force = -force * thrust / velocityMag
                            if dt * velocityMag / o.physics.mass > velocityMag then
                                o.physics.velocity = vec(0, 0)
                            else
                                Physics.ApplyImpulse(o.physics, force)
                            end
                        end
                    end
                end
            elseif o.base.warpSpeed ~= nil then
                local velocityMag = math.max(o.warp.factor * o.base.warpSpeed, o.base.maxVelocity) * SPEED_FACTOR
                o.physics.velocity = PolarVec(velocityMag, o.physics.angle)
            end

            if o.base.attributes.canAcceptBuild then
                UpdatePlanet(o, dt)
            end
        end

        RemoveDead()
        TestConditions(scen)
        --GenerateStatusLines(scen) -- not properly implemented due to configuration change

        UpdateEffects(dt)
        Physics.UpdateSystem(dt, scen.objects)
    end
end

function Win() -- this may look ugly, but you need the double backslashes to make it work
    print("__             __    ______     ___   _ ")
    print("\\ \\     /\\    / /   |__  __|   |   \\ | |")
    print(" \\ \\   /  \\  / /       | |     | |\\ \\| |")
    print("  \\ \\_/ /\\ \\/ /      __| |_    | | \\   |")
    print("   \\___/  \\__/      |______|   |_|  \\__|")
end

function render()
	graphics.begin_frame()

	CameraToObject(scen.playerShip)

	graphics.begin_warp(scen.playerShip.warp.factor,scen.playerShip.physics.angle, cameraRatio.current)

	graphics.draw_starfield(3.4)
	graphics.draw_starfield(1.8)
	graphics.draw_starfield(0.6)
	graphics.draw_starfield(-0.3)
	graphics.draw_starfield(-0.9)

	--DEBUG version, keep:
	--graphics.end_warp(scen.playerShip.warp.factor, scen.playerShip.physics.angle, cameraRatio.curr, scen.playerShip.physics.position)
	graphics.end_warp()

	DrawGrid()

	for objectId, object in pairs(scen.objects) do
		if objectId ~= scen.playerShipId then
			DrawObject(object)
		end
	end

	graphics.draw_particles()

	DrawObject(scen.playerShip)
	DrawEffects()

	DrawArrow()
	DrawMouse1()
	DrawPanels()

	local cam = CameraToWindow()
	graphics.set_camera(cam[1], cam[2], cam[3], cam[4])
	DrawMouse2()

	InterfaceDisplay(dt)
	PopDownConsole()

	--debug
	local zoomLevels = {
	"[2:1]","[1:1]","[1:2]","[1:4]","[1:16]","[closest hostile]", "[closest object]", "[all objects]"}
	graphics.draw_text(zoomLevels[cameraRatio.target], MAIN_FONT, "left", {x=100, y=100},30)
	graphics.end_frame()

	sound.listener(scen.playerShip.physics.position, scen.playerShip.physics.velocity)
end

function mouse(button, x, y)
    if button == "wheel_up" then
        DoScaleIn(0.2)
    elseif button == "wheel_down" then
        DoScaleOut(0.2)
    else
        mdown = true
    end
end

function mouse_up()
	if mdown then
        print(cameraRatio.current)
        local mousePos = GetMouseCoords()
        if keyboard[2][5].active == true then -- TARGET
            selection.targetId, selection.target = NextTargetUnderCursor(selection.targetId, true)
        else -- CONTROL
            selection.controlId, selection.control = NextTargetUnderCursor(selection.controlId, false)
            if selection.control.base.attributes.canAcceptBuild then
                selection.lastPlanet = selection.control
                CalculateBuildables(selection.lastPlanet, scen)
            end
        end
    end
    mdown = false
end

function shutdown()

end

function RemoveDead()
    --Remove destroyed or expired objects
    for i, o in pairs(scen.objects) do
        if o.status.dead == true then
            if scen.playerShipId == i then
                AddPlayerBody()
            end
            scen.objects[i] = nil
        end
    end
end

function AddPlayerBody()
    local body = NewObject(22)--[SCOTT][HARDCODE]
    body.ai.owner = scen.playerShip.ai.owner
    body.physics.velocity = scen.playerShip.physics.velocity
    body.physics.position = scen.playerShip.physics.position
    body.physics.angle = scen.playerShip.physics.angle

    scen.playerShipId = body.physics.object_id
    scen.objects[body.physics.object_id] = body
    --[SCOTT] We need a module for ship selection.
    ChangePlayerShip()
end

function ChangePlayerShip()

    scen.playerShip = scen.objects[scen.playerShipId]
    if scen.playerShip == nil then
        scen.playerShipId, scen.playerShip = next(scen.objects,scen.playerShipId)
        if scen.playerShip == nil then
            scen.playerShipId, scen.playerShip = next(scen.objects)
        end
    end

    scen.playerShip.control = {
        accel = false;
        decel = false;
        left = false;
        right = false;
        beam = false;
        pulse = false;
        special = false;
        warp = false;
    }
end

function Collide(a,b)
local o = a
local other = b
--[[
Equation for 1D elastic collision:
v1 = (m1v1 + m2v2 + m1C(v2-v1))/(m1+m2)

OR

Nathan's Method:
dist = dist(v1,v2)
angle = angleto(pos1,pos2)
momentMag = dist * m1/(m1+m2)
v1 = Polar2Rect(1,angle) * dist * m1 / (m1 + m2)
v2 = Polar2Rect(1,angle+180) * dist * m2 / (m1 + m2)
--]]
    if o.base.attributes.occupiesSpace
    and other.base.attributes.occupiesSpace then
        local p = o.physics
        local p2 = other.physics
        v1 = p.velocity
        m1 = p.mass
        v2 = p2.velocity
        m2 = p2.mass
--[[
        p.velocity = {
            x = (m1 * v1.x + m2 *v2.x + m1 * RESTITUTION_COEFFICIENT * ( v2.x - v1.x))/(m1+m2);
            y = (m1 * v1.y + m2 *v2.y + m1 * RESTITUTION_COEFFICIENT * ( v2.y - v1.y))/(m1+m2);
        }

        p2.velocity = {
            x = (m1 * v1.x + m2 *v2.x + m2 * RESTITUTION_COEFFICIENT * ( v1.x - v2.x))/(m1+m2);
            y = (m1 * v1.y + m2 *v2.y + m2 * RESTITUTION_COEFFICIENT * ( v1.y - v2.y))/(m1+m2);
        }
--]]

        local dist = hypot2(v1, v2)
        local angle = findAngle(p.position,p2.position)
        p.velocity = PolarVec(dist * m1 / (m1+m2), angle)
        p2.velocity = PolarVec(dist * m2 / (m1+m2), angle+math.pi)
    end

    CollideTrigger(o,other)
    CollideTrigger(other,o)

    if other.base.damage ~= nil then
        o.status.health = o.status.health - other.base.damage
    end
    if o.base.damage ~= nil then
        other.status.health = other.status.health - o.base.damage
    end
end

function Warp(object)
    local warp = object.warp

    if object.control.warp == true
    and warp.stage < WARP_COOLING then
        if warp.factor < 1.0 then
            warp.stage = WARP_SPOOLING
            warp.factor = warp.factor + dt / WARP_TIME
            if warp.factor >= warp.lastPlayed / 4 then
                warp.lastPlayed = warp.lastPlayed + 1
                sound.play("Warp"..warp.lastPlayed)
            end
            if warp.factor >= 1.0 then
                warp.stage = WARP_RUNNING
                warp.factor = 1.0
                warp.lastPlayed = 5

                local flare = NewObject(32)--[SCOTT][HARDCODE]
                flare.physics.position = object.physics.position + PolarVec(-object.physics.collision_radius*1.5,object.physics.angle)
                CreateTrigger(flare)
                scen.objects[flare.physics.object_id] = flare
            end
        end
    elseif warp.stage >= WARP_ABORTING then
        if warp.factor > 0.0 then
            warp.factor = warp.factor - dt / WARP_OUT_TIME
            if warp.stage == WARP_ABORTING then
                warp.factor = warp.factor - dt / WARP_OUT_TIME * 4
            end
            if warp.factor <= 0.0 then
                warp.factor = 0.0
                warp.lastPlayed = 0
                if warp.stage == WARP_COOLING then
                    local flare = NewObject(33)--[SCOTT][HARDCODE]
                flare.physics.position = object.physics.position + PolarVec(-object.physics.collision_radius*1.5,object.physics.angle)
                CreateTrigger(flare)
                scen.objects[flare.physics.object_id] = flare
                end
                warp.stage = WARP_IDLE
            end
        end
    end
end

function DrawObject(o)
	o.gfx.cycle = o.gfx.cycle + dt
	if o.type == "beam" then
		--[[
			BITS HEX FLAG
			001  0x1 RELATIVE
			010  0x2 STATIC
			100  0x4 BOLT
		--]]
		if o.base.beam.hex > 0 then
			local from = o.gfx.source.position + o.gfx.offset
			if o.base.beam.hex == "bolt" then
				graphics.draw_lightning(from, o.physics.position, 1.0, 10.0, false,ClutColour(o.base.beam.color))
			elseif o.base.beam.type == "static" then
				graphics.draw_line(from, o.physics.position, 3.0, ClutColour(o.base.beam.color))
			end
		else --kinetic
			local p1 = o.physics.position
			local p2 = PolarVec(BEAM_LENGTH,o.physics.angle)
			graphics.draw_line(p1, p1 + p2, 1, ClutColour(o.base.beam.color))
		end
	else
		if cameraRatio.current >= 1 / 4 then
			if o.type == "animation" then
				graphics.draw_sprite_frame(o.gfx.sprite, o.physics.position, o.gfx.dimensions, Animate(o))
			else -- Rotational
				graphics.draw_sprite(o.gfx.sprite, o.physics.position, o.gfx.dimensions, o.physics.angle)
			end
		else
			local cscale = 1
			if o.status.health <= o.status.healthMax / 2 then
				cscale = math.ceil((math.sin(o.gfx.cycle*4) + 1)*7)
			end
			local color

			if o.ai.owner == -1 then
				color = ClutColour(4,cscale)
			elseif o.ai.owner == scen.playerShip.ai.owner then
				color = ClutColour(5,cscale)
			else
				color = ClutColour(16,cscale)
			end

			local iconScale = 1.0/cameraRatio.current
			if o.base.iconShape == "square" then
				graphics.draw_rbox(o.physics.position, o.base.iconSize * iconScale, color)
			elseif o.base.iconShape == "plus" then
				graphics.draw_rplus(o.physics.position, o.base.iconSize * iconScale, color)
			elseif o.base.iconShape == "triangle" then
				graphics.draw_rtri(o.physics.position, o.base.iconSize * iconScale, color)
			elseif o.base.iconShape == "diamond" then
				graphics.draw_rdia(o.physics.position, o.base.iconSize * iconScale, color)
			elseif o.base.iconShape == "framed square" then --NOT IMPLEMENTED [TODO]
				graphics.draw_rbox(o.physics.position, o.base.iconSize * iconScale, color)
			end
		end
	end
end


text:
@InterfaceAudience.LimitedPrivate({"HBase", "HDFS", "MapReduce"})
@InterfaceStability.Unstable
package org.apache.hadoop.http;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;


text:
Detalles

				Posted on

				by

    	No Detalles yet, why don't you create one?


text:
package personaje;

import java.awt.Point;
import java.awt.Rectangle;

public class Humano extends Personaje{

	public Humano(String name) {
		super();
	}

	@Override
	public boolean puedeAtacar() {
		return energia >= 10;
	}

}


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

    Copyright (c) 2002-2015 mgm technology partners GmbH

    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.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<parent>
		<groupId>com.mgmtp.perfload.core</groupId>
		<artifactId>perfload-core</artifactId>
		<version>4.9.5-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>
	<artifactId>perfload-test</artifactId>
	<packaging>pom</packaging>
	<name>mgm perfLoad Test</name>
	<description>mgm perfLoad Test</description>

	<modules>
		<module>perfload-test-utils</module>
		<module>perfload-test-comp</module>
		<module>perfload-test-app</module>
		<module>perfload-test-client</module>
		<module>perfload-test-it</module>
	</modules>

</project>


text:
This is a statement by Nick Guiffrida that grants permission to
relicense its copyrights in the libzmq C++ library (ZeroMQ) under the
Mozilla Public License v2 (MPLv2) or any other Open Source Initiative
approved license chosen by the current ZeroMQ BDFL (Benevolent
Dictator for Life).

The commits made by the Github handle "goodfella", with commit author
"Nick Guiffrida goodfella005@gmail.com" are copyright of Nick
Guiffrida. This document hereby grants the libzmq project team to
relicense libzmq, including all past, present and future contributions
of the author listed above.


text:
using System;
using Microsoft.SPOT;

namespace uPLibrary.Networking.Smtp
{
    /// <summary>
    /// Information about Smtp server to connect for sending emails
    /// </summary>
    public class SmtpServer
    {
        // default Smtp server port
        public const int SMTP_DEFAULT_PORT = 25;

        // server host name and port
        private string host;
        private int port;

        /// <summary>
        /// Server host name
        /// </summary>
        public string Host
        {
            get { return this.host; }
            set { this.host = value; }
        }

        /// <summary>
        /// Server port (default 25)
        /// </summary>
        public int Port
        {
            get { return this.port; }
            set { this.port = value; }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="host">Server host name</param>
        /// <param name="port">Server port name</param>
        public SmtpServer(string host, int port)
        {
            this.host = host;
            this.port = port;
        }

        /// <summary>
        /// Costructor with Smtp port 25 as default
        /// </summary>
        /// <param name="host">Server host name</param>
        public SmtpServer(string host)
            : this(host, SMTP_DEFAULT_PORT)
        {
        }

    }
}


text:
package com.intel.ssg.dcst.panthera.parse.sql.generator.text;

import org.antlr.runtime.tree.CommonTree;

import com.intel.ssg.dcst.panthera.parse.sql.TranslateContext;

/**
 * TextGenerator interface.<br>
 * QueryTextGenerator.
 *
 */
public interface QueryTextGenerator {
  String textGenerateQuery(CommonTree root, TranslateContext context) throws Exception;
}


text:
#include<stdio.h>
#include<stdlib.h>
#include<curl/curl.h>
#include<jni.h>
#include"Test.h"

static size_t WriteCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
  /* we are not interested in the downloaded bytes itself,
     so we only return the size we would have saved ... */
  (void)ptr;  /* unused */
  (void)data; /* unused */
  return (size_t)(size * nmemb);
}

JNIEXPORT jdoubleArray JNICALL Java_Test_sayHello(JNIEnv *env, jobject obj, jstring URL){

    const char *url = (*env)->GetStringUTFChars(env, URL, NULL);
    printf("\t Hey Java!\n");
    curl_global_init( CURL_GLOBAL_ALL );
    CURL * myHandle;
    jdouble val,dns,conn,preTime,ttfb,ttime,redirectTime,redirectCount,size,downSpeed,resCode;
    val=dns=conn=preTime=ttfb=ttime=redirectTime=redirectCount=size=downSpeed=resCode=0;
    int no=0;
    jdoubleArray result=(*env)->NewDoubleArray(env, 10);
    CURLcode res; // We'll store the result of CURL's webpage retrieval, for simple error checking.
    myHandle = curl_easy_init( );
    // Notice the lack of major error checking, for brevity
    curl_easy_setopt(myHandle, CURLOPT_URL, url);
    curl_easy_setopt(myHandle, CURLOPT_USERAGENT,"Mozilla/4.0");
    curl_easy_setopt(myHandle, CURLOPT_TIMEOUT_MS, 2000L);
    curl_easy_setopt(myHandle, CURLOPT_WRITEFUNCTION, WriteCallback);
    res = curl_easy_perform( myHandle );
    if(CURLE_OK == res) {

        /* check for total download time */

          res = curl_easy_getinfo(myHandle, CURLINFO_NAMELOOKUP_TIME, &dns);
        if((CURLE_OK == res) && (dns>0))
        {
            printf("Name lookup time: %0.3f sec.\n", dns);

        }

          /* check for connect time */
          res = curl_easy_getinfo(myHandle, CURLINFO_CONNECT_TIME, &conn);
          if((CURLE_OK == res) && (conn>0))
          {

            //result[no++]=val;
            printf("Connect time: %0.3f sec.\n", conn);
        }

          res = curl_easy_getinfo(myHandle, CURLINFO_PRETRANSFER_TIME, &preTime);
          if((CURLE_OK == res) && (preTime>0))
          {

            //result[no++]=val;
            printf("Pretransfer time: %0.3f sec.\n", preTime);
        }

        res = curl_easy_getinfo(myHandle, CURLINFO_STARTTRANSFER_TIME, &ttfb);
          if((CURLE_OK == res) && (ttfb>0)){
            printf("TTFB: %0.3f sec.\n", ttfb);
            //result[no++]=val;
        }

        res = curl_easy_getinfo(myHandle, CURLINFO_TOTAL_TIME, &ttime);
        if((CURLE_OK == res) && (ttime>0)){
          printf("Total Response time: %0.3f sec.\n", ttime);
          //result[no++]=val;
      }

          res = curl_easy_getinfo(myHandle, CURLINFO_REDIRECT_TIME, &redirectTime);
          if((CURLE_OK == res) || (redirectTime>0))
          {

            //result[no++]=val;
            printf("Redirect Time: %0.3f sec.\n", redirectTime);
        }

          res = curl_easy_getinfo(myHandle, CURLINFO_REDIRECT_COUNT, &redirectCount);
          if((CURLE_OK == res) || (redirectCount>0))
          {

            //result[no++]=val;
            printf("Redirect Count: %f\n", redirectCount);
        }

        res = curl_easy_getinfo(myHandle, CURLINFO_SIZE_DOWNLOAD, &size);

        if((CURLE_OK == res) && (size>0))
        {
          printf("Response Size: %0.0f bytes.\n", size);
        //result[no++]=val;
    }

          res = curl_easy_getinfo(myHandle, CURLINFO_SPEED_DOWNLOAD, &downSpeed);
          if((CURLE_OK == res) && (downSpeed>0))
          {

            //result[no++]=val;
            printf("Download Speed: %0.3f sec.\n",downSpeed);
        }

    long rescode;
    res = curl_easy_getinfo(myHandle, CURLINFO_RESPONSE_CODE, &rescode);

        if((CURLE_OK == res) && (rescode>0))
        {
          printf("Response Code: %ld\n", rescode);
          resCode=rescode;
        //result[no++]=val;
    }

        //}

  } else {
    fprintf(stderr, "Error while fetching ");
  }

    //printf("LibCurl rules!");
    curl_easy_cleanup( myHandle );

    jdouble _result[]={resCode,dns,conn,preTime,ttfb,ttime,redirectTime,redirectCount,size,downSpeed};
    (*env)->SetDoubleArrayRegion(env, result, 0 , 10, _result);
    return result;
}


text:
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using System;

namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions
{
    public interface IEventBus
    {
        void Subscribe<T, TH>()
            where T : IntegrationEvent
            where TH : IIntegrationEventHandler<T>;
        void SubscribeDynamic<TH>(string eventName)
            where TH : IDynamicIntegrationEventHandler;

        void UnsubscribeDynamic<TH>(string eventName)
            where TH : IDynamicIntegrationEventHandler;

        void Unsubscribe<T, TH>()
            where TH : IIntegrationEventHandler<T>
            where T : IntegrationEvent;

        void Publish(IntegrationEvent @event);
    }
}


text:
"""'
Handy derived data and analysis functions for working with person-click
datasets in Pandas. Most of these functions get passed a person-click
DataFrame.

This product includes GeoLite data created by MaxMind, available from
http://www.maxmind.com.

Created on September 18, 2013

@author: tmullaney
"""'

import pandas as pd
import numpy as np
import re
import pytz
import datetime
import dateutil.parser

"""'
DERIVED DATA
Add columns to person-click datasets. Be careful running on very large
DataFrames, as these functions can be slow.
"""'
def getAgentInfo(df):
    from ua_parser import user_agent_parser
    # user_agent_parser
    #   module: https://github.com/tobie/ua-parser
    #   install: pip install pyyaml ua-parser
    def getInfo(agent):
        rec = user_agent_parser.Parse(agent)
        return pd.Series({
            'device': rec['device']['family'], # 'Other' = computer
            'os': rec['os']['family'],
            'browser': rec['user_agent']['family']
            })

    return df['agent'].apply(getInfo)

def getIPInfo(df, geolitecity_dat):
    import pygeoip
    # pygeoip
    #   module: https://pypi.python.org/pypi/pygeoip/
    #   install: easy_install pygeoip
    #   dataset: http://dev.maxmind.com/geoip/legacy/geolite/ (GeoLiteCity.dat)
    gi4 = pygeoip.GeoIP(geolitecity_dat, pygeoip.MEMORY_CACHE)

    def getInfo(time_ip_tuple):
        ip = time_ip_tuple[1]
        rec = gi4.record_by_addr(ip)

        # calc local time; sometimes the time_zone isn't in the db
        t = time_ip_tuple[0]
        if(len(t) > 5 and t[-6:] == '+00:00'): t = t[:-6]
        tz = rec['time_zone']
        dt = dateutil.parser.parse(str(t)).replace(tzinfo=pytz.utc)
        try: local_time = dt.astimezone(pytz.timezone(tz))
        except Exception: local_time = None

        return pd.Series({
            'local_time': local_time,
            'city': rec['city'],
            'country_name': rec['country_name'],
            'country_code': rec['country_code'],
            'latitude': rec['latitude'],
            'longitude': rec['longitude']
            })

    return df[['time', 'ip']].apply(getInfo, axis=1)

"""'
DATA INTEGRITY
Verify completeness/accuracy of a person-click dataset.
"""'
def loadPersonClick(personclick_csv, cols=None):
    # Full log person-click datasets can be too large for Pandas'
    # built-in CSV reader to work properly. This function loads a
    # dataframe in chunks and concatenates instead. You can optionally
    # pass a list of column names to limit which columns get read in
    # and save memory.
    it = pd.read_csv(personclick_csv, iterator=True, chunksize=1000, usecols=cols)
    return pd.concat([chunk for chunk in it], ignore_index=True)

def getUniqueDiscardPatterns(df_discards):
    # Because we discard log items in parsing a person-click dataset,
    # we need to justify each pattern we're discarding, and manually
    # check the noise.
    def replaceHashes(event_type):
        hashless = re.sub(r'[0-9a-f]{24,32}', '{HASH}', event_type)
        return re.sub(r'(lecture_[0-9]+)|([a-z]+_l[0-9]+(_[a-z]+)+)', '{NONHASH_ID}', hashless) # vert|cond|poll

    return df_discards.event_type.apply(replaceHashes).value_counts()

def countAnonymousUsers(df, pct=True):
    # When users aren't logged in, logged events don't have usernames.
    # When we don't have usernames, it's harder to do person-level
    # analyses.
    n_anonymous = len(df[df.actor.isnull()])
    n_total = len(df)
    return float(n_anonymous) / n_total if pct else n_anonymous

def getAxisLookupFails(df):
    # Sometimes courseware events will be logged that can't be found
    # in the Course Axes. When this happens, we don't have a meaningful
    # 'object_name' in the person-click dataset.
    return df[df.object_name.apply(lambda x: 'Axis Lookup Failed' in str(x))]

def makeVerbExampleTable(df):
    # Makes a DataFrame where each type of verb in the dataset gets
    # a row, and examples are filled in for the object, result, meta,
    # event_type, and event columns.
    ex_cols = ['verb', 'object_name', 'object_type', 'result', 'meta', 'event', 'event_type']
    return df[ex_cols].groupby(df.verb).last()

def makePersonLevel(df):
    # Makes a DataFrame where rows are unique usernames, columns are
    # verb types, and values are the number of occurrences of each
    # verb type per user. Note: 'df' only needs to have actor/verb
    # columns.
    user_verbs = df[["actor", "verb"]].groupby([df["actor"], df["verb"]]).size().reset_index()
    return user_verbs.pivot(index="actor", columns="verb", values=0)


text:
@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    MKTileOverlay *osmOverlay = [[MKTileOverlay alloc] initWithURLTemplate:@"http://c.tile.openstreetmap.org/{z}/{x}/{y}.png"];

    // This lets MapKit know that the provided tiles can replace the MapKit provided
    // tiles, when this is set to YES the MapKit tiles will not be rendered.
    osmOverlay.canReplaceMapContent = YES;

    [_mapView addOverlay:osmOverlay];
}

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay
{
    return [[MKTileOverlayRenderer alloc] initWithTileOverlay:overlay];
}

@end


text:
gem 'chargify_api_ares', '=1.3.2'
require 'chargify_api_ares'

Chargify.configure do |c|
  c.subdomain = ENV['CHARGIFY_SUBDOMAIN']
  c.api_key   = ENV['CHARGIFY_API_KEY']
end

page = 1

while true do

  subscriptions = Chargify::Subscription.find( :all, params: { per_page: 5, page: page, state: ["active","trialing"] } )

  puts subscriptions.count
  if subscriptions.count == 0 then break end

  subscriptions.each { |sub|
    curr_next_billing = sub.next_assessment_at
    new_next_billing = Time.new curr_next_billing.year, curr_next_billing.month, curr_next_billing.day, 6, 0, 0, "-05:00"
    sub.next_billing_at = new_next_billing
    puts "id: #{sub.id} curr: #{curr_next_billing} new: #{new_next_billing}"
    #sub.save
  }

  page = page + 1

end


text:
package org.colorcoding.ibas.bobas.db.mssql.test;

import java.math.BigDecimal;

import org.colorcoding.ibas.bobas.common.Criteria;
import org.colorcoding.ibas.bobas.common.ICondition;
import org.colorcoding.ibas.bobas.common.ICriteria;
import org.colorcoding.ibas.bobas.common.IOperationResult;
import org.colorcoding.ibas.bobas.data.DateTime;
import org.colorcoding.ibas.bobas.data.Decimal;
import org.colorcoding.ibas.bobas.data.emApprovalStatus;
import org.colorcoding.ibas.bobas.data.emDocumentStatus;
import org.colorcoding.ibas.bobas.test.bo.IMaterials;
import org.colorcoding.ibas.bobas.test.bo.ISalesOrderItem;
import org.colorcoding.ibas.bobas.test.bo.Materials;
import org.colorcoding.ibas.bobas.test.bo.SalesOrder;
import org.colorcoding.ibas.bobas.test.logic.MaterialsQuantityJournal;
import org.colorcoding.ibas.bobas.test.logic.PurchaseOrder;
import org.colorcoding.ibas.bobas.test.logic.PurchaseOrderItem;
import org.colorcoding.ibas.bobas.test.repository.BORepositoryTest;

import junit.framework.TestCase;

public class TestBOLogics extends TestCase {

	public void testSalesOrderLogics() {
		BORepositoryTest boRepository = new BORepositoryTest();

		String sign = String.valueOf(DateTime.getNow().getTime());
		IMaterials material_1 = new Materials();
		material_1.setItemCode(String.format("A%s", sign));
		material_1.setItemDescription(String.format("CPU [%s]", sign));
		IOperationResult<?> operationResult = boRepository.saveMaterials(material_1);
		System.out.println(String.format("code:%s message:%s results:%s", operationResult.getResultCode(),
				operationResult.getMessage(), operationResult.getResultObjects().size()));
		assertEquals(operationResult.getResultCode(), 0);
		sign = String.valueOf(DateTime.getNow().getTime());
		IMaterials material_2 = new Materials();
		material_2.setItemCode(String.format("A%s", sign));
		material_2.setItemDescription(String.format("CPU [%s]", sign));
		operationResult = boRepository.saveMaterials(material_2);
		System.out.println(String.format("code:%s message:%s results:%s", operationResult.getResultCode(),
				operationResult.getMessage(), operationResult.getResultObjects().size()));
		assertEquals(operationResult.getResultCode(), 0);

		SalesOrder order = new SalesOrder();

		order.setCustomerCode("C00001");
		order.setDocumentStatus(emDocumentStatus.RELEASED);
		order.setApprovalStatus(emApprovalStatus.PROCESSING);
		ISalesOrderItem orderItem = order.getSalesOrderItems().create();
		orderItem.setItemCode(material_1.getItemCode());
		orderItem.setItemDescription(material_1.getItemDescription());
		orderItem.setQuantity(new BigDecimal(2));
		orderItem.setPrice(BigDecimal.valueOf(99.99));
		orderItem = order.getSalesOrderItems().create();
		orderItem.setItemCode(material_2.getItemCode());
		orderItem.setItemDescription(material_2.getItemDescription());
		orderItem.setQuantity(1);
		orderItem.setPrice(199.99);

		operationResult = boRepository.saveSalesOrder(order);
		System.out.println(String.format("code:%s message:%s results:%s", operationResult.getResultCode(),
				operationResult.getMessage(), operationResult.getResultObjects().size()));
		assertEquals(operationResult.getResultCode(), 0);

	}

	public void testMaterialsOrderQuantity() {
		// 创建物料数据
		IMaterials materials01 = new Materials();
		materials01.setItemCode(String.format("A%s", DateTime.getNow().getTime()));
		materials01.setItemDescription("CPU i7");
		IMaterials materials02 = new Materials();
		materials02.setItemCode(String.format("B%s", DateTime.getNow().getTime()));
		materials02.setItemDescription("Disk 5T");
		BORepositoryTest boRepository = new BORepositoryTest();
		IOperationResult<?> operationResult;

		operationResult = boRepository.saveMaterials(materials01);
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		operationResult = boRepository.saveMaterials(materials02);
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);

		// 创建采购订单
		PurchaseOrder order = new PurchaseOrder();
		order.setCustomerCode("C00001");
		order.setCustomerName("宇宙无敌影业");
		PurchaseOrderItem item01 = order.getPurchaseOrderItems().create();
		item01.setItemCode(materials01.getItemCode());
		item01.setItemDescription(materials01.getItemDescription());
		item01.setQuantity(1);
		item01.setPrice(999999.99);
		PurchaseOrderItem item02 = order.getPurchaseOrderItems().create();
		item02.setItemCode(materials02.getItemCode());
		item02.setItemDescription(materials02.getItemDescription());
		item02.setQuantity(2);
		item02.setPrice(99.00);
		PurchaseOrderItem item03 = order.getPurchaseOrderItems().create();
		item03.setItemCode(materials02.getItemCode());
		item03.setItemDescription(materials02.getItemDescription());
		item03.setQuantity(9);
		item03.setPrice(99.00);

		operationResult = boRepository.savePurchaseOrder(order);
		if (operationResult.getResultCode() != 0) {
			System.err.println(operationResult.getMessage());
		}
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);

		operationResult = boRepository.fetchMaterials(materials01.getCriteria());
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		IMaterials materials01s = (IMaterials) operationResult.getResultObjects().firstOrDefault();
		// 检索的物料是否一致
		assertEquals("materials not same.", materials01.getItemCode(), materials01s.getItemCode());
		// 订购数量是否增加
		assertEquals(String.format("wrong matrials [%s] order quantity.", materials01.getItemCode()),
				materials01.getOnOrder().add(item01.getQuantity()).floatValue(),
				materials01s.getOnOrder().floatValue());
		operationResult = boRepository.fetchMaterials(materials02.getCriteria());
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		IMaterials materials02s = (IMaterials) operationResult.getResultObjects().firstOrDefault();
		assertEquals("materials not same.", materials02.getItemCode(), materials02s.getItemCode());
		assertEquals(String.format("wrong matrials [%s] order quantity.", materials02.getItemCode()),
				materials02.getOnOrder().add(item02.getQuantity().add(item03.getQuantity())).floatValue(),
				materials02s.getOnOrder().floatValue());

		// 修改数量
		item01.setQuantity(20);
		operationResult = boRepository.savePurchaseOrder(order);
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);

		operationResult = boRepository.fetchMaterials(materials02.getCriteria());
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		materials02s = (IMaterials) operationResult.getResultObjects().firstOrDefault();
		assertEquals("materials not same.", materials02.getItemCode(), materials02s.getItemCode());
		assertEquals(String.format("wrong matrials [%s] order quantity.", materials02.getItemCode()),
				materials02.getOnOrder().add(item02.getQuantity().add(item03.getQuantity())).floatValue(),
				materials02s.getOnOrder().floatValue());

		operationResult = boRepository.fetchMaterials(materials01.getCriteria());
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		materials01s = (IMaterials) operationResult.getResultObjects().firstOrDefault();
		assertEquals(String.format("wrong matrials [%s] order quantity.", materials01.getItemCode()),
				materials01.getOnOrder().add(item01.getQuantity()).floatValue(),
				materials01s.getOnOrder().floatValue());

		// 删除数据
		item03.delete();
		operationResult = boRepository.savePurchaseOrder(order);
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);

		operationResult = boRepository.fetchMaterials(materials02.getCriteria());
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		materials02s = (IMaterials) operationResult.getResultObjects().firstOrDefault();
		assertEquals("materials not same.", materials02.getItemCode(), materials02s.getItemCode());
		assertEquals(String.format("wrong matrials [%s] order quantity.", materials02.getItemCode()),
				materials02.getOnOrder().add(item02.getQuantity()).floatValue(),
				materials02s.getOnOrder().floatValue());

	}

	public void testMaterialsJournal() {
		// 创建物料数据
		IMaterials materials01 = new Materials();
		materials01.setItemCode(String.format("A%s", DateTime.getNow().getTime()));
		materials01.setItemDescription("CPU i7");
		IMaterials materials02 = new Materials();
		materials02.setItemCode(String.format("B%s", DateTime.getNow().getTime()));
		materials02.setItemDescription("Disk 5T");
		// 保存物料到文件系统
		BORepositoryTest boRepository = new BORepositoryTest();
		IOperationResult<?> operationResult;

		operationResult = boRepository.saveMaterials(materials01);
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		operationResult = boRepository.saveMaterials(materials02);
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);

		// 创建采购订单
		PurchaseOrder order = new PurchaseOrder();
		order.setCustomerCode("C00001");
		order.setCustomerName("宇宙无敌影业");
		PurchaseOrderItem item01 = order.getPurchaseOrderItems().create();
		item01.setItemCode(materials01.getItemCode());
		item01.setItemDescription(materials01.getItemDescription());
		item01.setQuantity(1);
		item01.setPrice(999999.99);
		PurchaseOrderItem item02 = order.getPurchaseOrderItems().create();
		item02.setItemCode(materials02.getItemCode());
		item02.setItemDescription(materials02.getItemDescription());
		item02.setQuantity(2);
		item02.setPrice(99.00);
		PurchaseOrderItem item03 = order.getPurchaseOrderItems().create();
		item03.setItemCode(materials02.getItemCode());
		item03.setItemDescription(materials02.getItemDescription());
		item03.setQuantity(9);
		item03.setPrice(99.00);

		operationResult = boRepository.savePurchaseOrder(order);
		if (operationResult.getResultCode() != 0) {
			System.err.println(operationResult.getMessage());
		}
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);

		operationResult = boRepository.fetchMaterials(materials01.getCriteria());
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		IMaterials materials01s = (IMaterials) operationResult.getResultObjects().firstOrDefault();
		assertEquals("materials not same.", materials01.getItemCode(), materials01s.getItemCode());
		assertEquals(String.format("wrong matrials [%s] order quantity.", materials01.getItemCode()),
				materials01.getOnOrder().add(item01.getQuantity()).floatValue(),
				materials01s.getOnOrder().floatValue());
		assertEquals(String.format("wrong matrials [%s] hand quantity.", materials01.getItemCode()),
				materials01.getOnHand().add(item01.getQuantity()).floatValue(), materials01s.getOnHand().floatValue());
		operationResult = boRepository.fetchMaterials(materials02.getCriteria());
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		IMaterials materials02s = (IMaterials) operationResult.getResultObjects().firstOrDefault();
		assertEquals("materials not same.", materials02.getItemCode(), materials02s.getItemCode());
		assertEquals(String.format("wrong matrials [%s] order quantity.", materials02.getItemCode()),
				materials02.getOnOrder().add(item02.getQuantity().add(item03.getQuantity())).floatValue(),
				materials02s.getOnOrder().floatValue());
		assertEquals(String.format("wrong matrials [%s] hand quantity.", materials02.getItemCode()),
				materials02.getOnHand().add(item02.getQuantity().add(item03.getQuantity())).floatValue(),
				materials02s.getOnHand().floatValue());

		ICriteria criteria = Criteria.create();
		ICondition condition = criteria.getConditions().create();
		condition.setAlias(MaterialsQuantityJournal.PROPERTY_BASEDOCUMENTTYPE.getName());
		condition.setValue(item01.getObjectCode());
		condition = criteria.getConditions().create();
		condition.setAlias(MaterialsQuantityJournal.PROPERTY_BASEDOCUMENTENTRY.getName());
		condition.setValue(item01.getDocEntry());
		condition = criteria.getConditions().create();
		condition.setAlias(MaterialsQuantityJournal.PROPERTY_BASEDOCUMENTLINEID.getName());
		condition.setValue(item01.getLineId());
		operationResult = boRepository.fetchMaterialsQuantityJournal(criteria);
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		MaterialsQuantityJournal journal01 = (MaterialsQuantityJournal) operationResult.getResultObjects()
				.firstOrDefault();
		assertEquals("materials not same.", item01.getItemCode(), journal01.getItemCode());
		assertEquals(String.format("wrong matrials [%s] order quantity.", item01.getItemCode()),
				item01.getQuantity().floatValue(), journal01.getQuantity().floatValue());

		item01.setQuantity(20);
		item03.delete();
		operationResult = boRepository.savePurchaseOrder(order);
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);

		operationResult = boRepository.fetchMaterials(materials02.getCriteria());
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		materials02s = (IMaterials) operationResult.getResultObjects().firstOrDefault();
		assertEquals("materials not same.", materials02.getItemCode(), materials02s.getItemCode());
		assertEquals(String.format("wrong matrials [%s] order quantity.", materials02.getItemCode()),
				materials02.getOnOrder().add(item02.getQuantity()).floatValue(),
				materials02s.getOnOrder().floatValue());
		assertEquals(String.format("wrong matrials [%s] hand quantity.", materials02.getItemCode()),
				materials02.getOnHand().add(item02.getQuantity()).floatValue(), materials02s.getOnHand().floatValue());

		operationResult = boRepository.fetchMaterials(materials01.getCriteria());
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		materials01s = (IMaterials) operationResult.getResultObjects().firstOrDefault();
		assertEquals(String.format("wrong matrials [%s] order quantity.", materials01.getItemCode()),
				materials01.getOnOrder().add(item01.getQuantity()).floatValue(),
				materials01s.getOnOrder().floatValue());
		assertEquals(String.format("wrong matrials [%s] hand quantity.", materials01.getItemCode()),
				materials01.getOnHand().add(item01.getQuantity()).floatValue(), materials01s.getOnHand().floatValue());

		criteria = Criteria.create();
		condition = criteria.getConditions().create();
		condition.setAlias(MaterialsQuantityJournal.PROPERTY_BASEDOCUMENTTYPE.getName());
		condition.setValue(item03.getObjectCode());
		condition = criteria.getConditions().create();
		condition.setAlias(MaterialsQuantityJournal.PROPERTY_BASEDOCUMENTENTRY.getName());
		condition.setValue(item03.getDocEntry());
		condition = criteria.getConditions().create();
		condition.setAlias(MaterialsQuantityJournal.PROPERTY_BASEDOCUMENTLINEID.getName());
		condition.setValue(item03.getLineId());
		operationResult = boRepository.fetchMaterialsQuantityJournal(criteria);
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		journal01 = (MaterialsQuantityJournal) operationResult.getResultObjects().firstOrDefault();
		assertNull(journal01);

	}

	public void testRules() {
		// 保存物料到文件系统
		BORepositoryTest boRepository = new BORepositoryTest();
		IOperationResult<?> operationResult;
		// 创建物料数据
		IMaterials materials01 = new Materials();
		materials01.setItemCode(String.format("A%s", DateTime.getNow().getTime()));
		materials01.setItemDescription("CPU i7");
		operationResult = boRepository.saveMaterials(materials01);
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
		// 创建采购订单
		PurchaseOrder order = new PurchaseOrder();
		order.setCustomerCode("C00001");// 测试点,不能为空
		order.setCustomerName("宇宙无敌影业");
		PurchaseOrderItem item01 = order.getPurchaseOrderItems().create();// 测试点,要求有元素
		item01.setItemCode(materials01.getItemCode());// 测试点,子项检查,要求值
		item01.setItemDescription(materials01.getItemDescription());
		item01.setQuantity(33);// 测试点,数量大于0
		item01.setPrice(999999.99);
		System.out.println(String.format("line total %s", item01.getLineTotal()));
		assertEquals(Decimal.round(item01.getLineTotal())
				.compareTo(Decimal.round(item01.getQuantity().multiply(item01.getPrice()))) == 0, true);
		item01.setLineTotal(666.77);
		System.out.println(String.format("line price %s", item01.getPrice()));
		assertEquals(Decimal.round(item01.getPrice())
				.compareTo(Decimal.divide(item01.getLineTotal(), item01.getQuantity())) == 0, true);// 注意四舍五入
		operationResult = boRepository.savePurchaseOrder(order);
		if (operationResult.getResultCode() != 0) {
			System.err.println(operationResult.getMessage());
		}
		assertEquals(operationResult.getMessage(), operationResult.getResultCode(), 0);
	}

}