text:
namespace tgui
{
    class SpinButtonRenderer;

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /// @brief Spin button widget
    ///
    /// Signals:
    ///     - ValueChanged (The value of the spin button has changed)
    ///         * Optional parameter int: New value
    ///         * Uses Callback member 'value'
    ///
    ///     - Inherited signals from ClickableWidget
    ///
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    class TGUI_API SpinButton : public ClickableWidget
    {
    public:

        typedef std::shared_ptr<SpinButton> Ptr; ///< Shared widget pointer
        typedef std::shared_ptr<const SpinButton> ConstPtr; ///< Shared constant widget pointer

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Default constructor
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        SpinButton();

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Creates a new spin button widget
        ///
        /// @param minimum  The minimum value of the spin button
        /// @param maximum  The maximum value of the spin button
        ///
        /// @return The new spin button
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        static SpinButton::Ptr create(int minimum = 0, int maximum = 10);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Makes a copy of another spin button
        ///
        /// @param spinButton  The other spin button
        ///
        /// @return The new spin button
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        static SpinButton::Ptr copy(SpinButton::ConstPtr spinButton);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Returns the renderer, which gives access to functions that determine how the widget is displayed
        ///
        /// @return Reference to the renderer
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        std::shared_ptr<SpinButtonRenderer> getRenderer() const
        {
            return std::static_pointer_cast<SpinButtonRenderer>(m_renderer);
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Set the position of the widget
        ///
        /// This function completely overwrites the previous position.
        /// See the move function to apply an offset based on the previous position instead.
        /// The default position of a transformable widget is (0, 0).
        ///
        /// @param position  New position
        ///
        /// @see move, getPosition
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual void setPosition(const Layout2d& position) override;
        using Transformable::setPosition;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes the size of the spin button.
        ///
        /// @param size  The new size of the spin button
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual void setSize(const Layout2d& size) override;
        using Transformable::setSize;

        //////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Returns the full size of the spin button
        ///
        /// The size returned by this function includes the borders.
        ///
        /// @return Full size of the spin button
        ///
        //////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual sf::Vector2f getFullSize() const override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Sets a minimum value.
        ///
        /// @param minimum  The new minimum value
        ///
        /// When the value is too small then it will be changed to this minimum.
        /// The default minimum value is 0.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setMinimum(int minimum);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Sets a maximum value.
        ///
        /// @param maximum  The new maximum value
        ///
        /// When the value is too big then it will be changed to this maximum.
        /// The default maximum value is 10.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setMaximum(int maximum);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes the current value.
        ///
        /// @param value  The new value
        ///
        /// The value can't be smaller than the minimum or bigger than the maximum.
        /// The default value is 0.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setValue(int value);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Returns the minimum value.
        ///
        /// @return The current minimum value
        ///
        /// The default minimum value 0.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        int getMinimum() const
        {
            return m_minimum;
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Returns the maximum value.
        ///
        /// @return The current maximum value
        ///
        /// The default maximum value 10.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        int getMaximum() const
        {
            return m_maximum;
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Returns the current value.
        ///
        /// @return The current value
        ///
        /// The default value is 0.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        int getValue() const
        {
            return m_value;
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes whether the spin button lies vertical or horizontal (arrows above or next to each other).
        ///
        /// @param verticalScroll  Does the spin button lie vertically?
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setVerticalScroll(bool verticalScroll);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Returns whether the spin button lies vertical or horizontal (arrows above or next to each other).
        ///
        /// @return Does the spin button lie vertically?
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        bool getVerticalScroll() const
        {
            return m_verticalScroll;
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes the opacity of the widget.
        ///
        /// @param opacity  The opacity of the widget. 0 means completely transparent, while 1 (default) means fully opaque.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual void setOpacity(float opacity) override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Returns the distance between the position where the widget is drawn and where the widget is placed
        ///
        /// This is basically the width and height of the optional borders drawn around widgets.
        ///
        /// @return Offset of the widget
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual sf::Vector2f getWidgetOffset() const override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @internal
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual void leftMousePressed(float x, float y) override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @internal
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual void leftMouseReleased(float x, float y) override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @internal
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual void mouseMoved(float x, float y) override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @internal
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual void widgetFocused() override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    protected:

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Reload the widget
        ///
        /// @param primary    Primary parameter for the loader
        /// @param secondary  Secondary parameter for the loader
        /// @param force      Try to only change the looks of the widget and not alter the widget itself when false
        ///
        /// @throw Exception when the connected theme could not create the widget
        ///
        /// When primary is an empty string the built-in white theme will be used.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual void reload(const std::string& primary = "", const std::string& secondary = "", bool force = false) override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Makes a copy of the widget
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual Widget::Ptr clone() const override
        {
            return std::make_shared<SpinButton>(*this);
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Draws the widget on the render target.
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    protected:

        // Is the spin button draw vertically (arrows on top of each other)?
        bool m_verticalScroll = true;

        int m_minimum = 0;
        int m_maximum = 10;
        int m_value = 0;

        // On which arrow is the mouse?
        bool m_mouseHoverOnTopArrow = false;
        bool m_mouseDownOnTopArrow = false;

        friend class SpinButtonRenderer;
    };

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    class TGUI_API SpinButtonRenderer : public WidgetRenderer, public WidgetBorders
    {
    public:

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Constructor
        ///
        /// @param spinButton  The spin button that is connected to the renderer
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        SpinButtonRenderer(SpinButton* spinButton) : m_spinButton{spinButton} {}

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Change a property of the renderer
        ///
        /// @param property  The property that you would like to change
        /// @param value     The new serialized value that you like to assign to the property
        ///
        /// @throw Exception when deserialization fails or when the widget does not have this property.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual void setProperty(std::string property, const std::string& value) override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Change a property of the renderer
        ///
        /// @param property  The property that you would like to change
        /// @param value     The new value that you like to assign to the property.
        ///                  The ObjectConverter is implicitly constructed from the possible value types.
        ///
        /// @throw Exception for unknown properties or when value was of a wrong type.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual void setProperty(std::string property, ObjectConverter&& value) override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Retrieve the value of a certain property
        ///
        /// @param property  The property that you would like to retrieve
        ///
        /// @return The value inside a ObjectConverter object which you can extract with the correct get function or
        ///         an ObjectConverter object with type ObjectConverter::Type::None when the property did not exist.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual ObjectConverter getProperty(std::string property) const override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Get a map with all properties and their values
        ///
        /// @return Property-value pairs of the renderer
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual std::map<std::string, ObjectConverter> getPropertyValuePairs() const override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes the background color of the arrows.
        ///
        /// @param color  New background color
        ///
        /// This color will overwrite the color for both normal and hover states.
        ///
        /// Note that this color is ignored when an up and down arrow image were set.
        ///
        /// @see setBackgroundColorNormal
        /// @see setBackgroundColorHover
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setBackgroundColor(const Color& color);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes the background color of the arrows in the normal state (mouse not on spin button).
        ///
        /// @param color  New background color
        ///
        /// Note that this color is ignored when an up and down arrow image were set.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setBackgroundColorNormal(const Color& color);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes the background color of the arrows in the hover state (mouse standing on top of the spin button).
        ///
        /// @param color  New background color
        ///
        /// Note that this color is ignored when an up and down arrow image were set.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setBackgroundColorHover(const Color& color);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes the color of the arrows.
        ///
        /// @param color  New arrow color
        ///
        /// This color will overwrite the color for both normal and hover states.
        ///
        /// Note that this color is ignored when an up and down arrow image were set.
        ///
        /// @see setArrowColorNormal
        /// @see setArrowColorHover
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setArrowColor(const Color& color);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes the color of the arrows in the normal state (mouse not on spin button).
        ///
        /// @param color  New arrow color
        ///
        /// Note that this color is ignored when an up and down arrow image were set.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setArrowColorNormal(const Color& color);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes the color of the arrows in the hover state (mouse standing on top of the spin button).
        ///
        /// @param color  New arrow color
        ///
        /// Note that this color is ignored when an up and down arrow image were set.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setArrowColorHover(const Color& color);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes the color of the borders that are optionally drawn around the arrows.
        ///
        /// @param color  New border color
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setBorderColor(const Color& color);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Change the image that is used as the up arrow
        ///
        /// @param texture  The new arrow texture
        ///
        /// When this image and the down image are set, the color properties will be ignored.
        /// Pass an empty texture to unset the image, in this case the color properties will be used again.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setArrowUpTexture(const Texture& texture);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Change the image that is used as the down arrow
        ///
        /// @param texture  The new arrow texture
        ///
        /// When this image and the up image are set, the color properties will be ignored.
        /// Pass an empty texture to unset the image, in this case the color properties will be used again.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setArrowDownTexture(const Texture& texture);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Change the image that is used as the up arrow when the mouse is on top of this arrow
        ///
        /// @param texture  The new hover arrow texture
        ///
        /// The hover texture is ignored if no normal texture was set.
        /// Pass an empty texture to unset the image.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setArrowUpHoverTexture(const Texture& texture);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Change the image that is used as the up arrow when the mouse is on top of this arrow
        ///
        /// @param texture  The new hover arrow texture
        ///
        /// The hover texture is ignored if no normal texture was set.
        /// Pass an empty texture to unset the image.
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setArrowDownHoverTexture(const Texture& texture);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// @brief Changes the space that is placed between the arrows.
        ///
        /// This space will use the BorderColor as color.
        ///
        /// When images are used, this space is scaled together with the size of the images
        ///
        /// @param space  New space between the arrows
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void setSpaceBetweenArrows(float space);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Draws the widget on the render target.
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        void draw(sf::RenderTarget& target, sf::RenderStates states) const;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private:

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Makes a copy of the renderer
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        virtual std::shared_ptr<WidgetRenderer> clone(Widget* widget) override;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    protected:

        SpinButton* m_spinButton;

        float     m_spaceBetweenArrows = 2;

        Texture   m_textureArrowUpNormal;
        Texture   m_textureArrowUpHover;
        Texture   m_textureArrowDownNormal;
        Texture   m_textureArrowDownHover;

        sf::Color m_backgroundColorNormal;
        sf::Color m_backgroundColorHover;
        sf::Color m_arrowColorNormal;
        sf::Color m_arrowColorHover;

        sf::Color m_borderColor;

        friend class SpinButton;

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    };

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#endif // TGUI_SPIN_BUTTON_HPP


text:
package de.brands4friends.daleq.core;

/**
 * A data holding entity which represents a table row according to Daleq's data model.
 * This class is used internally by Daleq and should not be accessed directly by clients.
 *
 * @see TableData
 * @see FieldData
 */
public interface RowData {

    /**
     * If the row contains a Field with the given fieldName, the respective {@link FieldData} is returned.
     *
     * @param fieldName the name of a field, which should exist in the respective row.
     * @throws NoSuchDaleqFieldException if such a field does not exist in the RowData
     */
    FieldData getFieldBy(final String fieldName);

    /**
     * Returns true, if such a field exists, otherwise false.
     *
     * @param fieldName the name of a field, which should exist in the respective row.
     */
    boolean containsField(final String fieldName);
}

redpajama_set_name: RedPajamaGithub


text:
require 'apps/messenger/lib/backends/mobyt'

Dato /^che lo username è "([^\"]*)"$/ do |username|
    @username = username
    Spider.conf.set('messenger.mobyt.username',username)
end

Dato /^che la password è "([^\"]*)"$/ do |password|
    @password = password
    Spider.conf.set('messenger.mobyt.password',password)
end

Quando /^invio un sms con i seguenti dati$/ do |table|
    to = table.hashes.first["to"]
    from = table.hashes.first["from"]
    testo = table.hashes.first["testo"]
    @risultato = Spider::Messenger::Mobyt.parametri(@username,@password,to,from,testo)
end

Allora /^il backend deve restituire i seguenti dati$/ do |table|
    table.rows_hash.each do |key, value|
        @risultato[key.to_sym].should eq value
    end
end

Dato /^che il backend è solo di tipo "([^\"]*)"$/ do |backend|
    require "apps/messenger/backends/sms/#{backend}"
    Spider.conf.set('messenger.sms.backends', [backend])
end

Dato /^che il from è "([^\"]*)"$/ do |from|
    Spider.conf.set('messenger.mobyt.from',from)
end

Quando /^invio un messaggio con messenger$/ do
    Spider::Messenger.sms("+39123456789", "Ciao")
end

Quando /^faccio girare la coda dei messaggi$/ do
    require "net/http"

    module Net
        class HTTP
            def self.post_form(uri, data)
                $uri_http = uri
                $data_http = data
            end

        end

    end
    Spider::Messenger.process_queue(:sms)
end

Allora /^deve essere fatta una chiamata in "([^\"]*)" all.url "([^\"]*)"$/ do |post, url|
    $uri_http.to_s.should eq url
end


text:
/**
*	Test case for Selection-Sort nodejs env
*
*	@author Lakha Singh
*/

var sort = require('../selection-sort.js');
var testData = [12, 4, 2, 75, 35, 27, 13];

console.log( sort(testData) );


text:
set -e
set -x
mkdir wmt14
cd wmt14

# download the dataset
wget http://www-lium.univ-lemans.fr/~schwenk/cslm_joint_paper/data/bitexts.tgz
wget http://www-lium.univ-lemans.fr/~schwenk/cslm_joint_paper/data/dev+test.tgz

# untar the dataset
tar -zxvf bitexts.tgz
tar -zxvf dev+test.tgz
gunzip bitexts.selected/*
mv bitexts.selected train
rm bitexts.tgz
rm dev+test.tgz

# separate the dev and test dataset
mkdir test gen
mv dev/ntst1213.* test
mv dev/ntst14.* gen
rm -rf dev

set +x
# rename the suffix, .fr->.src, .en->.trg
for dir in train test gen
do
  filelist=`ls $dir`
  cd $dir
  for file in $filelist
  do
    if [ ${file##*.} = "fr" ]; then
      mv $file ${file/%fr/src}
    elif [ ${file##*.} = 'en' ]; then
      mv $file ${file/%en/trg}
    fi
  done
  cd ..
done


text:
'''
Delayed Power Off (DPO)
-----------------------

Delayed Power off testcase is to test OS graceful shutdown request
to be notified from OPAL and OS should process the request.
We will use "ipmitool power soft" command to issue DPO.
'''

from common.OpTestConstants import OpTestConstants as BMC_CONST
from common.OpTestError import OpTestError

import unittest
import pexpect
import OpTestConfiguration
from common.OpTestSystem import OpSystemState
import common.OpTestQemu as OpTestQemu
import common.OpTestMambo as OpTestMambo

import logging
import OpTestLogger
log = OpTestLogger.optest_logger_glob.get_logger(__name__)

class Base(unittest.TestCase):
    def setUp(self):
        conf = OpTestConfiguration.conf
        self.cv_IPMI = conf.ipmi()
        self.cv_SYSTEM = conf.system()
        self.cv_HOST = conf.host()
        self.bmc_type = conf.args.bmc_type

class DPOSkiroot(Base):

    def setup_test(self):
        self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)
        self.host = "Skiroot"
        log.debug("Starting DPO test in Skiroot")

    def runTest(self):
        '''
        This will test DPO feature in skiroot and Host
        '''
        self.setup_test()
        # retry added for IPMI cases, seems more sensitive with initial start
        # of state=4
        if isinstance(self.cv_SYSTEM.console, OpTestQemu.QemuConsole) \
                or isinstance(self.cv_SYSTEM.console, OpTestMambo.MamboConsole):
            raise self.skipTest("Performing \"ipmitool power soft\" will "
                                "terminate QEMU/Mambo so skipped")
        self.cv_SYSTEM.console.run_command("uname -a", retry=5)
        if self.host == "Host":
            self.cv_SYSTEM.load_ipmi_drivers(True)
        self.cv_SYSTEM.console.pty.sendline("ipmitool power soft")
        rc = self.cv_SYSTEM.console.pty.expect_exact([
            "reboot: Power down",
            "Chassis Power Control: Soft",
            "Power down",
            "OPAL: Shutdown request type 0x0",
            "Invalid command",
            "Unspecified error",
            "Could not open device at",
            pexpect.TIMEOUT,
            pexpect.EOF], timeout=120)
        self.assertIn(rc, [0, 1, 2, 3], "Failed to power down")
        rc = self.cv_SYSTEM.sys_wait_for_standby_state()
        log.debug(rc)
        self.cv_SYSTEM.console.pty.expect_exact(
            ['.*', pexpect.TIMEOUT], timeout=3)
        # Force the system state to be detected again.
        self.cv_SYSTEM.set_state(OpSystemState.OFF)


text:
steal('can/util', function( can ) {

	// Register as an AMD module if supported, otherwise attach to the window
	if (false && typeof define === "function" && define.amd ) {
		define( "can", [], function () { return can; } );
	} else {
		window.can = can;
	}

});


text:
/*
http://www.cgsoso.com/forum-211-1.html

CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源!

CGSOSO 主打游戏开发,影视设计等CG资源素材。

插件如若商用,请务必官网购买!

daily assets update for try.

U should buy the asset from home store if u use it in your project!
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BestHTTP.Extensions
{
    /// <summary>
    /// Used for parsing WWW-Authenticate headers:
    /// Digest realm="my realm", nonce="4664b327a2963503ba58bbe13ad672c0", qop=auth, opaque="f7e38bdc1c66fce214f9019ffe43117c"
    /// </summary>
    public sealed class WWWAuthenticateHeaderParser : KeyValuePairList
    {
        public WWWAuthenticateHeaderParser(string headerValue)
        {
            Values = ParseQuotedHeader(headerValue);
        }

        private List<KeyValuePair> ParseQuotedHeader(string str)
        {
            List<KeyValuePair> result = new List<KeyValuePair>();

            if (str != null)
            {

                int idx = 0;

                // Read Type (Basic|Digest)
                string type = str.Read(ref idx, (ch) => !char.IsWhiteSpace(ch) && !char.IsControl(ch)).TrimAndLower();
                result.Add(new KeyValuePair(type));

                // process the rest of the text
                while (idx < str.Length)
                {
                    // Read key
                    string key = str.Read(ref idx, '=').TrimAndLower();
                    KeyValuePair qp = new KeyValuePair(key);

                    // Skip any white space
                    str.SkipWhiteSpace(ref idx);

                    qp.Value = str.ReadQuotedText(ref idx);

                    result.Add(qp);
                }
            }
            return result;
        }
    }
}


text:
import * as types from '../constants/ActionTypes'

function findIndex (list, id) {
  let i = 0
  // TODO: most efficient search algo in production or use hashmap for exampe
  for (; i < list.length; i++) {
    if (list[i].id === id) break
  }
  return i
}

function pages (state = {
  isFetching: false,
  isCreating: false,
  isToggling: false,
  isDeleting: false,
  deletingPageId: '',
  togglingPageId: '',
  createFormInputNameValue: '',
  items: []
}, action) {
  let index = null

  switch (action.type) {
    case types.REQUEST_PAGES:
      return Object.assign({}, state, {
        isFetching: true
      })
    case types.RECEIVE_PAGES:
      return Object.assign({}, state, {
        isFetching: false,
        items: action.pages
      })
    case types.CREATE_PAGE_REQUEST:
      return Object.assign({}, state, {
        createFormInputNameValue: action.name,
        isCreating: true
      })
    case types.CREATE_PAGE_FAILURE:
      return Object.assign({}, state, {
        isCreating: false
      })
    case types.CREATE_PAGE_SUCCESS:
      return Object.assign({}, state, {
        isCreating: false,
        createFormInputNameValue: '',
        items: [
          ...state.items,
          action.page
        ]
      })
    case types.TOGGLE_PUBLISH_REQUEST:
      return Object.assign({}, state, {
        togglingPageId: action.id,
        isToggling: true
      })
    case types.TOGGLE_PUBLISH_FAILURE:
      return Object.assign({}, state, {
        togglingPageId: '',
        isToggling: false
      })
    case types.TOGGLE_PUBLISH_SUCCESS:
      index = findIndex(state.items, action.page.id)
      return Object.assign({}, state, {
        togglingPageId: '',
        isToggling: false,
        items: [
          ...state.items.slice(0, index),
          action.page,
          ...state.items.slice(index + 1)
        ]
      })
    case types.DELETE_PAGE_REQUEST:
      return Object.assign({}, state, {
        deletingPageId: action.id,
        isDeleting: true
      })
    case types.DELETE_PAGE_FAILURE:
      return Object.assign({}, state, {
        deletingPageId: '',
        isDeleting: false
      })
    case types.DELETE_PAGE_SUCCESS:
      index = findIndex(state.items, action.page.id)
      return Object.assign({}, state, {
        deletingPageId: '',
        isDeleting: false,
        items: [
          ...state.items.slice(0, index),
          ...state.items.slice(index + 1)
        ]
      })
    default:
      return state
  }
}

export default pages


text:
/**
 * Contains method to find the size of a matrix mutation class up to permuting
 * the rows and columns in the matrix.
 */
#pragma once

#include "equiv_mutation_class_loader.h"
#include "equiv_quiver_matrix.h"

namespace cluster {
	namespace equivsize {
		/**
		 * Find the size of the mutation class, up to permuting the vertices of the
		 * matrices.
		 *
		 * Checking for permutations takes longer than just checking equality of
		 * the matrix, so for small cases this can be slower than checking the
		 * whole mutation class. However for larger matrices the mutation classes
		 * are ususally very large (think many millions) and so the program can
		 * easily run out of memory computing them all. This check however will
		 * not.
		 *
		 * @param matrix Matrix to sed the mutation class with
		 * @return Size of the mutation class
		 */
		int Size(const EquivQuiverMatrix& matrix);
	}
}


text:
forest
======

I'm using this as a playground of implementation of trees in Python.
Hopefully you find it useful.

Python Trees:
* Binary Tree
* Binary Search Tree
* N-ary Tree

## Binary Tree

```python
from forest.BinaryTree import BinaryTree

tree = BinaryTree(key=1, item='object',
                  left=BinaryTree(key=2, item='left'),
                  right=BinaryTree(key=3, item='right'),
)

def do_something(node):
    print node

tree.pre_order(visit=do_something)
```

## Binary Search Tree

```python
from forest.BinaryTree import BinarySearchTree

tree = BinarySearchTree(10, 'b')
tree[15] = 'k'
tree[17] = 'm'

# search
tree[15]

# removal
del tree[15]
```

It also contains a Red Black Tree implementation with a similar interface.

## N-ary Tree

```python
from forest.NaryTree import NaryTree

tree = NaryTree(key='1')
branch1 = tree.add_child(key='1.1')
branch2 = tree.add_child(key='1.2')
branch11 = branch1.add_child(key='1.1.1')

def do_something(node):
    print node

tree.traversal(visit=do_something)
```


text:
package com.mqvisualizer.ui.destination.view.dialog;

import com.mqvisualizer.model.connection.JmsDestinationView;
import javafx.event.ActionEvent;
import org.apache.commons.lang3.SerializationUtils;
import org.controlsfx.control.ButtonBar;
import org.controlsfx.control.action.AbstractAction;
import org.controlsfx.dialog.Dialog;
import org.controlsfx.dialog.DialogStyle;

/**
 * Created by Mykolas on 2014-08-20.
 */
public class JmsDestinationViewDialog extends Dialog {

    public JmsDestinationViewDialog() {
        super(null, "Create destination view", false, DialogStyle.NATIVE);

        JmsDestinationView view = new JmsDestinationView();
        JmsDestinationViewPanel panel = new JmsDestinationViewPanel(view);
        setContent(panel);

        CreateJmsDestinationViewAction createAction = new CreateJmsDestinationViewAction(view);
        ButtonBar.setType(createAction, ButtonBar.ButtonType.OK_DONE);
        getActions().addAll(createAction, Actions.CANCEL);

        createAction.disabledProperty().bind(panel.isValidPropertyProperty().not());
    }

    public JmsDestinationViewDialog(JmsDestinationView jmsDestinationView) {
        super(null, "Update destination view", false, DialogStyle.NATIVE);

        JmsDestinationView view = SerializationUtils.clone(jmsDestinationView);
        JmsDestinationViewPanel panel = new JmsDestinationViewPanel(view);
        setContent(panel);

        UpdateJmsDestinationViewAction updateAction =
                new UpdateJmsDestinationViewAction(jmsDestinationView, view);
        ButtonBar.setType(updateAction, ButtonBar.ButtonType.OK_DONE);
        getActions().addAll(updateAction, Actions.CANCEL);

        updateAction.disabledProperty().bind(panel.isValidPropertyProperty().not());
    }

    public class CreateJmsDestinationViewAction extends AbstractAction {

        private JmsDestinationView jmsDestinationView;

        public CreateJmsDestinationViewAction(JmsDestinationView jmsDestinationFilterConfig) {
            super("Create");
            this.jmsDestinationView = jmsDestinationFilterConfig;
        }

        public void handle(ActionEvent event) {
            Dialog d = (Dialog) event.getSource();
            d.hide();
        }

        public JmsDestinationView getJmsDestinationView() {
            return jmsDestinationView;
        }
    }

    public class UpdateJmsDestinationViewAction extends AbstractAction {

        private JmsDestinationView originalJmsDestinationView;
        private JmsDestinationView clonedJmsDestinationView;

        public UpdateJmsDestinationViewAction(
                JmsDestinationView originalJmsDestinationView,
                JmsDestinationView clonedJmsDestinationView
        ) {
            super("Update");
            this.originalJmsDestinationView = originalJmsDestinationView;
            this.clonedJmsDestinationView = clonedJmsDestinationView;
        }

        public void handle(ActionEvent event) {
            originalJmsDestinationView.setName(clonedJmsDestinationView.getName());

            Dialog d = (Dialog) event.getSource();
            d.hide();
        }
    }
}


text:
<?php
namespace TRex\Iterator\Iterator;

use TRex\Core\Enum;

/**
 * Class SortType.
 * Contains the different types of IIteratorSorter.
 *
 * @package TRex\Iterator
 * @author Raphaël Lefebvre <raphael@raphaellefebvre.be>
 * @transient
 */
class SortType extends Enum
{
    /**
     * Sort type by value.
     * Sort const.
     */
    const VALUE_SORT_TYPE = 'sort';

    /**
     * Sort type by key.
     * Sort const.
     */
    const KEY_SORT_TYPE = 'ksort';

    /**
     * Sort type in an associative way.
     * Sort const.
     */
    const ASSOCIATIVE_SORT_TYPE = 'asort';

    /**
     * {@inheritDoc}
     *
     * @param bool $isForCallable
     * @return mixed|string
     */
    public function getValue($isForCallable = false)
    {
        if ($isForCallable) {
            return 'u' . parent::getValue();
        }
        return parent::getValue();
    }
}


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

/// <summary>
/// Fetches local input and store it
/// </summary>
/// <remarks>
/// Used as a proxy for Unity's Input class
/// Sometimes we need to fake some inputs (when replaying old states for example)
/// </remarks>
public class CharacterInput : NetworkBehaviour {

    private CameraAimPoint cameraAim;

    public InputState currentInput;

    void Awake ()
    {
        cameraAim = Camera.main.GetComponent<CameraAimPoint>();
    }

    /// <summary>
    /// Ask to update input from Unity's Input
    /// </summary>
    public void Parse(int inputState)
    {
        if (isLocalPlayer)
        {
            currentInput.inputState = inputState;

            currentInput.setInputHorizontal(Input.GetAxis("Horizontal"));
            currentInput.setInputVertical(Input.GetAxis("Vertical"));
            currentInput.setPitch(cameraAim.pitch);
            currentInput.setYaw(cameraAim.yaw);

            currentInput.inputJump = Input.GetButton("Jump");
            currentInput.inputFire = Input.GetButton("Fire1");
            currentInput.inputAim  = Input.GetButton("Fire2");
            currentInput.inputRun  = Input.GetButton("Run");
        }
    }

    /// <summary>
    /// Internal an clean struct to store and transmit inout states
    /// </summary>
    /// <remarks>
    /// Maybe we don't need float precision for inputVertical or Horizontal
    /// We can store it in short or ints by multipling and rounding values.
    /// Just make sure to do it here so client and server simulate using the same rounded values
    /// </remarks>
    [System.Serializable]
    public struct InputState
    {
        public int inputState;

        public sbyte inputHorizontal;
        public sbyte inputVertical;
        public short pitch;
        public short yaw;

        public bool inputJump;
        public bool inputFire;
        public bool inputAim;
        public bool inputRun;

        public void setPitch(float value)
        {
            pitch = (short)(value * 10);
        }

        public void setYaw(float value)
        {
            yaw = (short)(value * 10);
        }

        public float getPitch()
        {
            return (float)pitch / 10;
        }

        public float getYaw()
        {
            return (float)yaw / 10;
        }

        public void setInputHorizontal(float value)
        {
            inputHorizontal = (sbyte)(value * 127);
        }

        public void setInputVertical(float value)
        {
            inputVertical = (sbyte)(value * 127);
        }

        public float getInputHorizontal()
        {
            return (float)inputHorizontal / 127;
        }

        public float getInputVertical()
        {
            return (float)inputVertical / 127;
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.keenesys.midinclude.midinclude.FacebookMainActivity"
    android:id="@+id/layout_main">

    <Button
        style="@style/ButtonXLarge"
        android:onClick="goToFacebook"
        android:text="@string/facebook"
        android:id="@+id/facebook"
        android:layout_alignParentTop="true"
        android:layout_marginTop="50dp" />

    <Button
        style="@style/ButtonXLarge"
        android:onClick="goToTwitter"
        android:text="@string/twitter"
        android:id="@+id/twitter"
        android:layout_below="@+id/facebook"
        android:layout_marginTop="110dp" />

    <Button
    style="@style/ButtonXLarge"
        android:onClick="goToSettings"
        android:text="@string/configuracoes"
        android:id="@+id/settings_button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>


text:
'use babel';

import EncourageAtom from '../lib/encourage';

// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.

describe('EncourageAtom', () => {
  let workspaceElement, activationPromise;

  beforeEach(() => {
    workspaceElement = atom.views.getView(atom.workspace);

    waitsForPromise(() => {
      return atom.packages.activatePackage('encourage');
    });
  });

  it('defaults to hidden', () => {
    expect(EncourageAtom.modalPanel.isVisible()).toBe(false);
  });

  describe('when a file is saved', () => {
    beforeEach(() => {
      EncourageAtom.encourage();
    });

    it('shows the modal panel', () => {
      expect(EncourageAtom.modalPanel.isVisible()).toBe(true);
    });

    it('hides the panel again after a short delay', () => {
      runs(() => {
        setTimeout(() => {
          expect(EncourageAtom.modalPanel.isVisible()).toBe(false);
        }, 1200);
      })
    })
  });
});


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans.GrainDirectory;

namespace Orleans.Runtime
{
    internal interface IActivationInfo
    {
        SiloAddress SiloAddress { get; }
        DateTime TimeCreated { get; }
        GrainDirectoryEntryStatus RegistrationStatus { get; set; }
        bool OkToRemove(UnregistrationCause cause);
    }

    internal interface IGrainInfo
    {
        Dictionary<ActivationId, IActivationInfo> Instances { get; }
        int VersionTag { get; }
        bool SingleInstance { get; }
        bool AddActivation(ActivationId act, SiloAddress silo);
        ActivationAddress AddSingleActivation(GrainId grain, ActivationId act, SiloAddress silo, GrainDirectoryEntryStatus registrationStatus);
        bool RemoveActivation(ActivationId act, UnregistrationCause cause, out IActivationInfo entry, out bool wasRemoved);
        bool Merge(GrainId grain, IGrainInfo other);
        void CacheOrUpdateRemoteClusterRegistration(GrainId grain, ActivationId oldActivation, ActivationId activation, SiloAddress silo);
        bool UpdateClusterRegistrationStatus(ActivationId activationId, GrainDirectoryEntryStatus registrationStatus, GrainDirectoryEntryStatus? compareWith = null);
    }

    /// <summary>
    /// Per-silo system interface for managing the distributed, partitioned grain-silo-activation directory.
    /// </summary>
    internal interface IRemoteGrainDirectory : ISystemTarget, IGrainDirectory
    {
        /// <summary>
        /// Records a bunch of new grain activations.
        /// This method should be called only remotely during handoff.
        /// </summary>
        /// <param name="addresses">The addresses of the grains to register</param>
        /// <param name="singleActivation">If true, use single-activation registration</param>
        /// <returns></returns>
        Task RegisterMany(List<ActivationAddress> addresses, bool singleActivation);

        /// <summary>
        /// Fetch the updated information on the given list of grains.
        /// This method should be called only remotely to refresh directory caches.
        /// </summary>
        /// <param name="grainAndETagList">list of grains and generation (version) numbers. The latter denote the versions of
        /// the lists of activations currently held by the invoker of this method.</param>
        /// <returns>list of tuples holding a grain, generation number of the list of activations, and the list of activations.
        /// If the generation number of the invoker matches the number of the destination, the list is null. If the destination does not
        /// hold the information on the grain, generation counter -1 is returned (and the list of activations is null)</returns>
        Task<List<Tuple<GrainId, int, List<ActivationAddress>>>> LookUpMany(List<Tuple<GrainId, int>> grainAndETagList);

        /// <summary>
        /// Handoffs the the directory partition from source silo to the destination silo.
        /// </summary>
        /// <param name="source">The address of the owner of the partition.</param>
        /// <param name="partition">The (full or partial) copy of the directory partition to be Haded off.</param>
        /// <param name="isFullCopy">Flag specifying whether it is a full copy of the directory partition (and thus any old copy should be just replaced) or the
        /// a delta copy (and thus the old copy should be updated by delta changes) </param>
        /// <returns></returns>
        Task AcceptHandoffPartition(SiloAddress source, Dictionary<GrainId, IGrainInfo> partition, bool isFullCopy);

        /// <summary>
        /// Removes the handed off directory partition from source silo on the destination silo.
        /// </summary>
        /// <param name="source">The address of the owner of the partition.</param>
        /// <returns></returns>
        Task RemoveHandoffPartition(SiloAddress source);
    }
}


text:
package com.amazonaws.services.dynamodbv2.datamodeling;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

import org.apache.http.annotation.GuardedBy;

/**
 * Reflection assistant for {@link DynamoDBMapper}
 */
class DynamoDBReflector {

    /*
     * Several caches for performance. Collectively, they can make this class
     * over twice as fast.
     */
    private final Map<Class<?>, Collection<Method>> getterCache = new HashMap<Class<?>, Collection<Method>>();
    private final Map<Class<?>, Method> primaryHashKeyGetterCache = new HashMap<Class<?>, Method>();
    private final Map<Class<?>, Method> primaryRangeKeyGetterCache = new HashMap<Class<?>, Method>();

    /*
     * All caches keyed by a Method use the getter for a particular mapped
     * property
     */
    private final Map<Method, Method> setterCache = new HashMap<Method, Method>();

    @GuardedBy("readWriteLockAttrName")
    private final Map<Method, String> attributeNameCache = new HashMap<Method, String>();

    private final Map<Method, Boolean> versionAttributeGetterCache = new HashMap<Method, Boolean>();
    private final Map<Method, Boolean> autoGeneratedKeyGetterCache = new HashMap<Method, Boolean>();

    private final ReentrantReadWriteLock readWriteLockAttrName = new ReentrantReadWriteLock();
    private final ReadLock readLockAttrName = readWriteLockAttrName.readLock();
    private final WriteLock writeLockAttrName = readWriteLockAttrName.writeLock();

    /**
     * Returns the set of getter methods which are relevant when marshalling or
     * unmarshalling an object.
     */
    Collection<Method> getRelevantGetters(Class<?> clazz) {
        synchronized (getterCache) {
            if ( !getterCache.containsKey(clazz) ) {
                List<Method> relevantGetters = findRelevantGetters(clazz);
                getterCache.put(clazz, relevantGetters);
            }
            return getterCache.get(clazz);
        }
    }

    static List<Method> findRelevantGetters(Class<?> clazz) {
        List<Method> relevantGetters = new LinkedList<Method>();
        for ( Method m : clazz.getMethods() ) {
            if ( isRelevantGetter(m) ) {
                relevantGetters.add(m);
            }
        }
        return relevantGetters;
    }

    /**
     * Returns whether the method given is a getter method we should serialize /
     * deserialize to the service. The method must begin with "get" or "is",
     * have no arguments, belong to a class that declares its table, and not be
     * marked ignored.
     */
    private static boolean isRelevantGetter(Method m) {
        return (m.getName().startsWith("get") || m.getName().startsWith("is"))
                && m.getParameterTypes().length == 0
                && ! (m.isBridge() || m.isSynthetic())
                && isDocumentType(m.getDeclaringClass())
                && !ReflectionUtils.getterOrFieldHasAnnotation(m, DynamoDBIgnore.class);
    }

    private static boolean isDocumentType(Class<?> clazz) {
        return (clazz.getAnnotation(DynamoDBTable.class) != null)
                || (clazz.getAnnotation(DynamoDBDocument.class) != null);
    }

    /**
     * Returns the annotated {@link DynamoDBRangeKey} getter for the class
     * given, or null if the class doesn't have one.
     */
    <T> Method getPrimaryRangeKeyGetter(Class<T> clazz) {
        synchronized (primaryRangeKeyGetterCache) {
            if ( !primaryRangeKeyGetterCache.containsKey(clazz) ) {
                Method rangeKeyMethod = null;
                for ( Method method : getRelevantGetters(clazz) ) {
                    if ( method.getParameterTypes().length == 0
                            && ReflectionUtils.getterOrFieldHasAnnotation(method, DynamoDBRangeKey.class)) {
                        rangeKeyMethod = method;
                        break;
                    }
                }
                primaryRangeKeyGetterCache.put(clazz, rangeKeyMethod);
            }
            return primaryRangeKeyGetterCache.get(clazz);
        }
    }

    /**
     * Returns all annotated {@link DynamoDBHashKey} and
     * {@link DynamoDBRangeKey} getters for the class given, throwing an
     * exception if there isn't one.
     *
     * TODO: caching
     */
    <T> Collection<Method> getPrimaryKeyGetters(Class<T> clazz) {
        List<Method> keyGetters = new LinkedList<Method>();
        for (Method getter : getRelevantGetters(clazz)) {
            if (ReflectionUtils.getterOrFieldHasAnnotation(getter, DynamoDBHashKey.class)
                    || ReflectionUtils.getterOrFieldHasAnnotation(getter, DynamoDBRangeKey.class)) {
                keyGetters.add(getter);
            }
        }

        return keyGetters;
    }

    /**
     * Returns the annotated {@link DynamoDBHashKey} getter for the class given,
     * throwing an exception if there isn't one.
     */
    <T> Method getPrimaryHashKeyGetter(Class<T> clazz) {
        Method hashKeyMethod;
        synchronized (primaryHashKeyGetterCache) {
            if ( !primaryHashKeyGetterCache.containsKey(clazz) ) {
                for ( Method method : getRelevantGetters(clazz) ) {
                    if ( method.getParameterTypes().length == 0
                            && ReflectionUtils.getterOrFieldHasAnnotation(method, DynamoDBHashKey.class)) {
                        primaryHashKeyGetterCache.put(clazz, method);
                        break;
                    }
                }
            }
            hashKeyMethod = primaryHashKeyGetterCache.get(clazz);
        }

        if ( hashKeyMethod == null ) {
            throw new DynamoDBMappingException("Public, zero-parameter hash key property must be annotated with "
                    + DynamoDBHashKey.class);
        }
        return hashKeyMethod;
    }

    /**
     * Returns the {@link DynamoDBTable} annotation of the class given, throwing
     * a runtime exception if it isn't annotated.
     */
    <T> DynamoDBTable getTable(Class<T> clazz) {
        DynamoDBTable table = clazz.getAnnotation(DynamoDBTable.class);
        if ( table == null )
            throw new DynamoDBMappingException("Class " + clazz + " must be annotated with " + DynamoDBTable.class);
        return table;
    }

    /**
     * Returns the attribute name corresponding to the given getter method.
     */
    String getAttributeName(Method getter) {
        String attributeName;
        readLockAttrName.lock();
        try {
            attributeName = attributeNameCache.get(getter);
        } finally {
            readLockAttrName.unlock();
        }
        if ( attributeName != null )
            return attributeName;
        DynamoDBHashKey hashKeyAnnotation = ReflectionUtils.getAnnotationFromGetterOrField(getter, DynamoDBHashKey.class);
        if ( hashKeyAnnotation != null ) {
            attributeName = hashKeyAnnotation.attributeName();
            if ( attributeName != null && attributeName.length() > 0 )
                return cacheAttributeName(getter, attributeName);
        }
        DynamoDBIndexHashKey indexHashKey = ReflectionUtils.getAnnotationFromGetterOrField(getter, DynamoDBIndexHashKey.class);
        if ( indexHashKey != null ) {
            attributeName = indexHashKey.attributeName();
            if ( attributeName != null && attributeName.length() > 0 )
                return cacheAttributeName(getter, attributeName);
        }
        DynamoDBRangeKey rangeKey = ReflectionUtils.getAnnotationFromGetterOrField(getter, DynamoDBRangeKey.class);
        if ( rangeKey != null ) {
            attributeName = rangeKey.attributeName();
            if ( attributeName != null && attributeName.length() > 0 )
                return cacheAttributeName(getter, attributeName);
        }
        DynamoDBIndexRangeKey indexRangeKey = ReflectionUtils.getAnnotationFromGetterOrField(getter, DynamoDBIndexRangeKey.class);
        if ( indexRangeKey != null ) {
            attributeName = indexRangeKey.attributeName();
            if ( attributeName != null && attributeName.length() > 0 )
                return cacheAttributeName(getter, attributeName);
        }
        DynamoDBAttribute attribute = ReflectionUtils.getAnnotationFromGetterOrField(getter, DynamoDBAttribute.class);
        if ( attribute != null ) {
            attributeName = attribute.attributeName();
            if ( attributeName != null && attributeName.length() > 0 )
                return cacheAttributeName(getter, attributeName);
        }
        DynamoDBVersionAttribute version = ReflectionUtils.getAnnotationFromGetterOrField(getter, DynamoDBVersionAttribute.class);
        if ( version != null ) {
            attributeName = version.attributeName();
            if ( attributeName != null && attributeName.length() > 0 )
                return cacheAttributeName(getter, attributeName);
        }
        // Default to the camel-cased field name of the getter method, inferred
        // according to the Java naming convention.
        attributeName = ReflectionUtils.getFieldNameByGetter(getter, true);
        return cacheAttributeName(getter, attributeName);
    }

    private String cacheAttributeName(Method getter, String attributeName) {
        writeLockAttrName.lock();
        try {
            attributeNameCache.put(getter, attributeName);
        } finally {
            writeLockAttrName.unlock();
        }
        return attributeName;
    }

    /**
     * Returns the setter corresponding to the getter given, or null if no such
     * setter exists.
     */
    Method getSetter(Method getter) {
        synchronized (setterCache) {
            if ( !setterCache.containsKey(getter) ) {
                String fieldName = ReflectionUtils.getFieldNameByGetter(getter, false);
                String setterName = "set" + fieldName;
                Method setter = null;
                try {
                    setter = getter.getDeclaringClass().getMethod(setterName, getter.getReturnType());
                } catch ( NoSuchMethodException e ) {
                    throw new DynamoDBMappingException("Expected a public, one-argument method called " + setterName
                            + " on class " + getter.getDeclaringClass(), e);
                } catch ( SecurityException e ) {
                    throw new DynamoDBMappingException("No access to public, one-argument method called " + setterName
                            + " on class " + getter.getDeclaringClass(), e);
                }
                setterCache.put(getter, setter);
            }
            return setterCache.get(getter);
        }
    }

    /**
     * Returns whether the method given is an annotated, no-args getter of a
     * version attribute.
     */
    boolean isVersionAttributeGetter(Method getter) {
        synchronized (versionAttributeGetterCache) {
            if ( !versionAttributeGetterCache.containsKey(getter) ) {
                versionAttributeGetterCache.put(
                        getter,
                        getter.getName().startsWith("get") && getter.getParameterTypes().length == 0
                                && ReflectionUtils.getterOrFieldHasAnnotation(getter, DynamoDBVersionAttribute.class));
            }
            return versionAttributeGetterCache.get(getter);
        }
    }

    /**
     * Returns whether the method given is an assignable key getter.
     */
    boolean isAssignableKey(Method getter) {
        synchronized (autoGeneratedKeyGetterCache) {
            if ( !autoGeneratedKeyGetterCache.containsKey(getter) ) {
                autoGeneratedKeyGetterCache.put(
                        getter,
                        ReflectionUtils.getterOrFieldHasAnnotation(getter, DynamoDBAutoGeneratedKey.class)
                                && ( ReflectionUtils.getterOrFieldHasAnnotation(getter, DynamoDBHashKey.class) ||
                                     ReflectionUtils.getterOrFieldHasAnnotation(getter, DynamoDBRangeKey.class) ||
                                     ReflectionUtils.getterOrFieldHasAnnotation(getter, DynamoDBIndexHashKey.class) ||
                                     ReflectionUtils.getterOrFieldHasAnnotation(getter, DynamoDBIndexRangeKey.class)));
            }
            return autoGeneratedKeyGetterCache.get(getter);
        }
    }

    /**
     * Returns the name of the primary hash key.
     */
    String getPrimaryHashKeyName(Class<?> clazz) {
        return getAttributeName(getPrimaryHashKeyGetter(clazz));
    }

    /**
     * Returns the name of the primary range key, or null if the table does not
     * one.
     */
    String getPrimaryRangeKeyName(Class<?> clazz) {
        Method primaryRangeKeyGetter = getPrimaryHashKeyGetter(clazz);
        return primaryRangeKeyGetter == null ?
                null
                :
                getAttributeName(getPrimaryRangeKeyGetter(clazz));
    }

    /**
     * Returns true if and only if the specified class has declared a
     * primary range key.
     */
    boolean hasPrimaryRangeKey(Class<?> clazz) {
        return getPrimaryRangeKeyGetter(clazz) != null;
    }
}


text:
layout: page
title: Download
---
# Download
Nothing here yet... edit ```download.html``` to change this contents.


text:
/**
 * @author Vincent Cheung (coolingfall@gmail.com)
 */

export { RxjsCallAdapter } from "./rxjs-call-adapter";


text:
package org.elasticsearch.xpack.core.action;

import org.elasticsearch.action.ActionType;
import org.elasticsearch.xpack.core.XPackField;

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

/**
 * A base action for info about a feature plugin.
 *
 * This action is implemented by each feature plugin, bound to the public constants here. The
 * {@link XPackInfoAction} implementation iterates over the {@link #ALL} list of actions to form
 * the complete info result.
 */
public class XPackInfoFeatureAction extends ActionType<XPackInfoFeatureResponse> {

    private static final String BASE_NAME = "cluster:monitor/xpack/info/";

    public static final XPackInfoFeatureAction SECURITY = new XPackInfoFeatureAction(XPackField.SECURITY);
    public static final XPackInfoFeatureAction MONITORING = new XPackInfoFeatureAction(XPackField.MONITORING);
    public static final XPackInfoFeatureAction WATCHER = new XPackInfoFeatureAction(XPackField.WATCHER);
    public static final XPackInfoFeatureAction GRAPH = new XPackInfoFeatureAction(XPackField.GRAPH);
    public static final XPackInfoFeatureAction MACHINE_LEARNING = new XPackInfoFeatureAction(XPackField.MACHINE_LEARNING);
    public static final XPackInfoFeatureAction LOGSTASH = new XPackInfoFeatureAction(XPackField.LOGSTASH);
    public static final XPackInfoFeatureAction EQL = new XPackInfoFeatureAction(XPackField.EQL);
    public static final XPackInfoFeatureAction SQL = new XPackInfoFeatureAction(XPackField.SQL);
    public static final XPackInfoFeatureAction ROLLUP = new XPackInfoFeatureAction(XPackField.ROLLUP);
    public static final XPackInfoFeatureAction INDEX_LIFECYCLE = new XPackInfoFeatureAction(XPackField.INDEX_LIFECYCLE);
    public static final XPackInfoFeatureAction SNAPSHOT_LIFECYCLE = new XPackInfoFeatureAction(XPackField.SNAPSHOT_LIFECYCLE);
    public static final XPackInfoFeatureAction CCR = new XPackInfoFeatureAction(XPackField.CCR);
    public static final XPackInfoFeatureAction TRANSFORM = new XPackInfoFeatureAction(XPackField.TRANSFORM);
    public static final XPackInfoFeatureAction VECTORS = new XPackInfoFeatureAction(XPackField.VECTORS);
    public static final XPackInfoFeatureAction VOTING_ONLY = new XPackInfoFeatureAction(XPackField.VOTING_ONLY);
    public static final XPackInfoFeatureAction FROZEN_INDICES = new XPackInfoFeatureAction(XPackField.FROZEN_INDICES);
    public static final XPackInfoFeatureAction SPATIAL = new XPackInfoFeatureAction(XPackField.SPATIAL);
    public static final XPackInfoFeatureAction ANALYTICS = new XPackInfoFeatureAction(XPackField.ANALYTICS);
    public static final XPackInfoFeatureAction ENRICH = new XPackInfoFeatureAction(XPackField.ENRICH);
    public static final XPackInfoFeatureAction SEARCHABLE_SNAPSHOTS = new XPackInfoFeatureAction(XPackField.SEARCHABLE_SNAPSHOTS);
    public static final XPackInfoFeatureAction DATA_STREAMS = new XPackInfoFeatureAction(XPackField.DATA_STREAMS);
    public static final XPackInfoFeatureAction DATA_TIERS = new XPackInfoFeatureAction(XPackField.DATA_TIERS);
    public static final XPackInfoFeatureAction AGGREGATE_METRIC = new XPackInfoFeatureAction(XPackField.AGGREGATE_METRIC);

    public static final List<XPackInfoFeatureAction> ALL;
    static {
        final List<XPackInfoFeatureAction> actions = new ArrayList<>();
        actions.addAll(Arrays.asList(
            SECURITY, MONITORING, WATCHER, GRAPH, MACHINE_LEARNING, LOGSTASH, EQL, SQL, ROLLUP, INDEX_LIFECYCLE, SNAPSHOT_LIFECYCLE, CCR,
            TRANSFORM, VECTORS, VOTING_ONLY, FROZEN_INDICES, SPATIAL, ANALYTICS, ENRICH, DATA_STREAMS, SEARCHABLE_SNAPSHOTS, DATA_TIERS,
            AGGREGATE_METRIC
        ));
        ALL = Collections.unmodifiableList(actions);
    }

    private XPackInfoFeatureAction(String name) {
        super(BASE_NAME + name, XPackInfoFeatureResponse::new);
    }

    @Override
    public String toString() {
        return "ActionType [" + name() + "]";
    }
}


text:
package org.apache.http.conn.scheme;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Extended {@link SchemeSocketFactory} interface for layered sockets such as SSL/TLS.
 *
 * @since 4.1
 *
 * @deprecated (4.2)  use {@link SchemeLayeredSocketFactory}
 */
@Deprecated
public interface LayeredSchemeSocketFactory extends SchemeSocketFactory {

    /**
     * Returns a socket connected to the given host that is layered over an
     * existing socket.  Used primarily for creating secure sockets through
     * proxies.
     *
     * @param socket the existing socket
     * @param target    the name of the target host.
     * @param port      the port to connect to on the target host
     * @param autoClose a flag for closing the underling socket when the created
     * socket is closed
     *
     * @return Socket a new socket
     *
     * @throws IOException if an I/O error occurs while creating the socket
     * @throws UnknownHostException if the IP address of the host cannot be
     * determined
     */
    Socket createLayeredSocket(
        Socket socket,
        String target,
        int port,
        boolean autoClose
    ) throws IOException, UnknownHostException;

}


text: define({toggle:"Basculer pour se déplacer ou pivoter en 3D"});


text:
uint32_t ConvertAsset_HLSL_Bytecode
(
	asset_s* outAsset,
	const void* data,
	uint64_t dataSizeInBytes,
	const char* basePath,
	uint32_t basePathLength,
	Memory_Linear_Allocator* allocator,
	uint32_t allocatorIdx
)
{
	return 0;
}

uint32_t ConvertAsset_SPIRV
(
	asset_s* outAsset,
	const void* data,
	uint64_t dataSizeInBytes,
	const char* basePath,
	uint32_t basePathLength,
	Memory_Linear_Allocator* allocator,
	uint32_t allocatorIdx
)
{
	return 0;
}

///////////////////////////////////////////
////Shader
///////////////////////////////////////////
Shader::Shader()
{

}

Shader::Shader(VkPipelineShaderStageCreateInfo shaderStage)
{
	m_shaderStage = shaderStage;
}

Shader::~Shader()
{
}

namespace VKTools
{
	///////////////////////////////////////////
	////ShaderLoader
	///////////////////////////////////////////
	Shader LoadShader(const char* fileName, const char* entryPoint, VkDevice device, VkShaderStageFlagBits stage, const char* globalFile)
	{
		VkPipelineShaderStageCreateInfo shaderStage = {};
		shaderStage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
		shaderStage.stage = stage;

		// Read the shader
		size_t size;
		FILE *fp = fopen(fileName, "rb");
		assert(fp);

		fseek(fp, 0L, SEEK_END);
		size = ftell(fp);
		fseek(fp, 0L, SEEK_SET);

		char* shaderCode = new char[size];
		size_t retval = fread(shaderCode, size, 1, fp);
		assert(retval == 1);
		assert(size > 0);
		fclose(fp);

		// Read the global
		size_t gsize = 0;
		char* globalCode = NULL;
		if (globalFile)
		{
			FILE* gfp = fopen(globalFile, "rb");
			assert(gfp);

			//get the size
			fseek(gfp, 0L, SEEK_END);
			gsize = ftell(gfp);
			fseek(gfp, 0L, SEEK_SET);

			globalCode = new char[gsize];
			size_t retval = fread(globalCode, gsize, 1, gfp);
			assert(retval == 1);
			assert(size > 0);
			fclose(gfp);
		}

		char* comb = new char[size + gsize];
		memcpy(comb, shaderCode, size);
		memcpy(comb + size, globalCode, gsize);

		VkShaderModule shaderModule;
		VkShaderModuleCreateInfo moduleCreateInfo;
		moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
		moduleCreateInfo.pNext = NULL;
		moduleCreateInfo.codeSize = size;
		moduleCreateInfo.pCode = (uint32_t*)comb;
		moduleCreateInfo.flags = 0;

		VK_CHECK_RESULT(vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderModule));

		delete[] shaderCode;
		delete[] comb;
		if (globalCode) delete[] globalCode;

		shaderStage.module = shaderModule;
		shaderStage.pName = entryPoint; // todo : make param
		assert(shaderStage.module != NULL);
		//create the shader class
		Shader shader(shaderStage);
		//return the shader
		return shader;
	}
};


text:
package com.example;

import android.os.Bundle;

import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

import expo.modules.splashscreen.singletons.SplashScreen;
import expo.modules.splashscreen.SplashScreenImageResizeMode;

public class MainActivity extends ReactActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
    // SplashScreen.show(...) has to be called after super.onCreate(...)
    // Below line is handled by '@expo/configure-splash-screen' command and it's discouraged to modify it manually
    SplashScreen.show(this, SplashScreenImageResizeMode.CONTAIN, ReactRootView.class, false);
  }

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "main";
    }

    @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Override
            protected ReactRootView createRootView() {
                return new RNGestureHandlerEnabledRootView(MainActivity.this);
            }
        };
    }
}


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

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

import org.apache.commons.lang3.StringUtils;
import org.flowable.app.model.common.UserRepresentation;
import org.flowable.app.model.runtime.TaskRepresentation;
import org.flowable.app.security.SecurityUtils;
import org.flowable.app.service.api.UserCache.CachedUser;
import org.flowable.app.service.exception.BadRequestException;
import org.flowable.app.service.exception.NotFoundException;
import org.flowable.app.service.exception.NotPermittedException;
import org.flowable.engine.common.api.FlowableException;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.identitylink.api.history.HistoricIdentityLink;
import org.flowable.identitylink.service.IdentityLinkType;
import org.flowable.idm.api.User;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * @author Tijs Rademakers
 */
@Service
@Transactional
public class FlowableTaskActionService extends FlowableAbstractTaskService {

    private static final Logger LOGGER = LoggerFactory.getLogger(FlowableTaskActionService.class);

    public void completeTask(String taskId) {
        User currentUser = SecurityUtils.getCurrentUserObject();
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        if (task == null) {
            throw new NotFoundException("Task with id: " + taskId + " does not exist");
        }

        if (!permissionService.isTaskOwnerOrAssignee(currentUser, task)) {
            if (StringUtils.isEmpty(task.getScopeType()) && !permissionService.validateIfUserIsInitiatorAndCanCompleteTask(currentUser, task)) {
                throw new NotPermittedException();
            }
        }

        try {
            if (StringUtils.isEmpty(task.getScopeType())) {
                taskService.complete(task.getId());
            } else {
                cmmnTaskService.complete(task.getId());
            }

        } catch (FlowableException e) {
            LOGGER.error("Error completing task {}", taskId, e);
            throw new BadRequestException("Task " + taskId + " can't be completed", e);
        }
    }

    public TaskRepresentation assignTask(String taskId, ObjectNode requestNode) {
        User currentUser = SecurityUtils.getCurrentUserObject();
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        if (task == null) {
            throw new NotFoundException("Task with id: " + taskId + " does not exist");
        }

        checkTaskPermissions(taskId, currentUser, task);

        if (requestNode.get("assignee") != null) {

            // This method can only be called by someone in a tenant. Check if the user is part of the tenant
            String assigneeIdString = requestNode.get("assignee").asText();

            CachedUser cachedUser = userCache.getUser(assigneeIdString);
            if (cachedUser == null) {
                throw new BadRequestException("Invalid assignee id");
            }
            assignTask(currentUser, task, assigneeIdString);

        } else {
            throw new BadRequestException("Assignee is required");
        }

        task = taskService.createTaskQuery().taskId(taskId).singleResult();
        TaskRepresentation rep = new TaskRepresentation(task);
        fillPermissionInformation(rep, task, currentUser);

        populateAssignee(task, rep);
        rep.setInvolvedPeople(getInvolvedUsers(taskId));
        return rep;
    }

    public void involveUser(String taskId, ObjectNode requestNode) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        if (task == null) {
            throw new NotFoundException("Task with id: " + taskId + " does not exist");
        }

        User currentUser = SecurityUtils.getCurrentUserObject();
        permissionService.validateReadPermissionOnTask(currentUser, task.getId());

        if (requestNode.get("userId") != null) {
            String userId = requestNode.get("userId").asText();
            CachedUser user = userCache.getUser(userId);
            if (user == null) {
                throw new BadRequestException("Invalid user id");
            }
            taskService.addUserIdentityLink(taskId, userId, IdentityLinkType.PARTICIPANT);

        } else {
            throw new BadRequestException("User id is required");
        }

    }

    public void removeInvolvedUser(String taskId, ObjectNode requestNode) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        if (task == null) {
            throw new NotFoundException("Task with id: " + taskId + " does not exist");
        }

        permissionService.validateReadPermissionOnTask(SecurityUtils.getCurrentUserObject(), task.getId());

        String assigneeString = null;
        if (requestNode.get("userId") != null) {
            String userId = requestNode.get("userId").asText();
            if (userCache.getUser(userId) == null) {
                throw new BadRequestException("Invalid user id");
            }
            assigneeString = String.valueOf(userId);

        } else if (requestNode.get("email") != null) {

            String email = requestNode.get("email").asText();
            assigneeString = email;

        } else {
            throw new BadRequestException("User id or email is required");
        }

        taskService.deleteUserIdentityLink(taskId, assigneeString, IdentityLinkType.PARTICIPANT);
    }

    public void claimTask(String taskId) {

        User currentUser = SecurityUtils.getCurrentUserObject();
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        if (task == null) {
            throw new NotFoundException("Task with id: " + taskId + " does not exist");
        }

        permissionService.validateReadPermissionOnTask(currentUser, task.getId());

        try {
            taskService.claim(task.getId(), String.valueOf(currentUser.getId()));
        } catch (FlowableException e) {
            throw new BadRequestException("Task " + taskId + " can't be claimed", e);
        }
    }

    protected void checkTaskPermissions(String taskId, User currentUser, Task task) {
        permissionService.validateReadPermissionOnTask(currentUser, task.getId());
    }

    protected String validateEmail(ObjectNode requestNode) {
        String email = requestNode.get("email") != null ? requestNode.get("email").asText() : null;
        if (email == null) {
            throw new BadRequestException("Email is mandatory");
        }
        return email;
    }

    protected void assignTask(User currentUser, Task task, String assigneeIdString) {
        try {
            String oldAssignee = task.getAssignee();
            taskService.setAssignee(task.getId(), assigneeIdString);

            // If the old assignee user wasn't part of the involved users yet, make it so
            addIdentiyLinkForUser(task, oldAssignee, IdentityLinkType.PARTICIPANT);

            // If the current user wasn't part of the involved users yet, make it so
            String currentUserIdString = String.valueOf(currentUser.getId());
            addIdentiyLinkForUser(task, currentUserIdString, IdentityLinkType.PARTICIPANT);

        } catch (FlowableException e) {
            throw new BadRequestException("Task " + task.getId() + " can't be assigned", e);
        }
    }

    protected void addIdentiyLinkForUser(Task task, String userId, String linkType) {
        List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(task.getId());
        boolean isOldUserInvolved = false;
        for (IdentityLink identityLink : identityLinks) {
            if (userId.equals(identityLink.getUserId()) && (identityLink.getType().equals(IdentityLinkType.PARTICIPANT) || identityLink.getType().equals(IdentityLinkType.CANDIDATE))) {
                isOldUserInvolved = true;
            }
        }
        if (!isOldUserInvolved) {
            taskService.addUserIdentityLink(task.getId(), userId, linkType);
        }
    }

    protected void populateAssignee(TaskInfo task, TaskRepresentation rep) {
        if (task.getAssignee() != null) {
            CachedUser cachedUser = userCache.getUser(task.getAssignee());
            if (cachedUser != null && cachedUser.getUser() != null) {
                rep.setAssignee(new UserRepresentation(cachedUser.getUser()));
            }
        }
    }

    protected List<UserRepresentation> getInvolvedUsers(String taskId) {
        List<HistoricIdentityLink> idLinks = historyService.getHistoricIdentityLinksForTask(taskId);
        List<UserRepresentation> result = new ArrayList<>(idLinks.size());

        for (HistoricIdentityLink link : idLinks) {
            // Only include users and non-assignee links
            if (link.getUserId() != null && !IdentityLinkType.ASSIGNEE.equals(link.getType())) {
                CachedUser cachedUser = userCache.getUser(link.getUserId());
                if (cachedUser != null && cachedUser.getUser() != null) {
                    result.add(new UserRepresentation(cachedUser.getUser()));
                }
            }
        }
        return result;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.isa.pad</groupId>
    <artifactId>BasicMQ</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <repositories>
        <repository>
            <url>
                https://maven.atlassian.com/3rdparty/
            </url>
            <id>
                Attlassian
            </id>
        </repository>
    </repositories>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.simpleframework/simple-xml -->
        <dependency>
            <groupId>org.simpleframework</groupId>
            <artifactId>simple-xml</artifactId>
            <version>2.7.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.4.1208-jdbc42-atlassian-hosted</version>
        </dependency>
    </dependencies>
</project>


text:
shared_examples 'it has an attribute for' do |attribute, default_value = nil|
  it "the attribute '#{attribute}'" do
    obj = described_class.new
    expect(obj.send(attribute)).to eq default_value
    obj.send("#{attribute}=", :foo)
    expect(obj.send(attribute)).to eq :foo
  end
end

shared_examples 'a CanvasCc::CanvasCC::Models::Resource' do
  it "by inheriting CanvasCc::CanvasCC::Models::Resource" do
    expect(described_class.ancestors).to include CanvasCc::CanvasCC::Models::Resource
  end
end

shared_examples 'a CanvasCc::Moodle2::Models::Quizzes::Question' do
  it "by inheriting CanvasCc::Moodle2::Models::Quizzes:Question" do
    expect(described_class.ancestors).to include CanvasCc::Moodle2::Models::Quizzes::Question
  end
end

shared_examples 'it is registered as a Question' do |type|
  it "for the type '#{type}'" do
    expect(CanvasCc::Moodle2::Models::Quizzes::Question.create(type)).to be_instance_of described_class
  end
end


text:
package de.nl.moo.responses.database;

public class ResearchApplicationResponse extends AbstractDatabaseFunctionResponse {

    private double costs = 0;

    private String technology = null;

    public ResearchApplicationResponse() {
        super();
    }

    public double getCosts() {
        return costs;
    }

    public void setCosts(double costs) {
        this.costs = costs;
    }

    public String getTechnology() {
        return technology;
    }

    public void setTechnology(String technology) {
        this.technology = technology;
    }
}


text:
  Template Name
  <input type="text" ng-model="$ctrl.inputName"/>
  <button ng-click='$ctrl.name($ctrl.inputName)' class="btn btn-success">Get Template</button>
  <button ng-click="$ctrl.getTimedTemps()" class="btn btn-info">Timed Templates</button>
  <button ng-click="$ctrl.getUntimedTemps()" class="btn btn-info">Untimed Templates</button>

      {{ show }}

      {{ show2 }}

<timed-view ng-if="$ctrl.timed" data="$ctrl.workoutData" workout="$ctrl.workout"></timed-view>
<untimed-view ng-if="$ctrl.untimed" data="$ctrl.workoutData" workout="$ctrl.workout"></untimed-view>


text:
module Fluent::Plugin
  module EverySenseProxy
    require 'uri'
    require 'net/http'
    require 'json'
    require 'time'

    class EverySenseProxyError
    end

    def start_proxy
      log.debug "start everysense proxy #{@url}"

      @uri = URI.parse(@url)
      @https = Net::HTTP.new(@uri.host, @uri.port)
      @https.use_ssl = (@uri.scheme == 'https')
      @session_key = nil
    end

    def shutdown_proxy
      log.debug "shutdown_proxy #{@session_key}"
      delete_session
      @https.finish() if @https.active?
    end

    def error_handler(response, message)
      if response.code != "200"
        log.error error: message
        log.debug "code: #{response.code}"
        log.debug "message: #{response.message}"
        log.debug "body: #{response.body}"
        return false
      end
      return true
    end

    def valid_session?
      # TODO validate @session_key using EverySense API
      if !@session_key.nil?
        if Time.now < @session_expires_in
          return true
        end
      end
      return false
    end

    def create_session_request
      session_req = Net::HTTP::Post.new(@uri + '/session')
      session_req.body = {login_name: @login_name, password: @password}.to_json
      session_req.content_type = 'application/json'
      session_req
    end

    def create_session
      return @session_key if valid_session?
      @session_req ||= create_session_request
      session_res = @https.request(@session_req)
      return nil if !error_handler(session_res, 'create_session failed.')
      @session_key = JSON.parse(session_res.body)["session_key"]
      @session_expires_in = Time.now + 60 * 60 * 12 # assuming time out in a half day
    end

    def delete_session_request
      Net::HTTP::Delete.new(@uri + "/session/#{@session_key}")
    end

    def delete_session
      return if !valid_session?
      del_session_res = @https.request(delete_session_request)
      error_handler(del_session_res, 'delete_session failed.')
    end

    def put_message_request(message)
      put_message_req = Net::HTTP::Post.new(@uri + "/device_data/#{@device_id}")
      put_message_req.body = message
      put_message_req.content_type = "application/#{@format}"
      put_message_req
    end

    def put_message(message)
      log.debug "put_message: #{message}"
      put_message_res = @https.request(put_message_request(message))
      error_handler(put_message_res, "put_message: '#{message}' failed.")
    end

    def target_path
      if !@device_id.nil?
        return "/device_data/#{@device_id}"
      elsif !@recipe_id.nil?
        return "/recipe_data/#{@recipe_id}.#{@format}"
      else
        raise Fluent::ConfigError, "device_id or recipe_id must be specified."
      end
    end

    def get_messages_params
      params = {
        session_key: @session_key,
        from: @from,
        to: @to,
        limit: @limit
      }
      if !@device_id.nil?
        return params
      elsif !@recipe_id.nil?
        return params.merge({keep: @keep, inline: @inline, format: @format})
      else
        raise ConfigError, "device_id or recipe_id must be specified."
      end
    end

    def get_messages_request
      from = Time.parse(@from)
      to = from + @interval
      to = Time.now if to > Time.now
      @to = to.iso8601
      get_messages_req = @uri + target_path
      get_messages_req.query = URI.encode_www_form(get_messages_params)
      log.debug "#{get_messages_req}?#{get_messages_req.query}"
      # currently time window is automatically updated
      #@from = Time.now.iso8601
      @from = @to
      get_messages_req
    end

    def get_messages
      if !valid_session?
        return nil if create_session.nil?
        log.debug "session #{@session_key} created."
      end
      get_messages_res = @https.get(get_messages_request)
      return nil if !error_handler(get_messages_res,"get_messages failed.")
      log.debug "get_message: #{get_messages_res.body}"
      get_messages_res.body
    end
  end
end


text:
Citing
#######################

If you use PyPSA for your research, we would appreciate it if you
would cite the following paper:

* T. Brown, J. Hörsch, D. Schlachtberger, `PyPSA: Python for Power
  System Analysis <https://arxiv.org/abs/1707.09913>`_, 2018,
  `Journal of Open Research Software
  <https://openresearchsoftware.metajnl.com/>`_, 6(1),
  `arXiv:1707.09913 <https://arxiv.org/abs/1707.09913>`_,
  `DOI:10.5334/jors.188 <https://doi.org/10.5334/jors.188>`_

Please use the following BibTeX: ::

   @article{PyPSA,
      author = {T. Brown and J. H\"orsch and D. Schlachtberger},
      title = {{PyPSA: Python for Power System Analysis}},
      journal = {Journal of Open Research Software},
      volume = {6},
      issue = {1},
      number = {4},
      year = {2018},
      eprint = {1707.09913},
      url = {https://doi.org/10.5334/jors.188},
      doi = {10.5334/jors.188}
   }

If you want to cite a specific PyPSA version, each release of PyPSA is
stored on `Zenodo <https://zenodo.org/>`_ with a release-specific DOI.
The release-specific DOIs can be found linked from the overall PyPSA
Zenodo DOI for Version 0.17.1 and onwards:

.. image:: https://zenodo.org/badge/DOI/10.5281/zenodo.3946412.svg
   :target: https://doi.org/10.5281/zenodo.3946412

or from the overall PyPSA Zenodo DOI for Versions up to and including 0.17.0:

.. image:: https://zenodo.org/badge/DOI/10.5281/zenodo.786605.svg
   :target: https://doi.org/10.5281/zenodo.786605


text:
import express from 'express';
import {getPersonalities} from '../controllers/personality';

const router = express.Router();

router.route('/')
  .get(getPersonalities)

export default router


text:
using GraphQL.DataLoader.Tests.Models;
using GraphQL.DataLoader.Tests.Stores;
using Moq;

namespace GraphQL.DataLoader.Tests;

public class DataLoaderExtensionsTests : DataLoaderTestBase
{
    private Mock<IDataLoader<int, User>> GetMockDataLoader()
    {
        var mock = new Mock<IDataLoader<int, User>>();
        mock.Setup(dl => dl.LoadAsync(It.IsAny<int>()))
            .Returns((int key) => new DataLoaderResult<User>(new User() { UserId = key }));
        return mock;
    }

    [Fact]
    public async Task LoadAsync_MultipleKeys_CallsSingularMultipleTimes()
    {
        var mock = GetMockDataLoader();
        var keys = new[] { 1, 2 };
        var users = await DataLoaderExtensions.LoadAsync(mock.Object, keys).GetResultAsync().ConfigureAwait(false);

        users.ShouldNotBeNull();
        users.Length.ShouldBe(keys.Length, "Should return array of same length as number of keys provided");

        users[0].ShouldNotBeNull();
        users[1].ShouldNotBeNull();

        users[0].UserId.ShouldBe(keys[0]);
        users[1].UserId.ShouldBe(keys[1]);

        mock.Verify(x => x.LoadAsync(It.IsAny<int>()), Times.Exactly(keys.Length));
    }

    [Fact]
    public async Task LoadAsync_MultipleKeysAsParams_CallsSingularMultipleTimes()
    {
        var mock = GetMockDataLoader();
        var users = await DataLoaderExtensions.LoadAsync(mock.Object, 1, 2).GetResultAsync().ConfigureAwait(false);

        users.ShouldNotBeNull();
        users.Length.ShouldBe(2, "Should return array of same length as number of keys provided");

        users[0].ShouldNotBeNull();
        users[1].ShouldNotBeNull();

        users[0].UserId.ShouldBe(1);
        users[1].UserId.ShouldBe(2);

        mock.Verify(x => x.LoadAsync(It.IsAny<int>()), Times.Exactly(2));
    }

    [Fact]
    public async Task LoadAsync_MultipleKeys_Works()
    {
        var mock = new Mock<IUsersStore>();
        var users = Fake.Users.Generate(2);

        mock.Setup(store => store.GetUsersByIdAsync(It.IsAny<IEnumerable<int>>(), default))
            .ReturnsAsync(() => users.ToDictionary(x => x.UserId));

        var usersStore = mock.Object;

        User[] users1 = null;
        User[] users2 = null;
        User user1 = null;
        User user2 = null;
        User user3 = null;

        var loader = new BatchDataLoader<int, User>(usersStore.GetUsersByIdAsync);

        // Start async tasks to load by ID
        var result1 = loader.LoadAsync(new int[] { 1, 2 });
        var result2 = loader.LoadAsync(new int[] { 1, 2, 3 });

        // Dispatch loading
        await loader.DispatchAsync().ConfigureAwait(false);
        var task1 = result1.GetResultAsync();
        var task2 = result2.GetResultAsync();

        // Now await tasks
        users1 = await task1.ConfigureAwait(false);
        users1.ShouldNotBeNull();
        user1 = users1[0];
        user2 = users1[1];

        users2 = await task2.ConfigureAwait(false);
        users2.ShouldNotBeNull();
        user3 = users2[2];

        users1.Length.ShouldBe(2, "First task with two keys should return array of two users");
        users2.Length.ShouldBe(3, "Second task with three keys should return array of three users");

        user1.ShouldNotBeNull();
        user2.ShouldNotBeNull();
        user3.ShouldBeNull();

        user1.UserId.ShouldBe(1);
        user2.UserId.ShouldBe(2);

        // This should have been called only once to load in a single batch
        mock.Verify(x => x.GetUsersByIdAsync(new[] { 1, 2, 3 }, default), Times.Once);
    }
}


text:
<?php

namespace TestPlugin\Auth;

use Cake\Auth\DefaultPasswordHasher;

class LegacyPasswordHasher extends DefaultPasswordHasher
{
}