text:
// Copyright 2016-2022, University of Colorado Boulder

/**
 * model of a heating element with a beaker on it
 *
 * @author John Blanco
 */

import createObservableArray from '../../../../axon/js/createObservableArray.js';
import NumberProperty from '../../../../axon/js/NumberProperty.js';
import dotRandom from '../../../../dot/js/dotRandom.js';
import Range from '../../../../dot/js/Range.js';
import Vector2 from '../../../../dot/js/Vector2.js';
import merge from '../../../../phet-core/js/merge.js';
import { Image } from '../../../../scenery/js/imports.js';
import Tandem from '../../../../tandem/js/Tandem.js';
import ReferenceIO from '../../../../tandem/js/types/ReferenceIO.js';
import waterIcon_png from '../../../images/waterIcon_png.js';
import EFACConstants from '../../common/EFACConstants.js';
import Beaker from '../../common/model/Beaker.js';
import EnergyChunk from '../../common/model/EnergyChunk.js';
import EnergyContainerCategory from '../../common/model/EnergyContainerCategory.js';
import EnergyType from '../../common/model/EnergyType.js';
import HeatTransferConstants from '../../common/model/HeatTransferConstants.js';
import TemperatureAndColorSensor from '../../common/model/TemperatureAndColorSensor.js';
import energyFormsAndChanges from '../../energyFormsAndChanges.js';
import EnergyFormsAndChangesStrings from '../../EnergyFormsAndChangesStrings.js';
import EnergyChunkPathMover from './EnergyChunkPathMover.js';
import EnergyUser from './EnergyUser.js';

// position and size constants, empirically determined
const BEAKER_WIDTH = 0.075; // In meters.
const BEAKER_HEIGHT = BEAKER_WIDTH * 1.1;
const BEAKER_OFFSET = new Vector2( 0, 0.016 );
const HEATING_ELEMENT_ENERGY_CHUNK_VELOCITY = 0.0075; // in meters/sec, quite slow
const HEATER_ELEMENT_2D_HEIGHT = 0.027; // height of image
const MAX_HEAT_GENERATION_RATE = 5000; // Joules/sec, not connected to incoming energy
const HEAT_ENERGY_CHANGE_RATE = 0.5; // in proportion per second

// energy chunk path offsets, empirically determined such that they move through the view in a way that looks good
const LEFT_SIDE_OF_WIRE_OFFSET = new Vector2( -0.04, -0.041 );
const WIRE_CURVE_POINT_1_OFFSET = new Vector2( -0.02, -0.041 );
const WIRE_CURVE_POINT_2_OFFSET = new Vector2( -0.015, -0.04 );
const WIRE_CURVE_POINT_3_OFFSET = new Vector2( -0.005, -0.034 );
const WIRE_CURVE_POINT_4_OFFSET = new Vector2( -0.001, -0.027 );
const WIRE_CURVE_POINT_5_OFFSET = new Vector2( -0.0003, -0.02 );
const BOTTOM_OF_CONNECTOR_OFFSET = new Vector2( -0.0003, -0.01 );
const CONVERSION_POINT_OFFSET = new Vector2( 0, 0.003 );
const ELECTRICAL_ENERGY_CHUNK_OFFSETS = [
  WIRE_CURVE_POINT_1_OFFSET,
  WIRE_CURVE_POINT_2_OFFSET,
  WIRE_CURVE_POINT_3_OFFSET,
  WIRE_CURVE_POINT_4_OFFSET,
  WIRE_CURVE_POINT_5_OFFSET,
  BOTTOM_OF_CONNECTOR_OFFSET,
  CONVERSION_POINT_OFFSET
];

class BeakerHeater extends EnergyUser {

  /**
   * @param {BooleanProperty} energyChunksVisibleProperty
   * @param {EnergyChunkGroup} energyChunkGroup
   * @param {EnergyChunkPathMoverGroup} energyChunkPathMoverGroup
   * @param {Object} [options]
   */
  constructor( energyChunksVisibleProperty,
               energyChunkGroup,
               energyChunkPathMoverGroup,
               options ) {

    options = merge( {
      tandem: Tandem.REQUIRED,
      phetioState: false // no internal fields to convey in state
    }, options );

    super( new Image( waterIcon_png ), options );

    // @public {string} - a11y name
    this.a11yName = EnergyFormsAndChangesStrings.a11y.beakerOfWater;

    // @private
    this.energyChunksVisibleProperty = energyChunksVisibleProperty;
    this.energyChunkGroup = energyChunkGroup;
    this.energyChunkPathMoverGroup = energyChunkPathMoverGroup;

    // @public (read-only) {NumberProperty}
    this.heatProportionProperty = new NumberProperty( 0, {
      range: new Range( 0, 1 ),
      tandem: options.tandem.createTandem( 'heatProportionProperty' ),
      phetioReadOnly: true,
      phetioHighFrequency: true,
      phetioDocumentation: 'proportion of how much heat the coils have'
    } );

    // @private {ObservableArrayDef.<EnergyChunkPathMover>} - arrays that move the energy chunks as they move into, within, and out of the
    // beaker
    this.electricalEnergyChunkMovers = createObservableArray( {
      tandem: options.tandem.createTandem( 'electricalEnergyChunkMovers' ),
      phetioType: createObservableArray.ObservableArrayIO( ReferenceIO( EnergyChunkPathMover.EnergyChunkPathMoverIO ) )
    } );
    this.heatingElementEnergyChunkMovers = createObservableArray( {
      tandem: options.tandem.createTandem( 'heatingElementEnergyChunkMovers' ),
      phetioType: createObservableArray.ObservableArrayIO( ReferenceIO( EnergyChunkPathMover.EnergyChunkPathMoverIO ) )
    } );
    this.radiatedEnergyChunkMovers = createObservableArray( {
      tandem: options.tandem.createTandem( 'radiatedEnergyChunkMovers' ),
      phetioType: createObservableArray.ObservableArrayIO( ReferenceIO( EnergyChunkPathMover.EnergyChunkPathMoverIO ) )
    } );

    // @public (read-only) {ObservableArrayDef} - energy chunks that are radiated by this beaker
    this.radiatedEnergyChunkList = createObservableArray( {
      tandem: options.tandem.createTandem( 'radiatedEnergyChunkList' ),
      phetioType: createObservableArray.ObservableArrayIO( ReferenceIO( EnergyChunk.EnergyChunkIO ) )
    } );

    // @private {Tandem} - used for instrumenting the water beaker and the thermometer's sensedElementNameProperty
    this.waterBeakerTandem = options.tandem.createTandem( 'waterBeaker' );

    // @public {Beaker} (read-only) - note that the position is absolute, not relative to the "parent" model element
    this.beaker = new Beaker(
      this.positionProperty.value.plus( BEAKER_OFFSET ),
      BEAKER_WIDTH,
      BEAKER_HEIGHT,
      energyChunksVisibleProperty,
      energyChunkGroup, {
        tandem: this.waterBeakerTandem,
        phetioDocumentation: 'beaker that contains water',
        userControllable: false
      }
    );

    // @public {TemperatureAndColorSensor} (read-only)
    this.thermometer = new TemperatureAndColorSensor(
      this,
      new Vector2( BEAKER_WIDTH * 0.45, BEAKER_HEIGHT * 0.6 ), // position is relative, not absolute
      true, {
        tandem: options.tandem.createTandem( 'thermometer' ),
        userControllable: false
      }
    );

    // @private, for convenience
    this.random = dotRandom;

    // move the beaker as the overall position changes
    this.positionProperty.link( position => {
      this.beaker.positionProperty.value = position.plus( BEAKER_OFFSET );
    } );
  }

  /**
   * @param  {number} dt - time step, in seconds
   * @param  {Energy} incomingEnergy
   * @public
   * @override
   */
  step( dt, incomingEnergy ) {
    if ( !this.activeProperty.value ) {
      return;
    }

    // this isn't designed to take in anything other than electrical energy, so make sure that's what we've got
    assert && assert( incomingEnergy.type === EnergyType.ELECTRICAL, `unexpected energy type: ${incomingEnergy.type}` );

    // handle any incoming energy chunks
    if ( this.incomingEnergyChunks.length > 0 ) {
      this.incomingEnergyChunks.forEach( chunk => {

        assert && assert(
          chunk.energyTypeProperty.value === EnergyType.ELECTRICAL,
          `Energy chunk type should be ELECTRICAL but is ${chunk.energyTypeProperty.value}`
        );

        // add the energy chunk to the list of those under management
        this.energyChunkList.push( chunk );

        // add a "mover" that will move this energy chunk through the wire to the heating element
        this.electricalEnergyChunkMovers.push( this.energyChunkPathMoverGroup.createNextElement( chunk,
          EnergyChunkPathMover.createPathFromOffsets( this.positionProperty.get(), ELECTRICAL_ENERGY_CHUNK_OFFSETS ),
          EFACConstants.ENERGY_CHUNK_VELOCITY ) );
      } );

      // clear incoming chunks array
      this.incomingEnergyChunks.clear();
    }
    this.moveElectricalEnergyChunks( dt );
    this.moveThermalEnergyChunks( dt );

    // set the proportion of max heat being generated by the heater element
    if ( this.energyChunksVisibleProperty.value ) {

      // Energy chunks are visible, so set the heat level based on the number of them that are on the burner.  This
      // calculation uses a shifted sigmoid function so that it will asymptotically approach one as more energy chunks
      // are present.  It was empirically determined by looking at the incoming energy rate versus the number of energy
      // chunks present when the system has been producing energy steadily for long enough that the energy chunks have
      // propagated all the way through.
      const currentHeatProportion = this.heatProportionProperty.value;
      const targetHeatProportion = 2 / ( 1 + Math.pow( Math.E, -this.heatingElementEnergyChunkMovers.length ) ) - 1;
      if ( targetHeatProportion > currentHeatProportion ) {
        this.heatProportionProperty.set(
          Math.min( targetHeatProportion, currentHeatProportion + HEAT_ENERGY_CHANGE_RATE * dt )
        );
      }
      else if ( targetHeatProportion < currentHeatProportion ) {
        this.heatProportionProperty.set(
          Math.max( targetHeatProportion, currentHeatProportion - HEAT_ENERGY_CHANGE_RATE * dt )
        );
      }
    }
    else {

      // set the heat proportion based on the incoming energy amount, but moderate the rate at which it changes
      const energyFraction = incomingEnergy.amount / ( EFACConstants.MAX_ENERGY_PRODUCTION_RATE * dt );
      this.heatProportionProperty.set(
        Math.min( energyFraction, this.heatProportionProperty.value + HEAT_ENERGY_CHANGE_RATE * dt )
      );
    }

    // add energy to the beaker based on heat coming from heat element
    this.beaker.changeEnergy( this.heatProportionProperty.value * MAX_HEAT_GENERATION_RATE * dt );

    // remove energy from the beaker based on loss of heat to the surrounding air
    const temperatureGradient = this.beaker.getTemperature() - EFACConstants.ROOM_TEMPERATURE;
    if ( Math.abs( temperatureGradient ) > EFACConstants.TEMPERATURES_EQUAL_THRESHOLD ) {
      const beakerRect = this.beaker.getUntransformedBounds();
      const thermalContactArea = ( beakerRect.width * 2 ) + ( beakerRect.height * 2 ) * this.beaker.fluidProportionProperty.value;
      const transferFactor = HeatTransferConstants.getHeatTransferFactor(
        EnergyContainerCategory.WATER, EnergyContainerCategory.AIR );
      const thermalEnergyLost = temperatureGradient * transferFactor * thermalContactArea * dt;

      this.beaker.changeEnergy( -thermalEnergyLost );

      if ( this.beaker.getEnergyBeyondMaxTemperature() > 0 ) {
        // Prevent the water from going beyond the boiling point.
        this.beaker.changeEnergy( -this.beaker.getEnergyBeyondMaxTemperature() );
      }
    }

    this.beaker.step( dt );

    if ( this.beaker.getEnergyChunkBalance() > 0 ) {

      // remove an energy chunk from the beaker and start it floating away, a.k.a. make it "radiate"
      const bounds = this.beaker.getBounds();
      const extractionPoint = new Vector2( bounds.minX + dotRandom.nextDouble() * bounds.width, bounds.maxY );
      const ec = this.beaker.extractEnergyChunkClosestToPoint( extractionPoint );

      if ( ec ) {
        ec.zPositionProperty.set( 0 ); // move to front of z order
        this.radiatedEnergyChunkList.push( ec );
        this.radiatedEnergyChunkMovers.push(
          this.energyChunkPathMoverGroup.createNextElement(
            ec,
            EnergyChunkPathMover.createRadiatedPath( ec.positionProperty.value, 0 ),
            EFACConstants.ENERGY_CHUNK_VELOCITY
          )
        );
      }
    }

    this.moveRadiatedEnergyChunks( dt );

    // step sub-elements
    this.thermometer.step();
  }

  /**
   * update the temperature and color at the specified position within the beaker
   *
   * @param {Vector2} position - position to be sensed
   * @param {Property.<number>} sensedTemperatureProperty
   * @param {Property.<Color>} sensedElementColorProperty
   * @public
   */
  updateTemperatureAndColorAndNameAtPosition(
    position,
    sensedTemperatureProperty,
    sensedElementColorProperty,
    sensedElementNameProperty
  ) {

    // validate that the specified position is inside the beaker, since that's the only supported position
    assert && assert(
    position.x >= BEAKER_OFFSET.x - BEAKER_WIDTH / 2 && position.x <= BEAKER_OFFSET.x + BEAKER_WIDTH / 2,
      'position is not inside of beaker'
    );
    assert && assert(
    position.y >= BEAKER_OFFSET.y - BEAKER_HEIGHT / 2 && position.y <= BEAKER_OFFSET.y + BEAKER_HEIGHT / 2,
      'position is not inside of beaker'
    );

    sensedTemperatureProperty.set( this.beaker.getTemperature() );
    sensedElementColorProperty.set( EFACConstants.WATER_COLOR_OPAQUE );
    sensedElementNameProperty.set( this.waterBeakerTandem.phetioID );
  }

  /**
   * @param  {number} dt - time step, in seconds
   * @private
   */
  moveRadiatedEnergyChunks( dt ) {
    const movers = this.radiatedEnergyChunkMovers.slice();

    movers.forEach( mover => {
      mover.moveAlongPath( dt );

      if ( mover.pathFullyTraversed ) {

        // remove this energy chunk entirely
        this.radiatedEnergyChunkList.remove( mover.energyChunk );
        this.radiatedEnergyChunkMovers.remove( mover );
        this.energyChunkGroup.disposeElement( mover.energyChunk );
        this.energyChunkPathMoverGroup.disposeElement( mover );
      }
    } );
  }

  /**
   * @param  {number} dt - time step, in seconds
   * @private
   */
  moveThermalEnergyChunks( dt ) {
    const movers = this.heatingElementEnergyChunkMovers.slice();

    movers.forEach( mover => {
      mover.moveAlongPath( dt );

      if ( mover.pathFullyTraversed ) {

        // This chunk is ready to move to the beaker.  We remove it from here, and the beaker takes over management of
        // the chunk.
        this.beaker.addEnergyChunk( mover.energyChunk );
        this.energyChunkList.remove( mover.energyChunk );
        this.heatingElementEnergyChunkMovers.remove( mover );
        this.energyChunkPathMoverGroup.disposeElement( mover );
      }
    } );
  }

  /**
   * @param  {number} dt - time step, in seconds
   * @private
   */
  moveElectricalEnergyChunks( dt ) {
    const movers = this.electricalEnergyChunkMovers.slice();

    movers.forEach( mover => {
      mover.moveAlongPath( dt );

      if ( mover.pathFullyTraversed ) {

        // the electrical energy chunk has reached the burner, so it needs to change into thermal energy
        this.electricalEnergyChunkMovers.remove( mover );
        mover.energyChunk.energyTypeProperty.set( EnergyType.THERMAL );

        // have the thermal energy move a little on the element before moving into the beaker
        this.heatingElementEnergyChunkMovers.push( this.energyChunkPathMoverGroup.createNextElement( mover.energyChunk,
          this.createHeaterElementEnergyChunkPath( mover.energyChunk.positionProperty.get() ),
          HEATING_ELEMENT_ENERGY_CHUNK_VELOCITY ) );
        this.energyChunkPathMoverGroup.disposeElement( mover );
      }
    } );
  }

  /**
   * @param  {Energy} incomingEnergyRate
   * @public
   * @override
   */
  preloadEnergyChunks( incomingEnergyRate ) {
    this.clearEnergyChunks();

    if ( incomingEnergyRate.amount === 0 || incomingEnergyRate.type !== EnergyType.ELECTRICAL ) {
      // no energy chunk pre-loading needed
      return;
    }

    const dt = 1 / EFACConstants.FRAMES_PER_SECOND;
    let energySinceLastChunk = EFACConstants.ENERGY_PER_CHUNK * 0.99;

    // simulate energy chunks moving through the system
    let preloadComplete = false;
    while ( !preloadComplete ) {
      energySinceLastChunk += incomingEnergyRate.amount * dt;

      // determine if time to add a new chunk
      if ( energySinceLastChunk >= EFACConstants.ENERGY_PER_CHUNK ) {

        // create and add a new chunk
        const newEnergyChunk = this.energyChunkGroup.createNextElement(
          EnergyType.ELECTRICAL,
          this.positionProperty.get().plus( LEFT_SIDE_OF_WIRE_OFFSET ),
          Vector2.ZERO,
          this.energyChunksVisibleProperty
        );
        this.energyChunkList.push( newEnergyChunk );

        // add a "mover" that will move this energy chunk through the wire to the heating element
        this.electricalEnergyChunkMovers.push( this.energyChunkPathMoverGroup.createNextElement( newEnergyChunk,
          EnergyChunkPathMover.createPathFromOffsets( this.positionProperty.get(), ELECTRICAL_ENERGY_CHUNK_OFFSETS ),
          EFACConstants.ENERGY_CHUNK_VELOCITY )
        );

        // update energy since last chunk
        energySinceLastChunk -= EFACConstants.ENERGY_PER_CHUNK;
      }

      this.moveElectricalEnergyChunks( dt );

      if ( this.heatingElementEnergyChunkMovers.length > 0 ) {

        // an energy chunk has made it to the heating element, which completes the preload
        preloadComplete = true;
      }
    }
  }

  /**
   * @public
   * @override
   */
  deactivate() {
    super.deactivate();
    this.beaker.reset();
    this.beaker.positionProperty.value = this.positionProperty.value.plus( BEAKER_OFFSET );
    this.heatProportionProperty.set( 0 );

    // step the thermometer so that any temperature changes resulting from the reset are immediately reflected
    this.thermometer.step();
  }

  /**
   * remove all energy chunks
   * @public
   * @override
   */
  clearEnergyChunks() {
    super.clearEnergyChunks();

    this.electricalEnergyChunkMovers.forEach( mover => this.energyChunkPathMoverGroup.disposeElement( mover ) );
    this.electricalEnergyChunkMovers.clear();
    this.heatingElementEnergyChunkMovers.forEach( mover => this.energyChunkPathMoverGroup.disposeElement( mover ) );
    this.heatingElementEnergyChunkMovers.clear();
    this.radiatedEnergyChunkMovers.forEach( mover => this.energyChunkPathMoverGroup.disposeElement( mover ) );
    this.radiatedEnergyChunkMovers.clear();
    this.radiatedEnergyChunkList.forEach( chunk => this.energyChunkGroup.disposeElement( chunk ) );
    this.radiatedEnergyChunkList.clear();
  }

  /**
   * @param  {Vector2} startingPoint
   * @returns {Vector2[]}
   * @private
   */
  createHeaterElementEnergyChunkPath( startingPoint ) {
    const path = [];

    // The path for the thermal energy chunks is meant to look like it is moving on the burner element.  This must be
    // updated if the burner element image changes.
    const angleSpan = Math.PI * 0.75;
    const angle = Math.PI / 2 + ( this.random.nextDouble() - 0.5 ) * angleSpan;

    // Calculate a travel distance that will move farther to the left and right, less in the middle, to match the
    // elliptical shape of the burner in the view, see https://github.com/phetsims/energy-forms-and-changes/issues/174.
    const travelDistance = ( 0.6 + Math.abs( Math.cos( angle ) ) * 0.3 ) * HEATER_ELEMENT_2D_HEIGHT;
    path.push( startingPoint.plus( new Vector2( travelDistance, 0 ).rotated( angle ) ) );
    return path;
  }
}

BeakerHeater.HEATER_ELEMENT_2D_HEIGHT = HEATER_ELEMENT_2D_HEIGHT;

energyFormsAndChanges.register( 'BeakerHeater', BeakerHeater );
export default BeakerHeater;


text:
<select id="select">
	<option selected></option>
	<option>Option 1</option>
	<option>Option 2</option>
	<option>Option 3</option>
</select>

redpajama_set_name: RedPajamaGithub


text:
using System.Configuration;

namespace InstagramFeed.Azure
{
    public class AzureSettings
    {
        public string ConnectionString { get; set; }

        private static AzureSettings _settings;

        /// <summary>
        /// Gets instance of config section.
        /// </summary>
        /// <returns></returns>
        public static AzureSettings Instance
        {
            get
            {
                if (_settings == null)
                {
                    const string settingsNodeName = "instagramFeedAzureSettings";
                    _settings = ConfigurationManager.GetSection(settingsNodeName) as AzureSettings;
                    if (_settings == null)
                        throw new ConfigurationErrorsException(string.Format("App.config is missing expected section '{0}'.", settingsNodeName));
                }

                return _settings;
            }
        }
    }
}


text:
import numpy as np
import gym

from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
from keras.optimizers import Adam

from rl.agents.sarsa import SarsaAgent
from rl.policy import BoltzmannQPolicy

ENV_NAME = 'CartPole-v0'

# Get the environment and extract the number of actions.
env = gym.make(ENV_NAME)
np.random.seed(123)
env.seed(123)
nb_actions = env.action_space.n

# Next, we build a very simple model.
model = Sequential()
model.add(Flatten(input_shape=(1,) + env.observation_space.shape))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(nb_actions))
model.add(Activation('linear'))
print(model.summary())

# Sarsa.py in rl.agent update every experience on policy, memory is not used.
policy = BoltzmannQPolicy()
sarsa = SarsaAgent(model=model, nb_actions=nb_actions, nb_steps_warmup=10, policy=policy)
sarsa.compile(Adam(lr=1e-3), metrics=['mae'])

# Okay, now it's time to learn something! We visualize the training here for show, but this
# slows down training quite a lot. You can always safely abort the training prematurely using
# Ctrl + C.
sarsa.fit(env, nb_steps=5000, visualize=False, verbose=2)

# After training is done, we save the final weights.
sarsa.save_weights('sarsa_{}_weights.h5f'.format(ENV_NAME), overwrite=True)

# Finally, evaluate our algorithm for 5 episodes.
sarsa.test(env, nb_episodes=5, visualize=False)


text:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:ignore="UselessParent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:orientation="vertical"
            android:paddingBottom="15dp" >

            <TextView
                android:id="@+id/tvTipoIndicador"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="@string/tvTipoIndicador"
                android:textSize="18sp" />

            <Spinner
                android:id="@+id/spTipo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="8dp"
                android:paddingBottom="8dp"
                android:textSize="20sp"
                android:prompt="@string/spTipo" />

            <TextView
                android:id="@+id/tvMedida1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="@string/tvMedida1"
                android:textSize="20sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp" >

                <EditText
                    android:id="@+id/etMedida1"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.24"
                    android:inputType="numberDecimal"
                    android:textSize="22sp" >
                </EditText>

                <TextView
                    android:id="@+id/tvUnidade1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="10dp"
                    android:text="@string/tvUnidade"
                    android:textSize="20sp" />

            </LinearLayout>

            <TextView
                android:id="@+id/tvMedida2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="@string/tvMedida2"
                android:textSize="20sp" />

           	<LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp" >

                <EditText
                    android:id="@+id/etMedida2"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.24"
                    android:inputType="numberDecimal"
                    android:textSize="22sp" >
                </EditText>

                <TextView
                    android:id="@+id/tvUnidade2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="10dp"
                    android:text="@string/tvUnidade"
                    android:textSize="20sp" />
            </LinearLayout>

            <Button
                android:id="@+id/btSave"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="32dp"
                android:text="@string/btSalvar"
                android:textSize="26sp" />
        </LinearLayout>

	</ScrollView>

</LinearLayout>


text:
package com.github.atave.junderscore;

/**
 * Iterates over an {@link Iterable}, yielding each value in turn to a function.
 *
 * @param <T> the type of each value
 */
public abstract class _each<T> {

    protected abstract void process(T object);

    public void on(Iterable<T> iterable) {
        for (T o : iterable) {
            process(o);
        }
    }
}


text:
package org.pdxfinder.services;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.pdxfinder.graph.dao.DataProjection;
import org.pdxfinder.graph.dao.ModelCreation;
import org.pdxfinder.graph.dao.TreatmentProtocol;
import org.pdxfinder.graph.dao.TreatmentSummary;
import org.pdxfinder.graph.repositories.*;
import org.pdxfinder.services.dto.CountDTO;
import org.springframework.stereotype.Service;

import java.util.*;

/*
 * Created by csaba on 29/03/2018.
 */
@Service
public class DrugService {

    private TreatmentSummaryRepository treatmentSummaryRepository;
    private TreatmentProtocolRepository treatmentProtocolRepository;
    private ResponseRepository responseRepository;
    private ModelCreationRepository modelCreationRepository;
    private DataProjectionRepository dataProjectionRepository;

    public DrugService(TreatmentSummaryRepository treatmentSummaryRepository,
                       TreatmentProtocolRepository treatmentProtocolRepository,
                       ResponseRepository responseRepository,
                       ModelCreationRepository modelCreationRepository,
                       DataProjectionRepository dataProjectionRepository) {

        this.treatmentSummaryRepository = treatmentSummaryRepository;
        this.treatmentProtocolRepository = treatmentProtocolRepository;
        this.responseRepository = responseRepository;
        this.modelCreationRepository = modelCreationRepository;
        this.dataProjectionRepository = dataProjectionRepository;
    }

    public int getDosingStudiesNumberByDataSource(String dataSource){

        return treatmentSummaryRepository.findDrugDosingStudyNumberByDataSource(dataSource);
    }

    public String getPlatformUrlByDataSource(String dataSource){

        return treatmentSummaryRepository.findPlatformUrlByDataSource(dataSource);
    }

    public List<String> getDrugNames(){

        Set<String> drugNamesSet = new HashSet<>();
        List<String> drugNames = new ArrayList<>();

        List<TreatmentSummary> treatmentSummaries = getModelTreatmentSummariesWithDrugAndResponse();

        for(TreatmentSummary ts : treatmentSummaries){

            for(TreatmentProtocol tp : ts.getTreatmentProtocols()){

                String drugName = tp.getTreatmentString(false);
                drugNamesSet.add(drugName);
            }
        }

        drugNames.addAll(drugNamesSet);
        return drugNames;
    }

    public List<String> getSpecimenDrugResponseOptions(){

        return responseRepository.findAllSpecimenDrugResponses();
    }

    public List<TreatmentSummary> getModelTreatmentSummariesWithDrugAndResponse(){

        return treatmentSummaryRepository.findAllMouseTreatments();
    }

    public List<TreatmentSummary> getPatientTreatmentSummariesWithDrug(){

        return treatmentSummaryRepository.findAllPatientTreatments();
    }

    public int getTotalSummaryNumber(){

        return treatmentSummaryRepository.findTotalSummaryNumber();
    }

    public List<CountDTO> getModelCountByDrugAndComponentType(String type){

        Map<String, Set<String>> results = new HashMap<>();
        Set<ModelCreation> models = modelCreationRepository.getModelsTreatmentsAndDrugs(type);
        List<CountDTO> res = new ArrayList<CountDTO>();

        for(ModelCreation mod : models){
            String modelId = mod.getDataSource() + mod.getSourcePdxId();
            for(TreatmentProtocol tp : mod.getTreatmentSummary().getTreatmentProtocols()){

                String drugName = tp.getTreatmentString(false);

                if(results.containsKey(drugName)){

                    results.get(drugName).add(modelId);
                }
                else{
                    Set s = new HashSet();
                    s.add(modelId);
                    results.put(drugName, s);
                }
            }
        }

        for(Map.Entry<String, Set<String>> entry : results.entrySet()){

            CountDTO c = new CountDTO(entry.getKey(), entry.getValue().size());
            res.add(c);
        }

        Collections.sort(res, (CountDTO c1, CountDTO c2) -> c2.getValue()-c1.getValue());

        return res;

    }

    public List<CountDTO> getModelCountByDrugs(){

        DataProjection dp = dataProjectionRepository.findByLabel("drug dosing counter");

        List<CountDTO> result = new ArrayList<>();
        Map<String, Set<Long>> data = new HashMap<>();
        String responses = "{}";

        if(dp != null) responses = dp.getValue();

        try{
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            data = mapper.readValue(responses, new TypeReference<Map<String, Set<Long>>>(){});
        }
        catch(Exception e){
            e.printStackTrace();
        }

        for(Map.Entry<String, Set<Long>> entry : data.entrySet()){
            CountDTO c = new CountDTO(entry.getKey(), entry.getValue().size());
            result.add(c);
        }

        Collections.sort(result, (CountDTO c1, CountDTO c2) -> c2.getValue()-c1.getValue());

        return result;
    }

}


text:
The ATRSHMLOG shmbininternalfiles script.  {#files_shmbininternalfiles_script}
====================================

The file is a list of all files that are created
from the link of the module to a object file
and an internal object.

The file is used in makeall.

If you create a new file and you want to make it with makeall add it to
the list  in this file.

Note: The iternal object is gone for now, so its a simple link.


text:
package org.jbpm.runtime.manager.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.jbpm.runtime.manager.util.TestUtil;
import org.jbpm.services.task.identity.JBossUserGroupCallbackImpl;
import org.jbpm.test.util.AbstractBaseTest;
import org.jbpm.test.util.PoolingDataSource;
import org.jbpm.workflow.instance.WorkflowProcessInstance;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.runtime.conf.ClockTypeOption;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.manager.RuntimeEnvironment;
import org.kie.api.runtime.manager.RuntimeEnvironmentBuilder;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.runtime.manager.RuntimeManagerFactory;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItem;
import org.kie.api.runtime.process.WorkItemHandler;
import org.kie.api.runtime.process.WorkItemManager;
import org.kie.api.task.UserGroupCallback;
import org.kie.api.task.model.TaskSummary;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.runtime.manager.context.EmptyContext;
import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext;
import org.kie.scanner.KieMavenRepository;

import static org.junit.Assert.*;
import static org.kie.scanner.KieMavenRepository.getKieMavenRepository;

public class KjarRuntimeEnvironmentTest extends AbstractBaseTest {

    private PoolingDataSource pds;
    private UserGroupCallback userGroupCallback;
    private RuntimeManager manager;

    private static final String ARTIFACT_ID = "kjar-module";
    private static final String GROUP_ID = "org.jbpm.test";
    private static final String VERSION = "1.0.0-SNAPSHOT";

    @Before
    public void setup() {
    	TestUtil.cleanupSingletonSessionId();
    	KieServices ks = KieServices.Factory.get();
        ReleaseId releaseId = ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION);
        List<String> processes = new ArrayList<String>();
        processes.add("BPMN2-ScriptTask.bpmn2");
        processes.add("BPMN2-UserTask.bpmn2");
        processes.add("BPMN2-CustomTask.bpmn2");

        InternalKieModule kJar1 = createKieJar(ks, releaseId, processes);
        File pom = new File("target/kmodule", "pom.xml");
        pom.getParentFile().mkdir();
        try {
            FileOutputStream fs = new FileOutputStream(pom);
            fs.write(getPom(releaseId).getBytes());
            fs.close();
        } catch (Exception e) {

        }
        KieMavenRepository repository = getKieMavenRepository();
        repository.installArtifact(releaseId, kJar1, pom);

        Properties properties= new Properties();
        properties.setProperty("mary", "HR");
        properties.setProperty("john", "HR");
        userGroupCallback = new JBossUserGroupCallbackImpl(properties);

        pds = TestUtil.setupPoolingDataSource();
    }

    @After
    public void teardown() {
    	if (manager != null) {
    		manager.close();
    	}
        pds.close();
    }

    @Test
    public void testCustomTaskFromKjar() {
    	KieServices ks = KieServices.Factory.get();

    	RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get()
    			.newDefaultBuilder(ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION))
                .userGroupCallback(userGroupCallback)
                .get();

        manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
        assertNotNull(manager);

        RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
        assertNotNull(engine);

        Map<String, Object> params = new HashMap<String, Object>();

        ProcessInstance processInstance = engine.getKieSession().startProcess("customtask", params);

        assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());

    }

    @Test
    public void testScriptTaskFromKjar() {
    	KieServices ks = KieServices.Factory.get();

    	RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get()
    			.newDefaultBuilder(ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION))
                .userGroupCallback(userGroupCallback)
                .get();

        manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
        assertNotNull(manager);

        RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
        assertNotNull(engine);

        Map<String, Object> params = new HashMap<String, Object>();

        ProcessInstance processInstance = engine.getKieSession().startProcess("ScriptTask", params);

        assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());

    }

    @Test
    public void testScriptTaskFromKjarUsingNamedKbaseKsession() {
    	KieServices ks = KieServices.Factory.get();

    	RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get()
    			.newDefaultBuilder(ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION), "defaultKieBase", "defaultKieSession")
                .userGroupCallback(userGroupCallback)
                .get();

        manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
        assertNotNull(manager);

        RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
        assertNotNull(engine);

        Map<String, Object> params = new HashMap<String, Object>();

        ProcessInstance processInstance = engine.getKieSession().startProcess("ScriptTask", params);

        assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());

    }

    @Test
    public void testUserTaskFromKjar() {
    	KieServices ks = KieServices.Factory.get();

    	RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get()
    			.newDefaultBuilder(ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION))
                .userGroupCallback(userGroupCallback)
                .get();

        manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
        assertNotNull(manager);

        RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
        assertNotNull(engine);

        Map<String, Object> params = new HashMap<String, Object>();

        ProcessInstance processInstance = engine.getKieSession().startProcess("UserTask", params);

        List<TaskSummary> tasks = engine.getTaskService().getTasksAssignedAsPotentialOwner("john", "en-UK");
        assertNotNull(tasks);
        assertEquals(1, tasks.size());

        long taskId = tasks.get(0).getId();

        engine.getTaskService().start(taskId, "john");
        engine.getTaskService().complete(taskId, "john", null);

        processInstance = engine.getKieSession().getProcessInstance(processInstance.getId());
        assertNull(processInstance);

        manager.disposeRuntimeEngine(engine);

    }

    @Test
    public void testScriptTaskFromKjarByName() {

    	RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get()
    			.newDefaultBuilder(GROUP_ID, ARTIFACT_ID, VERSION)
                .userGroupCallback(userGroupCallback)
                .get();

        manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
        assertNotNull(manager);

        RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
        assertNotNull(engine);

        Map<String, Object> params = new HashMap<String, Object>();

        ProcessInstance processInstance = engine.getKieSession().startProcess("ScriptTask", params);

        assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());

    }

    @Test
    public void testScriptTaskFromKjarByNameNamedKbaseKsession() {

    	RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get()
    			.newDefaultBuilder(GROUP_ID, ARTIFACT_ID, VERSION, "defaultKieBase", "defaultKieSession")
                .userGroupCallback(userGroupCallback)
                .get();

        manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
        assertNotNull(manager);

        RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
        assertNotNull(engine);

        Map<String, Object> params = new HashMap<String, Object>();

        ProcessInstance processInstance = engine.getKieSession().startProcess("ScriptTask", params);

        assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());

    }

    @Test
    public void testScriptTaskFromClasspathContainer() {

    	RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get()
    			.newClasspathKmoduleDefaultBuilder()
                .userGroupCallback(userGroupCallback)
                .get();

        manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
        assertNotNull(manager);

        RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
        assertNotNull(engine);

        Map<String, Object> params = new HashMap<String, Object>();

        ProcessInstance processInstance = engine.getKieSession().startProcess("ScriptTask", params);

        assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());

    }

    @Test
    public void testScriptTaskFromClasspathContainerNamedKbaseKsession() {

    	RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get()
    			.newClasspathKmoduleDefaultBuilder("defaultKieBase", "defaultKieSession")
                .userGroupCallback(userGroupCallback)
                .get();

        manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
        assertNotNull(manager);

        RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
        assertNotNull(engine);

        Map<String, Object> params = new HashMap<String, Object>();

        ProcessInstance processInstance = engine.getKieSession().startProcess("ScriptTask", params);

        assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());

    }

    @Test
    public void testUserTaskFromKjarPPI() {
    	KieServices ks = KieServices.Factory.get();

    	RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get()
    			.newDefaultBuilder(ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION))
                .userGroupCallback(userGroupCallback)
                .get();

        manager = RuntimeManagerFactory.Factory.get().newPerProcessInstanceRuntimeManager(environment);
        assertNotNull(manager);

        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get());
        assertNotNull(engine);

        Map<String, Object> params = new HashMap<String, Object>();

        ProcessInstance processInstance = engine.getKieSession().startProcess("UserTask", params);

        manager.disposeRuntimeEngine(engine);
        engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstance.getId()));

        List<TaskSummary> tasks = engine.getTaskService().getTasksAssignedAsPotentialOwner("john", "en-UK");
        assertNotNull(tasks);
        assertEquals(1, tasks.size());

        long taskId = tasks.get(0).getId();

        manager.disposeRuntimeEngine(engine);
        engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstance.getId()));

        engine.getTaskService().start(taskId, "john");

        manager.disposeRuntimeEngine(engine);
        engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstance.getId()));

        engine.getTaskService().complete(taskId, "john", null);

        manager.disposeRuntimeEngine(engine);
        try {
	        engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstance.getId()));

	        processInstance = engine.getKieSession().getProcessInstance(processInstance.getId());
	        assertNull(processInstance);
	        fail("Should fail as process instance is already completed");
        } catch (Exception e) {

        }
        manager.disposeRuntimeEngine(engine);

    }

    @Test
    public void testXStreamUnmarshalCustomObject() {
        KieServices ks = KieServices.Factory.get();
        ReleaseId releaseId = ks.newReleaseId(GROUP_ID, "xstream-test", VERSION);
        File kjar = new File("src/test/resources/kjar/jbpm-module.jar");
        File pom = new File("src/test/resources/kjar/pom.xml");
        KieMavenRepository repository = getKieMavenRepository();
        repository.installArtifact(releaseId, kjar, pom);

        RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get()
                .newDefaultBuilder(releaseId)
                .registerableItemsFactory(new DefaultRegisterableItemsFactory() {

                    @Override
                    public Map<String, WorkItemHandler> getWorkItemHandlers(RuntimeEngine runtime) {
                        Map<String, WorkItemHandler> handlers = super.getWorkItemHandlers(runtime);
                        handlers.put("Rest", new WorkItemHandler() {

                            @Override
                            public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
                                Map<String, Object> results = new HashMap<String, Object>();
                                results.put("Result", "<pv207.finepayment.Client><exists>true</exists><name>Pavel</name></pv207.finepayment.Client>");

                                manager.completeWorkItem(workItem.getId(), results);
                            }

                            @Override
                            public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
                            }
                        });

                        return handlers;
                    }

                })
                .userGroupCallback(userGroupCallback)
                .get();

        manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
        assertNotNull(manager);

        RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
        assertNotNull(engine);

        Map<String, Object> params = new HashMap<String, Object>();

        ProcessInstance processInstance = engine.getKieSession().startProcess("RESTTask.RestProcess", params);

        assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());

        Object processClient = ((WorkflowProcessInstance)processInstance).getVariable("processClient");
        assertNotNull(processClient);
        assertEquals("pv207.finepayment.Client", processClient.getClass().getName());
        assertEquals("Pavel", valueOf(processClient, "name"));
        assertEquals("true", valueOf(processClient, "exists"));
    }

    // helper methods
    protected String getPom(ReleaseId releaseId, ReleaseId... dependencies) {
        String pom =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
                "         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n" +
                "  <modelVersion>4.0.0</modelVersion>\n" +
                "\n" +
                "  <groupId>" + releaseId.getGroupId() + "</groupId>\n" +
                "  <artifactId>" + releaseId.getArtifactId() + "</artifactId>\n" +
                "  <version>" + releaseId.getVersion() + "</version>\n" +
                "\n";
        if (dependencies != null && dependencies.length > 0) {
            pom += "<dependencies>\n";
            for (ReleaseId dep : dependencies) {
                pom += "<dependency>\n";
                pom += "  <groupId>" + dep.getGroupId() + "</groupId>\n";
                pom += "  <artifactId>" + dep.getArtifactId() + "</artifactId>\n";
                pom += "  <version>" + dep.getVersion() + "</version>\n";
                pom += "</dependency>\n";
            }
            pom += "</dependencies>\n";
        }
        pom += "</project>";
        return pom;
    }

   protected InternalKieModule createKieJar(KieServices ks, ReleaseId releaseId, List<String> resources ) {

        KieFileSystem kfs = createKieFileSystemWithKProject(ks);
        kfs.writePomXML( getPom(releaseId) );

        for (String resource : resources) {
            kfs.write("src/main/resources/KBase-test/" + resource, ResourceFactory.newClassPathResource(resource));
        }

        KieBuilder kieBuilder = ks.newKieBuilder(kfs);
        if (!kieBuilder.buildAll().getResults().getMessages().isEmpty()) {
            for (Message message : kieBuilder.buildAll().getResults().getMessages()) {
                logger.error("Error Message: ({}) {}", message.getPath(), message.getText());
            }
            throw new RuntimeException(
                    "There are errors builing the package, please check your knowledge assets!");
        }

        return ( InternalKieModule ) kieBuilder.getKieModule();
    }

    protected KieFileSystem createKieFileSystemWithKProject(KieServices ks) {
        KieModuleModel kproj = ks.newKieModuleModel();

        KieBaseModel kieBaseModel1 = kproj.newKieBaseModel("defaultKieBase").setDefault(true).addPackage("*")
                .setEqualsBehavior( EqualityBehaviorOption.EQUALITY )
                .setEventProcessingMode( EventProcessingOption.STREAM );

        kieBaseModel1.newKieSessionModel("defaultKieSession").setDefault(true)
                .setType(KieSessionModel.KieSessionType.STATEFUL)
                .setClockType( ClockTypeOption.get("realtime") )
                .newWorkItemHandlerModel("Log", "new org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler()");
        KieFileSystem kfs = ks.newKieFileSystem();
        kfs.writeKModuleXML(kproj.toXML());
        return kfs;
    }

    protected Object valueOf(Object object, String fieldName) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(object);
        } catch (Exception e) {
            return null;
        }
    }
}


text:
layout: leaf-node
title: "Learning styles and formative assessment strategy: enhancing student achievement in Web-based learning"
title-url: "http://www.fisme.science.uu.nl/staff/christianb/downloads/180509/wangetal2006.pdf"
author: ["K.H. Wang","T.H. Wang","W.L.Wang","S. C. Huang"]
groups: pedagogical-styles
categories: formative-assessment
topics: scholarly-readings
summary: >
    The researchers performed empirical analysis to determine the effects of formative assessment
    on student success in an online learning environment.
cite: >
    Wang, K. H., Wang, T. H., Wang, W. L., & Huang, S. C. (2006). Learning styles and formative assessment strategy: enhancing student achievement in Web‐based learning. Journal of Computer Assisted Learning, 22(3), 207-217.
    Retrieved from http://www.fisme.science.uu.nl/staff/christianb/downloads/180509/wangetal2006.pdf
pub-date: 2006-06-01
added-date: 2017-04-28
resource-type: pdf-document
---


text:
        {{ site.theme_settings.codename }}  is designed by {{ site.theme_settings.creator }}
Copyright © {{ site.time | date: '%Y' }}


text:
<?php

/**
 * Subversion checkout implementation.
 *
 * @category  QualityAssurance
 * @package   VersionControl
 * @author    Manuel Pichler <mapi@phpundercontrol.org>
 * @copyright 2007-2011 Manuel Pichler. All rights reserved.
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version   Release: 0.4.0
 * @link      http://www.phpundercontrol.org/
 */
class phpucSubversionCheckout extends phpucAbstractCheckout
{
    /**
     * Performs a subversion checkout.
     *
     * @return void
     * @throws phpucErrorException
     *         If the subversion checkout fails.
     */
    public function checkout()
    {
        $options = ' --no-auth-cache --non-interactive';
        if ( $this->username !== null )
        {
            $options .= ' --username ' . escapeshellarg( $this->username );
        }
        if ( $this->password !== null )
        {
            $options .= ' --password ' . escapeshellarg( $this->password );
        }

        $svn = phpucFileUtil::findExecutable( 'svn' );
        $url = escapeshellarg( $this->url );
        $cmd = "{$svn} co {$options} {$url} source";

        popen( "{$cmd} 2>&1", "r" );

        if ( !file_exists( 'source' ) )
        {
            throw new phpucErrorException( 'The project checkout has failed.' );
        }
    }

    /**
     * Subversion uses update command to update existing repository from a server
     *
     * @return string
     */
    public function getUpdateCommand()
    {
        return "up";
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/left_switchbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:textSize="13sp"/>

     <Button
        android:id="@+id/right_switchbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:textSize="13sp"/>

</LinearLayout>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bot. Jb. 6: 393 (1885)

#### Original name
null

### Remarks
null


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

<title>ListCellRenderer (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="javax.swing.ListCellRenderer interface">
<meta name="keywords" content="getListCellRendererComponent()">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.swing

Interface ListCellRenderer<E>

Type Parameters:

E - the type of values this renderer can be used for

All Known Implementing Classes:

BasicComboBoxRenderer, BasicComboBoxRenderer.UIResource, DefaultListCellRenderer, DefaultListCellRenderer.UIResource, MetalFileChooserUI.FileRenderer, MetalFileChooserUI.FilterComboBoxRenderer

public interface ListCellRenderer<E>

Identifies components that can be used as "rubber stamps" to paint
 the cells in a JList.  For example, to use a JLabel as a
 ListCellRenderer, you would write something like this:

 class MyCellRenderer extends JLabel implements ListCellRenderer<Object> {
     public MyCellRenderer() {
         setOpaque(true);
     }

     public Component getListCellRendererComponent(JList<?> list,
                                                   Object value,
                                                   int index,
                                                   boolean isSelected,
                                                   boolean cellHasFocus) {

         setText(value.toString());

         Color background;
         Color foreground;

         // check if this cell represents the current DnD drop location
         JList.DropLocation dropLocation = list.getDropLocation();
         if (dropLocation != null
                 && !dropLocation.isInsert()
                 && dropLocation.getIndex() == index) {

             background = Color.BLUE;
             foreground = Color.WHITE;

         // check if this cell is selected
         } else if (isSelected) {
             background = Color.RED;
             foreground = Color.WHITE;

         // unselected, and not the DnD drop location
         } else {
             background = Color.WHITE;
             foreground = Color.BLACK;
         };

         setBackground(background);
         setForeground(foreground);

         return this;
     }
 }

See Also:

JList,
DefaultListCellRenderer

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

Component
getListCellRendererComponent(JList<? extends E> list,
                            E value,
                            int index,
                            boolean isSelected,
                            boolean cellHasFocus)

Return a component that has been configured to display the specified
 value.

Method Detail

getListCellRendererComponent

Component getListCellRendererComponent(JList<? extends E> list,
                                       E value,
                                       int index,
                                       boolean isSelected,
                                       boolean cellHasFocus)

Return a component that has been configured to display the specified
 value. That component's paint method is then called to
 "render" the cell.  If it is necessary to compute the dimensions
 of a list because the list cells do not have a fixed size, this method
 is called to generate a component on which getPreferredSize
 can be invoked.

Parameters:

list - The JList we're painting.

value - The value returned by list.getModel().getElementAt(index).

index - The cells index.

isSelected - True if the specified cell was selected.

cellHasFocus - True if the specified cell has the focus.

Returns:

A component whose paint() method will render the specified value.

See Also:

JList,
ListSelectionModel,
ListModel

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
using Nop.Core.Caching;
using Nop.Services.Tasks;

namespace Nop.Services.Caching
{
    /// <summary>
    /// Clear cache schedueled task implementation
    /// </summary>
    public partial class ClearCacheTask : ITask
    {
        /// <summary>
        /// Executes a task
        /// </summary>
        public void Execute()
        {
            var cacheManager = new MemoryCacheManager();
            cacheManager.Clear();
        }
    }
}


text:
#include "tfrt/tensor/btf_util.h"

#include <iostream>

namespace tfrt {
namespace {

constexpr size_t kBtfAlignment = 8;

size_t Pad(size_t n) {
  const size_t remainder = n % kBtfAlignment;
  if (remainder == 0) return 0;
  return kBtfAlignment - remainder;
}

Error WriteDHTToBTF(std::ostream* stream, const DenseHostTensor& dht) {
  std::vector<uint64_t> dims;
  dims.reserve(dht.shape().GetRank());
  for (int i = 0; i < dht.shape().GetRank(); i++) {
    dims.push_back(dht.shape().GetDimensionSize(i));
  }
  if (!WriteStream(stream, dims.data(), dims.size())) {
    return MakeStringError("failed to write tensor dims");
  }
  const size_t nbytes = dht.DataSizeInBytes();
  if (!WriteStream(stream, reinterpret_cast<const uint8_t*>(dht.data()),
                   nbytes)) {
    return MakeStringError("failed to write tensor data");
  }
  const size_t padding = Pad(nbytes);
  constexpr std::array<uint8_t, 7> pad_value{0, 0, 0, 0, 0, 0, 0};
  if (padding != 0 && !WriteStream(stream, pad_value.data(), padding)) {
    return MakeStringError("failed to pad tensor");
  }
  return Error::success();
}

}  // namespace

Expected<std::vector<uint64_t>> ReadBTFOffsets(std::istream* stream) {
  uint64_t num_tensors;
  if (!ReadStream(stream, &num_tensors, 1)) {
    return MakeStringError("failed to read num_tensors");
  }
  std::vector<uint64_t> offsets;
  offsets.resize(num_tensors);
  if (!ReadStream(stream, offsets.data(), num_tensors)) {
    return MakeStringError("failed to read tensor record offsets");
  }
  return offsets;
}

Expected<DenseHostTensor> ReadDHTFromBTF(std::istream* stream, uint64_t offset,
                                         HostContext* host) {
  stream->seekg(offset);
  btf::TensorHeader header;
  if (!ReadStream(stream, &header, 1)) {
    return MakeStringError("failed to read tensor header at offset", offset);
  }
  if (header.layout != btf::TensorLayout::kRMD) {
    return MakeStringError("unexpected tensor layout ", header.layout);
  }
  llvm::SmallVector<Index, 4> dims;
  dims.resize(header.rank);
  if (!ReadStream(stream, dims.data(), header.rank)) {
    return MakeStringError("failed to read tensor dims at offset", offset);
  }
  const TensorMetadata metadata(DType(ToDTypeKind(header.dtype)),
                                TensorShape(dims));
  auto dht_or = DenseHostTensor::CreateUninitialized(metadata, host);
  if (!dht_or.has_value()) {
    return MakeStringError("cannot allocate result tensor");
  }
  auto dht = std::move(*dht_or);
  // This can read a large amount of data from the stream. Depending on the
  // underlying file system implementation, we may need to have a more optimal
  // strategy for reading the file.
  if (!ReadStream(stream, reinterpret_cast<uint8_t*>(dht.data()),
                  dht.DataSizeInBytes())) {
    return MakeStringError("failed to read tensor data at offset", offset);
  }
  return std::move(dht);
}

Error WriteTensorsToBTF(std::ostream* stream, ArrayRef<const Tensor*> tensors) {
  const uint64_t num_tensors = tensors.size();
  if (!WriteStream(stream, &num_tensors, 1)) {
    return MakeStringError("failed to write num_tensors");
  }
  std::vector<uint64_t> offsets;
  offsets.reserve(num_tensors);
  uint64_t offset = (1 + num_tensors) * sizeof(uint64_t);
  for (const Tensor* tensor : tensors) {
    offsets.push_back(offset);
    if (tensor->tensor_type() == DenseHostTensor::kTensorType) {
      const auto& dht = reinterpret_cast<const DenseHostTensor&>(*tensor);
      const size_t nbytes = dht.DataSizeInBytes();
      offset += sizeof(btf::TensorHeader) +
                dht.shape().GetRank() * sizeof(uint64_t) + nbytes + Pad(nbytes);
    } else {
      return MakeStringError("unhandled tensor type when writing btf");
    }
  }
  if (!WriteStream(stream, offsets.data(), offsets.size())) {
    return MakeStringError("failed to write offsets");
  }
  for (const Tensor* tensor : tensors) {
    auto dtype_or = btf::ToTensorDType(tensor->dtype());
    if (!dtype_or) return dtype_or.takeError();
    btf::TensorHeader header{};
    header.rank = static_cast<uint64_t>(tensor->shape().GetRank());
    header.dtype = *dtype_or;
    header.layout = btf::TensorLayout::kRMD;
    if (!WriteStream(stream, &header, 1)) {
      return MakeStringError("failed to write tensor header");
    }
    if (tensor->tensor_type() == DenseHostTensor::kTensorType) {
      Error e = WriteDHTToBTF(
          stream, reinterpret_cast<const DenseHostTensor&>(*tensor));
      if (e) return e;
    } else {
      return MakeStringError("unhandled tensor type when writing btf");
    }
  }
  return Error::success();
}

}  // namespace tfrt


text:
<?xml version="1.0" encoding="UTF-8"?>
<fileResource exportedWithPermissions="false" dataFile="supermart_ja.properties.data">
    <folder>/public/SESamples/ExtraSamples/Resources/Bundles</folder>
    <name>supermart_ja.properties</name>
    <version>3</version>
    <label>supermart_ja.properties</label>
    <description>Japanese resource bundle</description>
    <creationDate>2014-06-19T19:22:03.540+02:00</creationDate>
    <updateDate>2012-06-28T23:50:07.000+02:00</updateDate>
    <fileType>prop</fileType>
</fileResource>


text:
module Pohoda
  module Builders
    module Acp
      class ActionPriceStockItemType
        include ParserCore::BaseBuilder

        def builder
          root = Ox::Element.new(name)
          root = add_attributes_and_namespaces(root)

          root << build_element('acp:stock', data[:stock], data[:stock_attributes]) if data.key? :stock
          root << build_element('acp:text', data[:text], data[:text_attributes]) if data.key? :text
          if data.key? :storage
            root << Typ::RefTypeStorage.new('acp:storage', data[:storage]).builder
          end
          if data.key? :default_price_stock
            root << Acp::DefaultPriceStockType.new('acp:defaultPriceStock', data[:default_price_stock]).builder
          end
          if data.key? :action_price_stock
            root << Acp::ActionPriceStockType.new('acp:actionPriceStock', data[:action_price_stock]).builder
          end

          root
        end
      end
    end
  end
end


text:
import test from 'ava'
import fs from 'fs'
import {textileToHtml, textileTokensToHtml, parseTextile, tokens} from './textile'

test('parse to html', t => {
  var expectedTokens = 'foo bar baz foo'
  t.same(expectedTokens, textileTokensToHtml(['foo ', tokens['bold'][0], 'bar', tokens['up'][0], ' baz foo', tokens['up'][1], tokens['bold'][1]]))
  t.end()
})

test('parse', t => {
  var expectedTokens = ['foo ', tokens['bold'][0], 'bar', tokens['up'][0], ' baz foo', tokens['up'][1], tokens['bold'][1]]
  t.same(expectedTokens, parseTextile(['foo *bar^ baz foo^*']))
  t.end()
})

test('parse unclosed', t => {
  var expectedTokens = ['foo ', tokens['bold'][0], 'bar', ' baz foo', tokens['bold'][1]]
  t.same(expectedTokens, parseTextile(['foo *bar^ baz foo*']))
  t.end()
})

test('parse one-item list', t => {
  var expectedTokens = ['foo ', tokens['unordered_list_group'][0], tokens['unordered_list'][0], 'bar', tokens['unordered_list'][1], tokens['unordered_list_group'][1], ' baz foo']
  t.same(expectedTokens, parseTextile(['foo \n* bar\n baz foo']))
  t.end()
})

test('file to html', t => {
    var text = fs.readFileSync(__dirname+'/test.tx', 'utf8')
    var html = textileToHtml(text)
    var expectedHtml = [
      'foo bar baz foo',
      '

baz',
          '

baz-1

baz-2

',
      '

boz',
          '

boz-1

',
      '

',
      '
foo
'].join('')
    t.same(expectedHtml, html)
    t.end()
})

test('bold', t => {
    var actualTokens = parseTextile('foo *bar* baz')
    var expectedTokens = ['foo ', tokens['bold'][0], 'bar', tokens['bold'][1], ' baz']
    t.same(expectedTokens, actualTokens)
    t.end()
})

test('italic', t => {
    var actualTokens = parseTextile('foo _bar_ baz')
    var expectedTokens = ['foo ', tokens['italic'][0], 'bar', tokens['italic'][1], ' baz']
    t.same(expectedTokens, actualTokens)
    t.end()
})

test('up', t => {
    var actualTokens = parseTextile('foo ^bar^ baz')
    var expectedTokens = ['foo ', tokens['up'][0], 'bar', tokens['up'][1], ' baz']
    t.same(expectedTokens, actualTokens)
    t.end()
})

test('down', t => {
    var actualTokens = parseTextile('foo ~bar~ baz')
    var expectedTokens = ['foo ', tokens['down'][0], 'bar', tokens['down'][1], ' baz']
    t.same(expectedTokens, actualTokens)
    t.end()
})

test('line break', t => {
    var actualTokens = parseTextile('foo \nbar\n baz')
    var expectedTokens = ['foo ', tokens.line_break, 'bar', tokens.line_break, ' baz']
    t.same(expectedTokens, actualTokens)
    t.end()
})

test('mixed phrase', t => {
    var actualTokens = parseTextile('*foo*~bar~*baz*')
    var expectedTokens = [tokens['bold'][0], 'foo', tokens['bold'][1], tokens['down'][0], 'bar', tokens['down'][1], tokens['bold'][0], 'baz', tokens['bold'][1]]
    t.same(expectedTokens, actualTokens)
    t.end()
})

test('list one unsorted', t => {
    var actualTokens = parseTextile('foo \n* bar\n* baz\n foo')
    var expectedTokens = ['foo ', tokens['unordered_list_group'][0], tokens['unordered_list'][0], 'bar', tokens['unordered_list'][1], tokens['unordered_list'][0], 'baz', tokens['unordered_list'][1], tokens['unordered_list_group'][1], ' foo']
    t.same(expectedTokens, actualTokens)
    t.end()
})

test('list two unsorted', t => {
    var actualTokens = parseTextile('foo \n* bar\n** baz\n** bak\n* bee\n foo')
    var expectedTokens = ['foo ', tokens['unordered_list_group'][0], tokens['unordered_list'][0], 'bar', tokens['unordered_list_two_group'][0], tokens['unordered_list_two'][0], 'baz', tokens['unordered_list_two'][1], tokens['unordered_list_two'][0], 'bak', tokens['unordered_list_two'][1], tokens['unordered_list_two_group'][1], tokens['unordered_list'][1], tokens['unordered_list'][0], 'bee', tokens['unordered_list'][1], tokens['unordered_list_group'][1], ' foo']
    t.same(expectedTokens, actualTokens)
    t.end()
})


text:
/*
  A console.log that won't leave you hanging when node exits
  90% of this file was ripped from node.js

  License: see: https://github.com/joyent/node/blob/master/lib/console.js
 */

 // console object
var formatRegExp = /%[sdj]/g;
function format(f) {
  var util = require('util');

  if (typeof f !== 'string') {
    var objects = [];
    for (var i = 0; i < arguments.length; i++) {
      objects.push(util.inspect(arguments[i]));
    }
    return objects.join(' ');
  }

  var i = 1;
  var args = arguments;
  var str = String(f).replace(formatRegExp, function(x) {
    switch (x) {
      case '%s': return String(args[i++]);
      case '%d': return Number(args[i++]);
      case '%j': return JSON.stringify(args[i++]);
      default:
        return x;
    }
  });
  for (var len = args.length, x = args[i]; i < len; x = args[++i]) {
    if (x === null || typeof x !== 'object') {
      str += ' ' + x;
    } else {
      str += ' ' + util.inspect(x);
    }
  }
  return str;
}

console.log = function() {
  var res = process.stdout.write(format.apply(this, arguments) + '\n');

  // this is the first time stdout got backed up
  if (!res && !process.stdout.pendingWrite) {
     process.stdout.pendingWrite = true;

     // magic sauce: keep node alive until stdout has flushed
     process.stdout.once('drain', function () {
       process.stdout.draining = false;
     });
  }
};


text:
<?php

namespace CallFire\Api\Soap\Request;

use CallFire\Api\Soap\AbstractRequest as AbstractRequest;

class CampaignIdRequest extends AbstractRequest
{

    /**
     * @var long
     */
    protected $campaignId = null;

    public function getCampaignId()
    {
        return $this->campaignId;
    }

    public function setCampaignId($campaignId)
    {
        $this->campaignId = $campaignId;

        return $this;
    }

}


text:
package org.apache.wiki.workflow;

import org.apache.wiki.api.exceptions.WikiException;

/**
 * Exception thrown when an activity -- that would otherwise complete silently --
 * cannot complete because a workflow {@link Decision} is required. The message
 * string should be a human-readable, internationalized String explaining why
 * the activity could not complete, or that the activity has been queued for
 * review.
 *
 */
public class DecisionRequiredException extends WikiException
{

    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new exception.
     * @param message the message
     */
    public DecisionRequiredException(final String message )
    {
        super( message );
    }
}


text:
namespace tyr {

class Condition : private UnCopyable {
  std::condition_variable cond_;
public:
  void Singal(void) {
    cond_.notify_one();
  }

  void Broadcast(void) {
    cond_.notify_all();
  }

  void Wait(Mutex& mutex) {
    std::unique_lock<std::mutex> lock(*mutex.InnerMutex());
    cond_.wait(lock);
  }

  bool TimedWait(Mutex& mutex, uint64_t timeout) {
    std::unique_lock<std::mutex> lock(*mutex.InnerMutex());
    return (std::cv_status::no_timeout ==
        cond_.wait_for(lock, std::chrono::nanoseconds(timeout)));
  }
};

}

#endif  // __TYR_CPP11_CONDITION_HEADER_H__


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/*
 * 1개 부분만 연결 가능한 블럭들(asset trigger에서의 action, trigger)
 * */

namespace PAUT.GUI
{
    public class PieceOneConnect : PieceBase
    {

        //move하는 중일 때 거리 확인하는 함수,
        //true일시 원래 위치로 이동하기
        //false일시 고정된 상태로 유지하기

        /*
        public override void attachedMyRightInGUI(PieceBase _origin)
        {
            base.attachedMyRightInGUI(_origin);
        }
        public override void  attachedToInGUI(PieceBase _origin)
        {
            base.attachedToFront(_origin);

            _origin.IsFrontAttachedPieceGUI = true;
            IsFrontAttachedPieceGUI = true;

            setWorldPosition(_origin.getWorldPosition(), true);

            FrontAttachedPieceGUI = _origin;
            _origin.FrontAttachedPieceGUI = this;
        }

        public override void dettachedToFrontInGUI()
        {
            base.dettachedToFrontInGUI();

            FrontAttachedPieceGUI.IsFrontAttachedPieceGUI = false;
            IsFrontAttachedPieceGUI = false;

            FrontAttachedPieceGUI.FrontAttachedPieceGUI = null;
            FrontAttachedPieceGUI = null;

        }

        public override bool checkIfDettached(Vector3 curPosition)
        {
            if (FrontAttachedPieceGUI != null)
            {
                float distance = Vector3.Distance(curPosition, FrontAttachedPieceGUI.getWorldPosition());

                if (distance > attachedThreshold)
                {
                    dettachedToFrontInGUI();
                    return true;
                }
                return false;
            }
            return false;
        }

        public override bool checkIfAttached2Other()
        {
            bool isExistAttachedPiece = false;

            List<float> distances = new List<float>();
            List<PieceBase> attachablePiecesSet = new List<PieceBase>();

            //주변에 있는 다른 piecebase block과의 거리 계산하기
            foreach (PieceBase pb in PieceBase.allAttachablePiece)
            {
                float distance = Vector3.Distance( getWorldPosition(), pb.getWorldPosition());

                if (distance < attachedThreshold)
                {
                    distances.Add(distance);
                    attachablePiecesSet.Add(pb);
                }
            }

            //distance sort하기, 그에 맞춰서 pb 역시 sorting 하기
            for (int i = 0; i < distances.Count; i++)
            {
                for (int j = i; j < distances.Count; j++)
                {
                    if (distances[i] > distances[j])
                    {
                        float tmp = distances[i];
                        distances[i] = distances[j];
                        distances[j] = tmp;

                        PieceBase pb = attachablePiecesSet[i];
                        attachablePiecesSet[i] = attachablePiecesSet[j];
                        attachablePiecesSet[j] = pb;
                    }
                }
            }

            //첫 번째 꺼만 있음
            PieceTypes pt = attachableFrontType[0];

            foreach (PieceBase pb in attachablePiecesSet)
            {
                if (pb.myType == pt)
                {
                    if (pb.IsFrontAttachedPieceGUI == false)
                    {
                        //붙이기 시작

                        //pb에 나를 갖다 댄다
                        attachedToFrontInGUI(pb);
                        isExistAttachedPiece = true;

                        return isExistAttachedPiece;
                    }
                    //제일 가까운 녀석만 붙이기

                }
            }

            return isExistAttachedPiece;
        }

        public override void OnMouseDown()
        {
            base.OnMouseDown();
        }

        public override void OnMouseDrag()
        {
            if (parentShell == null)
            {
                Debug.Log("Parent shell is not defined");
                return;
            }

            Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
            Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;

            //만일 GUI하게 붙어 있지 않은 경우

            //front가 붙어있지 않은 경우, threshold 안에 맞는 block이 있을 시 달라 붙기
            if (IsFrontAttachedPieceGUI == false)
            {
                //checkMoveable이 참일때만 curPosition으로 이동시켜줍니다
                if (checkIfAttached2Other() == false)
                {
                    parentShell.position = curPosition;
                }
            }

            //front가 붙어 있는 경우, threshold 밖으로 position이 존재할 시 떼기
            else
            {
                if (checkIfDettached(curPosition) == true)
                {
                    parentShell.position = curPosition;
                }
            }
            */
    }

}


text:
using System;
using System.Runtime.Serialization;
using CacheProvider.Model;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace CacheProvider.Mongo.Model
{
	[Serializable, DataContract]
	public class MongoCachModel : CacheModel
    {
        public MongoCachModel()
        {
            Id = ObjectId.GenerateNewId().ToString();
        }

        [BsonId]
        public String Id { get; set; }
    }
}


text:
var GenericActions = require('../GenericActions.js');
var Bookshelf = require('../bookshelf/Bookshelf.js');
var LoginPage = require('../login/LoginPage.js');
var Reading = require('../reading-pdf/Reading.js');

describe('reading-follow-pis-EPUB', function () {
  var loginPage = new LoginPage();
  var genericActions = new GenericActions();
  var bookshelf = new Bookshelf();
  var reading = new Reading();
  var params = browser.params;
  beforeAll(function () {
    reading.beforeAllFunction();
    bookshelf.doPrepareForTest();
  });
  beforeEach(function () {
    genericActions.smartAngularWait();
  });

  it("System presents indicated page after following a leaf node of Highlights", function () {
    loginPage.doLogin(params.login.user, params.login.password);
    bookshelf.doOpenEpubGroup();
    bookshelf.doDownloadBookByTitle("Antidiskriminační zákon. Komentář_epub");
    bookshelf.doOpenBookByTitle("Antidiskriminační zákon. Komentář_epub");
    reading.doRemoveAllHighlights();
    reading.doShowNavigationBar();
    reading.doClickMenuIcon();
    reading.doClickTOC();
    reading.doClickTocItemByIndex(2);
    reading.doHighlightText2Epub(6);
    reading.doClickHighlightContextMenu();
    reading.doClickBlue();
    reading.doGoToBeginning();
    reading.doClickMenuIcon();
    reading.doClickPersonalItemsMenu();
    reading.getPersonalItemBlock(0).click();
    reading.doClickMenuBackButton();
    reading.doClickCloseIcon();
    browser.switchTo().frame(0);
    expect($('.highlight-blue').isPresent()).toBeTruthy();
  });

  it("Follow a leaf note of Highlights: Back button is enabled", function () {
    browser.switchTo().defaultContent();
    reading.doShowNavigationBar()
    bookshelf.getPlatform=function (platform) {
      if (platform == 'Android') {
        expect(genericActions.hasClass(reading.getHistoryBackButton(), 'icon-disabled')).toBe(false);
      } else {
        expect(genericActions.hasClass(reading.getHistoryBackButton(), 'disabled')).toBe(false);
      }
    }
  });

  it("Follow a leaf note of Highlights: Forward button is disabled", function () {
    bookshelf.getPlatform=function (platform) {
      if (platform == 'Android') {
        expect(genericActions.hasClass(reading.getHistoryForwardButton(), 'icon-disabled')).toBe(true);
      } else {
        expect(genericActions.hasClass(reading.getHistoryForwardButton(), 'disabled')).toBe(true);
      }
    }
   });

   it("System presents indicated page after following a leaf node of Notes", function () {
     reading.doRemoveAllHighlights();
     //reading.doAddNote1EPUB('note text', 6);
       reading.doHighlightText2Epub(2);
       reading.doClickAddNoteContextMenu();
       reading.doSetNoteTextAndSave("text");
     reading.doGoToBeginning();
     reading.doClickMenuIcon();
     reading.doClickPersonalItemsMenu();
     reading.getPersonalItemTextElement().click();
     //reading.doShowNavigationBar();
     reading.doClickMenuBackButton();
     reading.doClickCloseIcon();
     browser.switchTo().frame(0);
     expect($('.highlight-gray').isPresent()).toBeTruthy();
   });

   it("Follow a leaf note of Notes: Back button is enabled", function () {
     browser.switchTo().defaultContent();
     reading.doShowNavigationBar();
     bookshelf.getPlatform=function (platform) {
       if (platform == 'Android') {
         expect(genericActions.hasClass(reading.getHistoryBackButton(), 'icon-disabled')).toBe(false);
       } else {
         expect(genericActions.hasClass(reading.getHistoryBackButton(), 'disabled')).toBe(false);
       }
    }
   });

   it("Follow a leaf note of Notes: Forward button is disabled", function () {
     bookshelf.getPlatform=function (platform) {
       if (platform == 'Android') {
         expect(genericActions.hasClass(reading.getHistoryForwardButton(), 'icon-disabled')).toBe(true);
       } else {
         expect(genericActions.hasClass(reading.getHistoryForwardButton(), 'disabled')).toBe(true);
       }
     }
   });

   it("System presents indicated page after following a leaf node of Bookmarks", function () {
   reading.doGoToBeginning();
   reading.doRemoveAllHighlights();
   reading.doShowNavigationBar();
   reading.doClickMenuIcon();
   reading.doClickTOC();
   reading.doClickTocItemByIndex(0);
   reading.doClickBookmarkIcon();
   reading.doGoToBeginning();
   reading.doClickMenuIcon();
   reading.doClickPersonalItemsMenu();
   reading.getPersonalItemTextElement().click();
   //reading.doShowNavigationBar();
     reading.doClickMenuBackButton();
     reading.doClickCloseIcon();
   expect($('.icon-bookmark2').isPresent()).toBeTruthy();
   });

   it("Follow a leaf note of Notes: Back button is enabled", function () {
   browser.switchTo().defaultContent();
     bookshelf.getPlatform=function (platform) {
       if (platform == 'Android') {
         expect(genericActions.hasClass(reading.getHistoryBackButton(), 'icon-disabled')).toBe(false);
       } else {
         expect(genericActions.hasClass(reading.getHistoryBackButton(), 'disabled')).toBe(false);
       }
     }
   });

   it("Follow a leaf note of Notes: Forward button is disabled", function () {
     bookshelf.getPlatform=function (platform) {
       if (platform == 'Android') {
         expect(genericActions.hasClass(reading.getHistoryForwardButton(), 'icon-disabled')).toBe(true);
       } else {
         expect(genericActions.hasClass(reading.getHistoryForwardButton(), 'disabled')).toBe(true);
       }
     }
   });

  // it('Delete downloaded Book', function () {
  //   //reading-pdf.doShowNavigationBar();
  //   reading-pdf.doBackToBookshelf();
  //   bookshelf.doOpenMainBookshelf();
  //   browser.sleep(1000);
  //   bookshelf.showAll();
  //   bookshelf.doDeleteAllBooks();
  // });

});


text:
namespace Kvasir {
//Mailbox
    namespace MailboxIrq0{    ///<Interrupt request register for the Cortex-M0+ CPU.
        using Addr = Register::Address<0x1c02c000,0x00000000,0x00000000,unsigned>;
        ///If any bit is set, an interrupt request is sent to the								Cortex-M0+ interrupt controller.
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> intreq{};
    }
    namespace MailboxIrq0set{    ///<Set bits in IRQ0
        using Addr = Register::Address<0x1c02c004,0x00000000,0x00000000,unsigned>;
        ///Writing 1 sets the corresponding bit in the IRQ0								register.
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> intreqset{};
    }
    namespace MailboxIrq0clr{    ///<Clear bits in IRQ0
        using Addr = Register::Address<0x1c02c008,0x00000000,0x00000000,unsigned>;
        ///Writing 1 clears the corresponding bit in the IRQ0								register.
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> intreqclr{};
    }
    namespace MailboxIrq1{    ///<Interrupt request register for the Cortex M4 CPU.
        using Addr = Register::Address<0x1c02c010,0x00000000,0x00000000,unsigned>;
        ///If any bit is set, an interrupt request is sent to the								Cortex-M0+ interrupt controller.
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> intreq{};
    }
    namespace MailboxIrq1set{    ///<Set bits in IRQ1
        using Addr = Register::Address<0x1c02c014,0x00000000,0x00000000,unsigned>;
        ///Writing 1 sets the corresponding bit in the IRQ1								register.
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> intreqset{};
    }
    namespace MailboxIrq1clr{    ///<Clear bits in IRQ1
        using Addr = Register::Address<0x1c02c018,0x00000000,0x00000000,unsigned>;
        ///Writing 1 clears the corresponding bit in the IRQ1								register.
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> intreqclr{};
    }
    namespace MailboxMutex{    ///<Mutual exclusion register
        using Addr = Register::Address<0x1c02c0f8,0x00000000,0x00000000,unsigned>;
        ///Cleared when read, set when written. See usage description								above.
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ex{};
        ///Reserved
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,1),Register::ReadWriteAccess,unsigned> reserved{};
    }
}


text:
this is a fork from that project https://github.com/andrejunges/vscode-handlebars but with some
modifications for work with patternlab

## Features
* Colorization
* Snippets

List of snippets

#Handlebars
-

#Json
-


text:
package ru.job4j.carMarket.model.dao;

import ru.job4j.carMarket.model.entity.*;

import java.util.List;

public interface Storage {

    List<Car> getCars();

    List<Mark> getMarks();

    List<Model> findModelsByMark(int id);

    List<Transmission> getTransmission();

    List<BodyType> getBodyType();

    Car addCarToUser(User user, Car car);

    User addUser(User user);

    User findUserByLogin(String login);

    void soldCar(int id);

}


text:
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;

#[test]
fn sidt_1() {
    run_test(&Instruction { mnemonic: Mnemonic::SIDT, operand1: Some(IndirectDisplaced(SI, 110, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 1, 76, 110], OperandSize::Word)
}

#[test]
fn sidt_2() {
    run_test(&Instruction { mnemonic: Mnemonic::SIDT, operand1: Some(IndirectScaledIndexedDisplaced(ECX, EBX, Four, 1645513045, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 1, 140, 153, 85, 137, 20, 98], OperandSize::Dword)
}

#[test]
fn sidt_3() {
    run_test(&Instruction { mnemonic: Mnemonic::SIDT, operand1: Some(Indirect(RDI, Some(OperandSize::Unsized), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 1, 15], OperandSize::Qword)
}


text:
<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="resources/link-highlight-style.css">

Link 1

Link 2

Link 3

Target Link.

Link 4

Link 5

This test is successful if "Target Link" above is covered in a green rectangle with square corners.

</script>


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using XenAdmin.Network;

namespace XenAPI
{
    partial class Task
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public delegate task_status_type TaskStatusOp(Session session, string task);
        public delegate double TaskProgressOp(Session session, string task);
        public delegate Task TaskGetRecordOp(Session session, string task);

        /// <summary>
        /// Try and run the delegate.
        /// If it fails with a web exception or invalid session, try again.
        /// Only retry 60 times.
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="session"></param>
        /// <param name="f"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static Object DoWithSessionRetry(IXenConnection connection, ref Session session, Delegate f, params object[] p)
        {
            int retries = 60;

            while (true)
            {
                try
                {
                    object[] ps = new object[p.Length + 1];

                    ps[0] = session;

                    for (int i = 0; i < p.Length; i++)
                    {
                        ps[i + 1] = p[i];
                    }

                    try
                    {
                        return f.DynamicInvoke(ps);
                    }
                    catch (TargetInvocationException exn)
                    {
                        throw exn.InnerException;
                    }
                }
                catch (WebException we)
                {
                    log.Error($"WebException in DoWithSessionRetry, retry {retries}: ", we);

                    if (retries <= 0)
                        throw;
                }
                catch (Failure failure)
                {
                    log.Error($"Failure in DoWithSessionRetry, retry {retries}", failure);

                    if (retries <= 0)
                        throw;

                    if (failure.ErrorDescription.Count < 1 || failure.ErrorDescription[0] != XenAPI.Failure.SESSION_INVALID)
                        throw;
                }

                Session newSession;

                try
                {
                    // try to create a new TCP stream to use, as the other one has failed us
                    newSession = connection.DuplicateSession();
                    session = newSession;
                }
                catch
                {
                }

                retries--;

                Thread.Sleep(connection.ExpectDisruption ? 500 : 100);
            }
        }

        /// <summary>
        /// A list of OpaqueRefs of objects to which the current task applies.  This is set
        /// by one XenCenter instance, and picked up by other ones.
        /// </summary>
        public List<string> AppliesTo()
        {
            string s = Get(other_config, "applies_to");
            return s == null ? null : new List<string>(s.Split(','));
        }

        public static void SetAppliesTo(Session session, string _task, List<string> applies_to)
        {
            try
            {
                remove_from_other_config(session, _task, "applies_to");
                add_to_other_config(session, _task, "applies_to", string.Join(",", applies_to.ToArray()));
            }
            catch (XenAPI.Failure f)
            {
                if (f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
                {
                    // Read only user without task.other_config rights - just ignore this request
                    return;
                }
                throw f;
            }
        }

        public string XenCenterUUID()
        {
            return Get(other_config, "XenCenterUUID");
        }

        public static void SetXenCenterUUID(Session session, string _task, string uuid)
        {
            try
            {
                remove_from_other_config(session, _task, "XenCenterUUID");
                add_to_other_config(session, _task, "XenCenterUUID", uuid);
            }
            catch (XenAPI.Failure f)
            {
                if (f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
                {
                    // Read only user without task.other_config rights - just ignore this request
                    return;
                }
                throw f;
            }
        }

        public static void RemoveXenCenterUUID(Session session, string task)
        {
            if(session == null || String.IsNullOrEmpty(task))
                return;

            try
            {
                remove_from_other_config(session, task, "XenCenterUUID");
            }
            catch (XenAPI.Failure f)
            {
                if (f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
                {
                    // Read only user without task.other_config rights - just ignore this request
                    return;
                }
                throw;
            }
        }

        public override string Name()
        {
            return name_label.Replace("Async.", "");
        }

        public override string Description()
        {
            return name_description;
        }

        private static List<string> tasksToIgnore = new List<string>(new string[] { "SR.scan" });
        public bool IgnoreInCacheUpdate()
        {
            return tasksToIgnore.Contains(name_label);
        }
    }
}


text:
package org.tlc.mtg.nouns;

/**
 * Parts of key words have points at which they activate.
 * These are the phases of activation for all key words.
 *
 * For example "Vigilance" does not tap during attack.
 * This means Vigilance is implemented with a composed attack, but no tap.
 * Double Strike is an attack which repeats the damage, some as composed with first strike and normal damage.
 */
public enum Phases {
  /**
   * Card load
   */
  LOAD,

  UNTAP,
  UPKEEP,
  DRAW,
  LAND,
  SPELLS,
  ATTACK,
  CLEANUP,
  END,

  /**
   * Tapping
   */
  TAP,
  /**
   * Declaration of attack
   */
  ATTACK_DECL,
  /**
   * Addition to an attack.
   */
  ATTACK_ADD,
  /**
   * Defence declaration.
   */
  DEFEND_DECL,
  /**
   * Add to defenders.
   */
  DEFEND_ADD,
  /**
   * When a card is cast
   */
  CAST,
  /**
   * After spell resolution, damage
   */
  DAMAGE_RESOLUTION,
  /**
   * The actual damage.
   */
  DAMAGE,
  /**
   * into the graveyard
   */
  LEAVE,
  /**
   * Exiled, board -> gone.
   */
  EXILE,
  /**
   * Put into play from any source
   */
  COMES_INTO_PLAY,
}


text:
#import <Foundation/Foundation.h>
#import "ROFilterField.h"
#import "RODatasource.h"

@class ROFilterViewController;

@interface ROFilterFieldSelection : NSObject <ROFilterField>

@property (nonatomic, strong) NSString *fieldLabel;

@property (nonatomic, strong) NSString *fieldName;

@property (nonatomic, strong) NSString *placeholder;

@property (nonatomic, strong) NSArray *options;

@property (nonatomic, strong) NSMutableArray *optionsSelected;

@property (nonatomic, assign) BOOL single;

@property (nonatomic, strong) ROFilterViewController *formController;

@property (nonatomic, strong) id<RODatasource> datasource;

@property (nonatomic, assign) BOOL required;

- (instancetype)initWithFieldLabel:(NSString *)fieldLabel
                         fieldName:(NSString *)fieldName
                    formController:(ROFilterViewController *)formController
                            single:(BOOL)single;

+ (instancetype)fieldLabel:(NSString *)fieldLabel
                 fieldName:(NSString *)fieldName
            formController:(ROFilterViewController *)formController
                            single:(BOOL)single;

@end