text:
namespace blink {

namespace {

String toString(const Vector<char>& data) {
  if (data.IsEmpty())
    return String("");
  return String(data.data(), data.size());
}

class MockMultipartParserClient final
    : public GarbageCollected<MockMultipartParserClient>,
      public MultipartParser::Client {
 public:
  struct Part {
    Part() = default;
    explicit Part(const HTTPHeaderMap& header_fields)
        : header_fields(header_fields), data_fully_received(false) {}
    HTTPHeaderMap header_fields;
    Vector<char> data;
    bool data_fully_received;
  };
  void PartHeaderFieldsInMultipartReceived(
      const HTTPHeaderMap& header_fields) override {
    parts_.push_back(header_fields);
  }
  void PartDataInMultipartReceived(const char* bytes, size_t size) override {
    parts_.back().data.Append(bytes, base::checked_cast<wtf_size_t>(size));
  }
  void PartDataInMultipartFullyReceived() override {
    parts_.back().data_fully_received = true;
  }
  const Part& GetPart(wtf_size_t part_index) const {
    EXPECT_LT(part_index, NumberOfParts());
    return part_index < NumberOfParts() ? parts_[part_index] : empty_part_;
  }
  wtf_size_t NumberOfParts() const { return parts_.size(); }

 private:
  Part empty_part_;
  Vector<Part> parts_;
};

constexpr char kBytes[] =
    "preamble"
    "\r\n--boundary\r\n\r\n"
    "\r\n--boundary\r\ncontent-type: application/xhtml+xml\r\n\r\n1"
    "\r\n--boundary\t\r\ncontent-type: "
    "text/html\r\n\r\n2\r\n--\r\n--bound--\r\n--\r\n2\r\n"
    "\r\n--boundary \r\ncontent-type: text/plain; charset=iso-8859-1\r\n\r\n333"
    "\r\n--boundary--\t \r\n"
    "epilogue";

TEST(MultipartParserTest, AppendDataInChunks) {
  const size_t sizes[] = {1u, 2u, strlen(kBytes)};

  Vector<char> boundary;
  boundary.Append("boundary", 8u);
  for (const size_t size : sizes) {
    MockMultipartParserClient* client =
        MakeGarbageCollected<MockMultipartParserClient>();
    MultipartParser* parser =
        MakeGarbageCollected<MultipartParser>(boundary, client);

    for (size_t i = 0u, length = strlen(kBytes); i < length; i += size)
      EXPECT_TRUE(parser->AppendData(kBytes + i, std::min(size, length - i)));
    EXPECT_TRUE(parser->Finish()) << " size=" << size;
    EXPECT_EQ(4u, client->NumberOfParts()) << " size=" << size;
    EXPECT_EQ(0u, client->GetPart(0).header_fields.size());
    EXPECT_EQ(0u, client->GetPart(0).data.size());
    EXPECT_TRUE(client->GetPart(0).data_fully_received);
    EXPECT_EQ(1u, client->GetPart(1).header_fields.size());
    EXPECT_EQ("application/xhtml+xml",
              client->GetPart(1).header_fields.Get(http_names::kContentType));
    EXPECT_EQ("1", toString(client->GetPart(1).data));
    EXPECT_TRUE(client->GetPart(1).data_fully_received);
    EXPECT_EQ(1u, client->GetPart(2).header_fields.size());
    EXPECT_EQ("text/html",
              client->GetPart(2).header_fields.Get(http_names::kContentType));
    EXPECT_EQ("2\r\n--\r\n--bound--\r\n--\r\n2\r\n",
              toString(client->GetPart(2).data));
    EXPECT_TRUE(client->GetPart(2).data_fully_received);
    EXPECT_EQ(1u, client->GetPart(3).header_fields.size());
    EXPECT_EQ("text/plain; charset=iso-8859-1",
              client->GetPart(3).header_fields.Get(http_names::kContentType));
    EXPECT_EQ("333", toString(client->GetPart(3).data));
    EXPECT_TRUE(client->GetPart(3).data_fully_received);
  }
}

TEST(MultipartParserTest, Epilogue) {
  constexpr size_t ends[] = {
      0u,   // Non-empty epilogue in the end.
      8u,   // Empty epilogue in the end.
      9u,   // Partial CRLF after close delimiter in the end.
      10u,  // No CRLF after close delimiter in the end.
      12u,  // No transport padding nor CRLF after close delimiter in the end.
      13u,  // Partial close delimiter in the end.
      14u,  // No close delimiter but a delimiter in the end.
      15u   // Partial delimiter in the end.
  };

  Vector<char> boundary;
  boundary.Append("boundary", 8u);
  for (size_t end : ends) {
    MockMultipartParserClient* client =
        MakeGarbageCollected<MockMultipartParserClient>();
    MultipartParser* parser =
        MakeGarbageCollected<MultipartParser>(boundary, client);

    EXPECT_TRUE(parser->AppendData(kBytes, strlen(kBytes) - end));
    EXPECT_EQ(end <= 12u, parser->Finish()) << " end=" << end;
    EXPECT_EQ(4u, client->NumberOfParts()) << " end=" << end;
    EXPECT_EQ(0u, client->GetPart(0).header_fields.size());
    EXPECT_EQ(0u, client->GetPart(0).data.size());
    EXPECT_TRUE(client->GetPart(0).data_fully_received);
    EXPECT_EQ(1u, client->GetPart(1).header_fields.size());
    EXPECT_EQ("application/xhtml+xml",
              client->GetPart(1).header_fields.Get(http_names::kContentType));
    EXPECT_EQ("1", toString(client->GetPart(1).data));
    EXPECT_TRUE(client->GetPart(1).data_fully_received);
    EXPECT_EQ(1u, client->GetPart(2).header_fields.size());
    EXPECT_EQ("text/html",
              client->GetPart(2).header_fields.Get(http_names::kContentType));
    EXPECT_EQ("2\r\n--\r\n--bound--\r\n--\r\n2\r\n",
              toString(client->GetPart(2).data));
    EXPECT_TRUE(client->GetPart(2).data_fully_received);
    EXPECT_EQ(1u, client->GetPart(3).header_fields.size());
    EXPECT_EQ("text/plain; charset=iso-8859-1",
              client->GetPart(3).header_fields.Get(http_names::kContentType));
    switch (end) {
      case 15u:
        EXPECT_EQ("333\r\n--boundar", toString(client->GetPart(3).data));
        EXPECT_FALSE(client->GetPart(3).data_fully_received);
        break;
      default:
        EXPECT_EQ("333", toString(client->GetPart(3).data));
        EXPECT_TRUE(client->GetPart(3).data_fully_received);
        break;
    }
  }
}

TEST(MultipartParserTest, NoEndBoundary) {
  constexpr char bytes[] =
      "--boundary\r\ncontent-type: application/xhtml+xml\r\n\r\n1";

  Vector<char> boundary;
  boundary.Append("boundary", 8u);
  MockMultipartParserClient* client =
      MakeGarbageCollected<MockMultipartParserClient>();
  MultipartParser* parser =
      MakeGarbageCollected<MultipartParser>(boundary, client);

  EXPECT_TRUE(parser->AppendData(bytes, strlen(bytes)));
  EXPECT_FALSE(parser->Finish());  // No close delimiter.
  EXPECT_EQ(1u, client->NumberOfParts());
  EXPECT_EQ(1u, client->GetPart(0).header_fields.size());
  EXPECT_EQ("application/xhtml+xml",
            client->GetPart(0).header_fields.Get(http_names::kContentType));
  EXPECT_EQ("1", toString(client->GetPart(0).data));
  EXPECT_FALSE(client->GetPart(0).data_fully_received);
}

TEST(MultipartParserTest, NoStartBoundary) {
  constexpr char bytes[] =
      "content-type: application/xhtml+xml\r\n\r\n1\r\n--boundary--\r\n";

  Vector<char> boundary;
  boundary.Append("boundary", 8u);
  MockMultipartParserClient* client =
      MakeGarbageCollected<MockMultipartParserClient>();
  MultipartParser* parser =
      MakeGarbageCollected<MultipartParser>(boundary, client);

  EXPECT_FALSE(parser->AppendData(
      bytes, strlen(bytes)));  // Close delimiter before delimiter.
  EXPECT_EQ(0u, client->NumberOfParts());
}

TEST(MultipartParserTest, NoStartNorEndBoundary) {
  constexpr char bytes[] = "content-type: application/xhtml+xml\r\n\r\n1";

  Vector<char> boundary;
  boundary.Append("boundary", 8u);
  MockMultipartParserClient* client =
      MakeGarbageCollected<MockMultipartParserClient>();
  MultipartParser* parser =
      MakeGarbageCollected<MultipartParser>(boundary, client);

  EXPECT_TRUE(parser->AppendData(bytes, strlen(bytes)));  // Valid preamble.
  EXPECT_FALSE(parser->Finish());                         // No parts.
  EXPECT_EQ(0u, client->NumberOfParts());
}

constexpr size_t kStarts[] = {
    0u,   // Non-empty preamble in the beginning.
    8u,   // Empty preamble in the beginning.
    9u,   // Truncated delimiter in the beginning.
    10u,  // No preamble in the beginning.
    11u   // Truncated dash boundary in the beginning.
};

TEST(MultipartParserTest, Preamble) {
  Vector<char> boundary;
  boundary.Append("boundary", 8u);
  for (const size_t start : kStarts) {
    MockMultipartParserClient* client =
        MakeGarbageCollected<MockMultipartParserClient>();
    MultipartParser* parser =
        MakeGarbageCollected<MultipartParser>(boundary, client);

    EXPECT_TRUE(parser->AppendData(kBytes + start, strlen(kBytes + start)));
    EXPECT_TRUE(parser->Finish());
    switch (start) {
      case 9u:
      case 11u:
        EXPECT_EQ(3u, client->NumberOfParts()) << " start=" << start;
        EXPECT_EQ(1u, client->GetPart(0).header_fields.size());
        EXPECT_EQ("application/xhtml+xml", client->GetPart(0).header_fields.Get(
                                               http_names::kContentType));
        EXPECT_EQ("1", toString(client->GetPart(0).data));
        EXPECT_TRUE(client->GetPart(0).data_fully_received);
        EXPECT_EQ(1u, client->GetPart(1).header_fields.size());
        EXPECT_EQ("text/html", client->GetPart(1).header_fields.Get(
                                   http_names::kContentType));
        EXPECT_EQ("2\r\n--\r\n--bound--\r\n--\r\n2\r\n",
                  toString(client->GetPart(1).data));
        EXPECT_TRUE(client->GetPart(1).data_fully_received);
        EXPECT_EQ(1u, client->GetPart(2).header_fields.size());
        EXPECT_EQ(
            "text/plain; charset=iso-8859-1",
            client->GetPart(2).header_fields.Get(http_names::kContentType));
        EXPECT_EQ("333", toString(client->GetPart(2).data));
        EXPECT_TRUE(client->GetPart(2).data_fully_received);
        break;
      default:
        EXPECT_EQ(4u, client->NumberOfParts()) << " start=" << start;
        EXPECT_EQ(0u, client->GetPart(0).header_fields.size());
        EXPECT_EQ(0u, client->GetPart(0).data.size());
        EXPECT_TRUE(client->GetPart(0).data_fully_received);
        EXPECT_EQ(1u, client->GetPart(1).header_fields.size());
        EXPECT_EQ("application/xhtml+xml", client->GetPart(1).header_fields.Get(
                                               http_names::kContentType));
        EXPECT_EQ("1", toString(client->GetPart(1).data));
        EXPECT_TRUE(client->GetPart(1).data_fully_received);
        EXPECT_EQ(1u, client->GetPart(2).header_fields.size());
        EXPECT_EQ("text/html", client->GetPart(2).header_fields.Get(
                                   http_names::kContentType));
        EXPECT_EQ("2\r\n--\r\n--bound--\r\n--\r\n2\r\n",
                  toString(client->GetPart(2).data));
        EXPECT_TRUE(client->GetPart(2).data_fully_received);
        EXPECT_EQ(1u, client->GetPart(3).header_fields.size());
        EXPECT_EQ(
            "text/plain; charset=iso-8859-1",
            client->GetPart(3).header_fields.Get(http_names::kContentType));
        EXPECT_EQ("333", toString(client->GetPart(3).data));
        EXPECT_TRUE(client->GetPart(3).data_fully_received);
        break;
    }
  }
}

TEST(MultipartParserTest, PreambleWithMalformedBoundary) {
  Vector<char> boundary;
  boundary.Append("--boundary", 10u);
  for (const size_t start : kStarts) {
    MockMultipartParserClient* client =
        MakeGarbageCollected<MockMultipartParserClient>();
    MultipartParser* parser =
        MakeGarbageCollected<MultipartParser>(boundary, client);

    EXPECT_TRUE(parser->AppendData(kBytes + start,
                                   strlen(kBytes + start)));  // Valid preamble.
    EXPECT_FALSE(parser->Finish());                           // No parts.
    EXPECT_EQ(0u, client->NumberOfParts());
  }
}

}  // namespace

}  // namespace blink


text:
package net.mgsx.game.plugins.btree.tools;

import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ai.btree.BehaviorTree;
import com.badlogic.gdx.ai.btree.utils.BehaviorTreeLibraryManager;
import com.badlogic.gdx.ai.btree.utils.BehaviorTreeParser;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.SerializationException;

import net.mgsx.game.core.EditorScreen;
import net.mgsx.game.core.annotations.Editable;
import net.mgsx.game.core.helpers.NativeService;
import net.mgsx.game.core.helpers.NativeService.DefaultCallback;
import net.mgsx.game.core.tools.Tool;
import net.mgsx.game.plugins.btree.BTreeModel;
import net.mgsx.game.plugins.btree.EntityBlackboard;
import net.mgsx.game.plugins.editor.systems.SelectionSystem;

@Editable
public class BTreeTool extends Tool
{
	public BTreeTool(EditorScreen editor) {
		super("Behavor Tree", editor);
	}
	@Editable
	public void load(){
		NativeService.instance.openLoadDialog(new DefaultCallback() {
			@Override
			public void selected(FileHandle file) {
				load(editor, file);
			}
			@Override
			public boolean match(FileHandle file) {
				return file.extension().equals("btree");
			}
			@Override
			public String description() {
				return "BehaviorTree files (btree)";
			}
		});
	}

	@Editable
	public void empty(){
		NativeService.instance.openSaveDialog(new DefaultCallback() {
			@Override
			public void selected(FileHandle file) {
				file.writeString("success", false);
				load(editor, file);
			}
			@Override
			public boolean match(FileHandle file) {
				return file.extension().equals("btree");
			}
			@Override
			public String description() {
				return "BehaviorTree files (btree)";
			}
		});
	}

	public static void load(EditorScreen editor, FileHandle file){
		Entity entity = editor.entityEngine.getSystem(SelectionSystem.class).currentEntity();

		if(!editor.assets.isLoaded(file.path())){
			if(file.extension().equals("btree")){
				try{
					new BehaviorTreeParser<EntityBlackboard>(BehaviorTreeParser.DEBUG_LOW).parse(file, null);
				}catch(SerializationException e){
					// TODO raise UI Error ...
					Gdx.app.error("BTree", "Error parsing file", e);
					return;
				}
			}

			editor.loadAssetNow(file.path(), BehaviorTree.class);
		}
		BTreeModel model = BTreeModel.components.get(entity);
		if(model == null){
			model = editor.entityEngine.createComponent(BTreeModel.class);
		}

		model.libraryName = file.path();
		model.tree = BehaviorTreeLibraryManager.getInstance().createBehaviorTree(file.path());

		entity.add(model);
	}

}

redpajama_set_name: RedPajamaGithub


text:
title: Function Length
localeTitle: Длина функции
---
## Длина функции

Свойство `length` на объекте функции содержит количество аргументов, ожидаемых функцией при вызове.

```javascript
function noArgs() { }

 function oneArg(a) { }

 console.log(noArgs.length); // 0

 console.log(oneArg.length); // 1
```

### Синтаксис ES2015

ES2015 или ES6, как его обычно называют, вводили оператор останова и параметры функции по умолчанию. Оба эти дополнения изменяют способ работы с `length` .

Если в объявлении функции используется либо оператор останова, либо параметры по умолчанию, свойство `length` будет включать только количество аргументов перед оператором отдыха или параметр по умолчанию.

```javascript
function withRest(...args) { }

 function withArgsAndRest(a, b, ...args) { }

 function withDefaults(a, b = 'I am the default') { }

 console.log(withRest.length); // 0

 console.log(withArgsAndRest.length); // 2

 console.log(withDefaults.length); // 1
```

Более подробную информацию о `Function.length` можно найти [в Документах MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) от [Mozilla](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) .


text:
package com.hurence.logisland.record;

/**
 * Set of allowed values for a field type
 * <p>
 * https://avro.apache.org/docs/1.8.1/spec.html#schema_primitive
 */
public enum FieldType {

    NULL,
    STRING,
    INT,
    LONG,
    ARRAY,
    FLOAT,
    DOUBLE,
    BYTES,
    RECORD,
    MAP,
    ENUM,
    BOOLEAN,
    UNION;

    public String toString() {
        return name;
    }
    private String name;

    FieldType() {
        this.name = this.name().toLowerCase();
    }

    public String getName() {
        return name;
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Timers;
//-----------------------------------------------------------------------------
namespace Sand.Fhem.Basics.Collections
{
    public class FhemObjectsRepository : IEnumerable<FhemObject>, INotifyCollectionChanged
    {
        //---------------------------------------------------------------------
        #region Fields

        private FhemClient  m_fhemClient;

        private FhemObjectsCollection  m_fhemObjectsCollection = new FhemObjectsCollection();

        private Timer  m_updateTimer;

        private double  m_updateTimerInterval = 5000;

        //-- Fields
        #endregion
        //---------------------------------------------------------------------
        #region Properties

        /// <summary>
        /// Gets the duration of the last repository update. Just nice to know.
        /// </summary>
        public TimeSpan LastUpdateDuration { get; private set; }

        /// <summary>
        /// Gets or sets the update intervall.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">
        /// The update interval may not be smaller than 2000ms.
        /// </exception>
        public double UpdateInterval
        {
            get { return m_updateTimerInterval;  }
            set
            {
                //-- Do nothing when the value has not changed
                if( value == m_updateTimerInterval ) { return; }

                if( value < 2000 )
                {
                    throw new ArgumentOutOfRangeException( "The update interval may not be smaller than 2000ms!" );
                }

                //-- Update the timer interval
                m_updateTimerInterval = value;

                //-- Reset the update timer
                this.ResetUpdateTimer( m_updateTimerInterval );
            }
        }

        //-- Properties
        #endregion
        //---------------------------------------------------------------------
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the FhemObjectsRepository class.
        /// </summary>
        /// <param name="a_fhemClient">
        /// The Fhem client for keeping the repository up to date.
        /// </param>
        /// <remarks>
        /// The constructor is private to force the usage of the static
        /// 'Create' method (long lasting operations do not belong into a
        /// constructor ;).
        /// </remarks>
        public FhemObjectsRepository( FhemClient a_fhemClient )
        {
            //-- Initialize fields
            m_fhemClient = a_fhemClient;

            //-- Start the update timer with a very small interval to force an
            //-- immediate update. After elapsing, the timer will be configured
            //-- anew for standard use
            m_updateTimer = new Timer( 20 );
            m_updateTimer.AutoReset = false; //-- The starter event handler should be called only once
            m_updateTimer.Elapsed += m_updateTimer_Elapsed_StarterHandler;
            m_updateTimer.Start();
        }

        //-- Constructors
        #endregion
        //---------------------------------------------------------------------
        #region Event Handlers

        private void m_updateTimer_Elapsed( object sender, ElapsedEventArgs e )
        {
            //-- Keep the start timestamp in mind
            var startDateTime = DateTime.Now;

            //-- Get all available Fhem objects
            var currentFhemObjects = m_fhemClient.GetFhemObjects();

            //-- Determine old Fhem objects
            ////var oldFhemObjects = new List<FhemObject>();
            ////foreach( FhemObject tmpFhemObject in m_fhemObjectsByNr.Values )
            ////{
            ////    if( !currentFhemObjects.ContainsKey( tmpFhemObject.ID ) )
            ////    {
            ////        oldFhemObjects.Add( tmpFhemObject );
            ////    }
            ////}

            ////-- Determine new Fhem objects
            //var newFhemObjects = new List<FhemObject>();
            //foreach( FhemObject currentFhemObject in currentFhemObjects )
            //{
            //    if( !m_fhemObjectsByNr.ContainsKey( currentFhemObject.ID ) )
            //    {
            //        newFhemObjects.Add( currentFhemObject );
            //    }
            //}

            ////-- Raise the 'CollectionChanged' event
            //this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, newFhemObjects, oldFhemObjects ) );

            //-- Calculate the update duration
            this.LastUpdateDuration = DateTime.Now - startDateTime;
        }

        private void m_updateTimer_Elapsed_StarterHandler( object sender, ElapsedEventArgs e )
        {
            //-- Get all available Fhem objects
            m_fhemObjectsCollection = m_fhemClient.GetFhemObjects();

            //-- Raise the 'CollectionChanged' event
            this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, m_fhemObjectsCollection ) );

            //-- Reset the update timer for regular use
            this.ResetUpdateTimer( m_updateTimerInterval );
        }

        //-- Event Handlers
        #endregion
        //---------------------------------------------------------------------
        #region IEnumerable

        public IEnumerator GetEnumerator()
        {
            return m_fhemObjectsCollection.GetEnumerator();
        }

        IEnumerator<FhemObject> IEnumerable<FhemObject>.GetEnumerator()
        {
            return ( (IEnumerable<FhemObject>) m_fhemObjectsCollection ).GetEnumerator();
        }

        //-- IEnumerable
        #endregion
        //---------------------------------------------------------------------
        #region INotifyCollectionChanged

        public event NotifyCollectionChangedEventHandler CollectionChanged;

        //-- INotifyCollectionChanged
        #endregion
        //---------------------------------------------------------------------
        #region Methods

        /// <summary>
        /// Resets the update timer with the given update interval.
        /// </summary>
        /// <param name="a_updateInterval">
        /// The update interval.
        /// </param>
        private void ResetUpdateTimer( double a_updateInterval )
        {
            if( m_updateTimer != null )
            {
                //-- Stop an existing timer
                m_updateTimer.Stop();
                m_updateTimer.Elapsed -= m_updateTimer_Elapsed;
            }

            //-- Create a new timer with the new interval
            m_updateTimer = new Timer( a_updateInterval );
            m_updateTimer.Elapsed += m_updateTimer_Elapsed;
            m_updateTimer.Start();
        }

        //-- Methods
        #endregion
        //---------------------------------------------------------------------
    }
}
//-----------------------------------------------------------------------------


text:
// Copyright © 2018 Wave Engine S.L. All rights reserved. Use is subject to license terms.

#region Usings Statements
using Leap;
using System;
using System.Runtime.Serialization;
using WaveEngine.Common.Graphics;
using WaveEngine.Common.Math;
using WaveEngine.Framework;
using WaveEngine.Framework.Graphics;
using WaveEngine.Framework.Services;
#endregion

namespace WaveEngine.LeapMotion.Drawables
{
    /// <summary>
    /// A basic drawable3D to draw the hands capture with leap motion.
    /// </summary>
    [DataContract(Namespace = "WaveEngine.LeapMotion.Drawables")]
    public class LeapMotionDebug : Drawable3D
    {
        /// <summary>
        /// Reference to leap motion service.
        /// </summary>
        private LeapMotionService leapService;

        /// <summary>
        /// The linebatch used to draw lines
        /// </summary>
        private LineBatch3D lineBatch;

        /// <summary>
        /// The transform
        /// </summary>
        [RequiredComponent]
        private Transform3D transform = null;

        #region Initialize

        /// <summary>
        /// Default values
        /// </summary>
        protected override void DefaultValues()
        {
            base.DefaultValues();
        }

        /// <summary>
        /// Initialize this instance.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            this.leapService = WaveServices.GetService<LeapMotionService>();

            if (this.leapService == null)
            {
                Console.WriteLine("You need to register the LeapMotion service.");
            }

            if (!this.leapService.IsReady)
            {
                Console.WriteLine("You need to call to start method before.");
            }

            this.lineBatch = this.RenderManager.FindLayer(DefaultLayers.Opaque).LineBatch3D;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Draw the left and right hands capture with leap motion.
        /// </summary>
        /// <param name="gameTime">the current game time.</param>
        public override void Draw(TimeSpan gameTime)
        {
            if (this.leapService != null && this.leapService.IsReady)
            {
                if (this.leapService.CurrentFeatures.HasFlag(LeapFeatures.Hands))
                {
                    this.DrawHand(this.leapService.RightHand);
                    this.DrawHand(this.leapService.LeftHand);
                }
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Draw debug lines of each hand.
        /// </summary>
        /// <param name="hand">the hand to draw.</param>
        private void DrawHand(Hand hand)
        {
            if (hand != null && hand.IsValid)
            {
                Color red = Color.Red;
                Color green = Color.Green;
                Color yellow = Color.Yellow;
                Color white = Color.White;

                // Plam
                var plamPosition = hand.PalmPosition.ToPositionVector3();
                this.DrawLine(plamPosition, plamPosition + (hand.PalmNormal.ToPositionVector3() * 40), green);
                this.DrawLine(plamPosition, plamPosition + (hand.Direction.ToPositionVector3() * 40), red);

                // Arm
                this.DrawLine(hand.Arm.ElbowPosition.ToPositionVector3(), hand.Arm.WristPosition.ToPositionVector3(), white);

                // Fingers
                foreach (Finger finger in hand.Fingers)
                {
                    // Get finger bones
                    Leap.Bone bone;
                    foreach (Leap.Bone.BoneType boneType in (Leap.Bone.BoneType[])Enum.GetValues(typeof(Leap.Bone.BoneType)))
                    {
                        bone = finger.Bone(boneType);
                        this.DrawLine(bone.PrevJoint.ToPositionVector3(), bone.NextJoint.ToPositionVector3(), yellow);
                    }
                }
            }
        }

        /// <summary>
        /// Draw debug line
        /// </summary>
        /// <param name="start">Start line</param>
        /// <param name="end">End line</param>
        /// <param name="color">The color of the line</param>
        private void DrawLine(Vector3 start, Vector3 end, Color color)
        {
            var worldTransform = this.transform.WorldTransform;

            Vector3.Transform(ref start, ref worldTransform, out start);
            Vector3.Transform(ref end, ref worldTransform, out end);
            this.lineBatch.DrawLine(ref start, ref end, ref color);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
        }

        #endregion
    }
}


text:
package com.opengamma.analytics.math.curve;

import java.util.HashMap;
import java.util.Map;

/**
 * Contains methods for performing shifts on {@link Curve} without needing to know the exact type of the curve.
 */
public class CurveShiftFunctionFactory {
  /** Shift function for {@link ConstantDoublesCurve} */
  public static final ConstantCurveShiftFunction CONSTANT = new ConstantCurveShiftFunction();
  /** Shift function for {@link FunctionalDoublesCurve} */
  public static final FunctionalCurveShiftFunction FUNCTIONAL = new FunctionalCurveShiftFunction();
  /** Shift function for {@link InterpolatedDoublesCurve} */
  public static final InterpolatedCurveShiftFunction INTERPOLATED = new InterpolatedCurveShiftFunction();
  /** Shift function for {@link SpreadDoublesCurve} */
  public static final SpreadCurveShiftFunction SPREAD = new SpreadCurveShiftFunction();
  private static final Map<Class<?>, CurveShiftFunction<?>> s_instances = new HashMap<>();

  static {
    s_instances.put(ConstantCurveShiftFunction.class, CONSTANT);
    s_instances.put(FunctionalCurveShiftFunction.class, FUNCTIONAL);
    s_instances.put(InterpolatedCurveShiftFunction.class, INTERPOLATED);
    s_instances.put(SpreadCurveShiftFunction.class, SPREAD);
  }

  /**
   * Gets the function for a class type.
   * @param clazz The class
   * @return The function
   * @throws IllegalArgumentException If the function is not one of the static instances
   */
  public static CurveShiftFunction<?> getFunction(final Class<?> clazz) {
    final CurveShiftFunction<?> f = s_instances.get(clazz);
    if (f == null) {
      throw new IllegalArgumentException("Could not get function for " + clazz.getName());
    }
    return f;
  }

  /**
   * For a curve Curve<Double, Double>, return a parallel-shifted curve.
   * @param curve The original curve
   * @param shift The shift
   * @return A shifted curve with automatically-generated name
   * @throws IllegalArgumentException If the curve type is not constant, functional, interpolated, nodal or spread
   */
  public static DoublesCurve getShiftedCurve(final Curve<Double, Double> curve, final double shift) {
    if (curve instanceof ConstantDoublesCurve) {
      return CONSTANT.evaluate((ConstantDoublesCurve) curve, shift);
    }
    if (curve instanceof FunctionalDoublesCurve) {
      return FUNCTIONAL.evaluate((FunctionalDoublesCurve) curve, shift);
    }
    if (curve instanceof InterpolatedDoublesCurve) {
      return INTERPOLATED.evaluate((InterpolatedDoublesCurve) curve, shift);
    }
    if (curve instanceof SpreadDoublesCurve) {
      return SPREAD.evaluate((SpreadDoublesCurve) curve, shift);
    }
    throw new IllegalArgumentException("Do not have a curve shift function for curve " + curve.getClass());
  }

  /**
   * For a curve Curve<Double, Double>, return a curve shifted at one point.
   * @param curve The original curve
   * @param x The x value of the shift
   * @param shift The shift
   * @return A shifted curve with automatically-generated name
   * @throws IllegalArgumentException If the curve type is not constant, functional, interpolated, nodal or spread
   */
  public static DoublesCurve getShiftedCurve(final Curve<Double, Double> curve, final double x, final double shift) {
    if (curve instanceof ConstantDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a constant curve");
    }
    if (curve instanceof FunctionalDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a functional curve");
    }
    if (curve instanceof InterpolatedDoublesCurve) {
      return INTERPOLATED.evaluate((InterpolatedDoublesCurve) curve, x, shift);
    }
    if (curve instanceof SpreadDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a spread curve");
    }
    throw new IllegalArgumentException("Do not have a curve shift function for curve " + curve.getClass());
  }

  /**
   * For a curve Curve<Double, Double>, return a parallel-shifted curve.
   * @param curve The original curve
   * @param x An array of x values to shift
   * @param y The shifts
   * @return A shifted curve with automatically-generated name
   * @throws IllegalArgumentException If the curve type is not constant, functional, interpolated, nodal or spread
   */
  public static DoublesCurve getShiftedCurve(final Curve<Double, Double> curve, final double[] x, final double[] y) {
    if (curve instanceof ConstantDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a constant curve");
    }
    if (curve instanceof FunctionalDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a functional curve");
    }
    if (curve instanceof InterpolatedDoublesCurve) {
      return INTERPOLATED.evaluate((InterpolatedDoublesCurve) curve, x, y);
    }
    if (curve instanceof SpreadDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a spread curve");
    }
    throw new IllegalArgumentException("Do not have a curve shift function for curve " + curve.getClass());
  }

  /**
   * For a curve Curve<Double, Double>, return a parallel-shifted curve.
   * @param curve The original curve
   * @param shift The shift
   * @param newName The name of the shifted curve
   * @return A shifted curve
   * @throws IllegalArgumentException If the curve type is not constant, functional, interpolated, nodal or spread
   */
  public static DoublesCurve getShiftedCurve(final Curve<Double, Double> curve, final double shift, final String newName) {
    if (curve instanceof ConstantDoublesCurve) {
      return CONSTANT.evaluate((ConstantDoublesCurve) curve, shift, newName);
    }
    if (curve instanceof FunctionalDoublesCurve) {
      return FUNCTIONAL.evaluate((FunctionalDoublesCurve) curve, shift, newName);
    }
    if (curve instanceof InterpolatedDoublesCurve) {
      return INTERPOLATED.evaluate((InterpolatedDoublesCurve) curve, shift, newName);
    }
    if (curve instanceof SpreadDoublesCurve) {
      return SPREAD.evaluate((SpreadDoublesCurve) curve, shift, newName);
    }
    throw new IllegalArgumentException("Do not have a curve shift function for curve " + curve.getClass());
  }

  /**
   * For a curve Curve<Double, Double>, return a curve shifted at one point.
   * @param curve The original curve
   * @param x The x value of the shift
   * @param shift The shift
   * @param newName The name of the shifted curve
   * @return A shifted curve
   * @throws IllegalArgumentException If the curve type is not constant, functional, interpolated, nodal or spread
   */
  public static DoublesCurve getShiftedCurve(final Curve<Double, Double> curve, final double x, final double shift, final String newName) {
    if (curve instanceof ConstantDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a constant curve");
    }
    if (curve instanceof FunctionalDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a functional curve");
    }
    if (curve instanceof InterpolatedDoublesCurve) {
      return INTERPOLATED.evaluate((InterpolatedDoublesCurve) curve, x, shift, newName);
    }
    if (curve instanceof SpreadDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a spread curve");
    }
    throw new IllegalArgumentException("Do not have a curve shift function for curve " + curve.getClass());
  }

  /**
   * For a curve Curve<Double, Double>, return a parallel-shifted curve.
   * @param curve The original curve
   * @param x An array of x values to shift
   * @param y The shifts
   * @param newName The name of the shifted curve
   * @return A shifted curve
   * @throws IllegalArgumentException If the curve type is not constant, functional, interpolated, nodal or spread
   */
  public static DoublesCurve getShiftedCurve(final Curve<Double, Double> curve, final double[] x, final double[] y, final String newName) {
    if (curve instanceof ConstantDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a constant curve");
    }
    if (curve instanceof FunctionalDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a functional curve");
    }
    if (curve instanceof InterpolatedDoublesCurve) {
      return INTERPOLATED.evaluate((InterpolatedDoublesCurve) curve, x, y, newName);
    }
    if (curve instanceof SpreadDoublesCurve) {
      throw new UnsupportedOperationException("Cannot shift a single point on a spread curve");
    }
    throw new IllegalArgumentException("Do not have a curve shift function for curve " + curve.getClass());
  }
}


text:
from __future__ import unicode_literals

import os
import re

from .common import InfoExtractor
from ..compat import (
    compat_urllib_parse,
    compat_urllib_parse_urlparse,
    compat_urllib_request,
)
from ..utils import (
    str_to_int,
)
from ..aes import (
    aes_decrypt_text
)

class PornHubIE(InfoExtractor):
    _VALID_URL = r'https?://(?:www\.)?pornhub\.com/view_video\.php\?viewkey=(?P<id>[0-9a-f]+)'
    _TEST = {
        'url': 'http://www.pornhub.com/view_video.php?viewkey=648719015',
        'md5': '882f488fa1f0026f023f33576004a2ed',
        'info_dict': {
            'id': '648719015',
            'ext': 'mp4',
            "uploader": "Babes",
            "title": "Seductive Indian beauty strips down and fingers her pink pussy",
            "age_limit": 18
        }
    }

    def _extract_count(self, pattern, webpage, name):
        count = self._html_search_regex(pattern, webpage, '%s count' % name, fatal=False)
        if count:
            count = str_to_int(count)
        return count

    def _real_extract(self, url):
        video_id = self._match_id(url)

        req = compat_urllib_request.Request(url)
        req.add_header('Cookie', 'age_verified=1')
        webpage = self._download_webpage(req, video_id)

        video_title = self._html_search_regex(r'
]+>([^<]+)', webpage, 'title')
        video_uploader = self._html_search_regex(
            r'(?s)From: .+?<(?:a href="/users/|a href="/channels/|]+>(.+?)<',
            webpage, 'uploader', fatal=False)
        thumbnail = self._html_search_regex(r'"image_url":"([^"]+)', webpage, 'thumbnail', fatal=False)
        if thumbnail:
            thumbnail = compat_urllib_parse.unquote(thumbnail)

        view_count = self._extract_count(r'([\d,\.]+) views', webpage, 'view')
        like_count = self._extract_count(r'([\d,\.]+)', webpage, 'like')
        dislike_count = self._extract_count(r'([\d,\.]+)', webpage, 'dislike')
        comment_count = self._extract_count(
            r'All comments \(<var class="videoCommentCount">([\d,\.]+)</var>', webpage, 'comment')

        video_urls = list(map(compat_urllib_parse.unquote, re.findall(r'"quality_[0-9]{3}p":"([^"]+)', webpage)))
        if webpage.find('"encrypted":true') != -1:
            password = compat_urllib_parse.unquote_plus(self._html_search_regex(r'"video_title":"([^"]+)', webpage, 'password'))
            video_urls = list(map(lambda s: aes_decrypt_text(s, password, 32).decode('utf-8'), video_urls))

        formats = []
        for video_url in video_urls:
            path = compat_urllib_parse_urlparse(video_url).path
            extension = os.path.splitext(path)[1][1:]
            format = path.split('/')[5].split('_')[:2]
            format = "-".join(format)

            m = re.match(r'^(?P<height>[0-9]+)P-(?P<tbr>[0-9]+)K$', format)
            if m is None:
                height = None
                tbr = None
            else:
                height = int(m.group('height'))
                tbr = int(m.group('tbr'))

            formats.append({
                'url': video_url,
                'ext': extension,
                'format': format,
                'format_id': format,
                'tbr': tbr,
                'height': height,
            })
        self._sort_formats(formats)

        return {
            'id': video_id,
            'uploader': video_uploader,
            'title': video_title,
            'thumbnail': thumbnail,
            'view_count': view_count,
            'like_count': like_count,
            'dislike_count': dislike_count,
            'comment_count': comment_count,
            'formats': formats,
            'age_limit': 18,
        }


text:
package mblog.web.controller.admin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import mblog.core.data.Tag;
import mblog.core.persist.service.TagService;
import mblog.web.controller.BaseController;
import mtons.modules.pojos.Data;
import mtons.modules.pojos.Paging;

/**
 * @author langhsu
 *
 */
@Controller("mng_tag_ctl")
@RequestMapping("/admin/tags")
public class TagsController extends BaseController {
	@Autowired
	private TagService tagService;

	@RequestMapping("/list")
	public String list(Integer pn, String key, String order, ModelMap model) {
		Paging page = wrapPage(pn);
		tagService.paging(page, key, order);
		model.put("page", page);
		model.put("key", key);
		model.put("order", order);
		return "/admin/tags/list";
	}

	@RequestMapping("/view")
	public String view(Long id, ModelMap model) {
		Tag tag = tagService.get(id);
		model.put("view", tag);
		return "/admin/tags/view";
	}

	@RequestMapping("/update")
	public String update(Tag tag) {
		if (tag != null) {
			tagService.update(tag);
		}
		return "redirect:/admin/tags/list";
	}

	@RequestMapping("/featured")
	public @ResponseBody Data featured(Long id, int status) {
		Data data = Data.failure("操作失败");
		if (id != null) {
			try {
				tagService.updateFeatured(id, status);
				data = Data.success("操作成功", Data.NOOP);
			} catch (Exception e) {
				data = Data.failure(e.getMessage());
			}
		}
		return data;
	}

	@RequestMapping("/lock")
	public @ResponseBody Data lock(Long id, int status) {
		Data data = Data.failure("操作失败");
		if (id != null) {
			try {
				tagService.updateLock(id, status);
				data = Data.success("操作成功", Data.NOOP);
			} catch (Exception e) {
				data = Data.failure(e.getMessage());
			}
		}
		return data;
	}

	@RequestMapping("/delete")
	public @ResponseBody Data delete(Long id) {
		Data data = Data.failure("操作失败");
		if (id != null) {
			try {
				tagService.delete(id);
				data = Data.success("操作成功", Data.NOOP);
			} catch (Exception e) {
				data = Data.failure(e.getMessage());
			}
		}
		return data;
	}

}


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

import java.net.InetSocketAddress;
import java.util.List;
import org.apache.yetus.audience.InterfaceAudience;

import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.ServerName;

/**
 * Abstraction that allows different modules in RegionServer to update/get the favored nodes
 * information for regions.
 */
@InterfaceAudience.Private
public interface FavoredNodesForRegion {
  /**
   * Used to update the favored nodes mapping when required.
   */
  void updateRegionFavoredNodesMapping(String encodedRegionName, List<ServerName> favoredNodes);

  /**
   * Get the favored nodes mapping for this region. Used when the HDFS create API is invoked to pass
   * in favored nodes hints for new region files.
   * @return array containing the favored nodes' InetSocketAddresses
   */
  InetSocketAddress[] getFavoredNodesForRegion(String encodedRegionName);
}


text:
function Character(_character) {
    Component.call(this, _character);
    try {
        this.setSpeed(_character.speed);
        this.setSpeedJump(_character.speedJump);
        this.setMaxHealth(_character.maxHealth);
        this.setHealth(_character.health); //percentage of maxHealth (0 to 100)
        this.setDamage(_character.damage);
        this.setAnimation(_character.animation);
        this.healBar;
        this.move = {
            right: false,
            left: false,
            up: false,
            down: false
        };
        this.isDead = false;
    } catch (e) {
        throw (e);
    }
    this.start();
}

Character.prototype = Object.create(Component.prototype);

Character.prototype.setMaxHealth = function (value = 100) {
    this.maxHealth = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.setSpeed = function (value = 100) {
    this.speed = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.setSpeedJump = function (value = 100) {
    this.speedJump = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.setHealth = function (value = 100) {
    this.health = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.setDamage = function (value = 0) {
    this.damage = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.kill = function () {
    this.healBar.maxHealth.destroy();
    this.healBar.health.destroy();
    this.healBar.damage.destroy();
    this.figure.destroy();
    this.isDead = true;
    delete this.healBar;
};

Character.prototype.receiveDamage = function (damage) {
    this.damage = this.damage + damage;
    this.health = ((this.maxHealth - this.damage) * 100) / this.maxHealth;
    this.healBar.health.w = 96 * this.health / 100; //96 is the initial width of the healbar;
    if ((96 * this.health / 100) <= 0) {
        this.healBar.health.color('rgba (0,0,0,0)');
        this.kill();
    }
};

Character.prototype.setAnimation = function (value) {
    this.animation = value;
};

Character.prototype.start = function () {
    this.healBar = new HealBar(this);
    this.isDead = false;
    this.figure = Crafty.e(this.reference + ', 2D, Canvas' /*, Color,*/ + ', Gravity, Collision, balotelliRun, SpriteAnimation')
        .attr({
            x: this.posX,
            y: this.posY,
            w: this.width,
            h: this.height
        })
        /*.color(this.color)*/
        .gravity('Floor')
        .collision()
        .reel('running', 500, [
            [0, 0],
            [1, 0],
            [2, 0],
            [3, 0],
            [4, 0],
            [5, 0],
            [6, 0],
            [7, 0],
            [8, 0],
            [9, 0]
        ]) // setup animation
        .animate('running', -1).bind('KeyDown', (e) => {
            // Default movement booleans to false
            this.move.right = this.move.left = this.move.down = this.move.up = false;
            // If keys are down, set the direction
            if (e.key == Crafty.keys.RIGHT_ARROW || e.key == Crafty.keys.D) {
                this.move.right = true;
            }
            if (e.key == Crafty.keys.LEFT_ARROW || e.key == Crafty.keys.A) {
                this.move.left = true;
            }
            if (e.keyCode === Crafty.keys.UA) this.move.up = true;
            if (e.keyCode === Crafty.keys.DA) this.move.down = true;
        })
        .bind('Moved', (from) => {
            this.posX = this.figure.x;
            this.posY = this.figure.y;
            this.healBar.maxHealth.x = this.figure.x - this.figure.w / 2;
            this.healBar.maxHealth.y = this.figure.y - this.figure.h + 30;
            this.healBar.health.x = this.healBar.maxHealth.x + 2;
            this.healBar.health.y = this.healBar.maxHealth.y + 2;
            this.healBar.damage.x = this.healBar.maxHealth.x + 2;
            this.healBar.damage.y = this.healBar.maxHealth.y + 2;
            if (this.figure.hit("limitLeft")) {
                this.figure.attr({
                    x: 1,
                    y: this.figure.y
                });
            }
            if (this.figure.hit("limitRight")) {
                this.figure.attr({
                    x: 719,
                    y: this.figure.y
                });
            }
            if (this.figure.hit("LimitTop")) {
                this.figure.attr({
                    x: this.figure.x,
                    y: -1
                });
            }
            if (this.move.right) {
                this.figure.unflip("X");
            }
            if (this.move.left) {
                this.figure.flip("X");
            }
        });
};


text:
@interface TGScanView : UIView

@end


text:
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import sys
import os
import setuptools

__version__ = '0.0.1'

class get_pybind_include(object):
    """Helper class to determine the pybind11 include path

    The purpose of this class is to postpone importing pybind11
    until it is actually installed, so that the ``get_include()``
    method can be invoked. """

    def __init__(self, user=False):
        self.user = user

    def __str__(self):
        import pybind11
        return pybind11.get_include(self.user)

class get_numpy_include(object):
    """Helper class to determine the numpy include path

    The purpose of this class is to postpone importing numpy
    until it is actually installed, so that the ``get_include()``
    method can be invoked. """

    def __str__(self):
        import numpy
        return numpy.get_include()

ext_modules = [
    Extension(
        'xtensor_python_test',
        ['main.cpp'],
        include_dirs=[
            # Path to pybind11 headers
            '../include/',
            get_pybind_include(),
            get_pybind_include(user=True),
            # Path to numpy headers
            get_numpy_include(),
            os.path.join(sys.prefix, 'include'),
            os.path.join(sys.prefix, 'Library', 'include')
        ],
        language='c++'
    ),
]

def has_flag(compiler, flagname):
    """Return a boolean indicating whether a flag name is supported on
    the specified compiler.
    """
    import tempfile
    with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f:
        f.write('int main (int argc, char **argv) { return 0; }')
        try:
            compiler.compile([f.name], extra_postargs=[flagname])
        except setuptools.distutils.errors.CompileError:
            return False
    return True

def cpp_flag(compiler):
    """Return the -std=c++14 compiler flag  and errors when the flag is
    no available.
    """
    if has_flag(compiler, '-std=c++14'):
        return '-std=c++14'
    else:
        raise RuntimeError('C++14 support is required by xtensor!')

class BuildExt(build_ext):
    """A custom build extension for adding compiler-specific options."""
    c_opts = {
        'msvc': ['/EHsc'],
        'unix': [],
    }

    if sys.platform == 'darwin':
        c_opts['unix'] += ['-stdlib=libc++', '-mmacosx-version-min=10.7']

    def build_extensions(self):
        ct = self.compiler.compiler_type
        opts = self.c_opts.get(ct, [])
        if ct == 'unix':
            opts.append('-DVERSION_INFO="%s"' % self.distribution.get_version())
            opts.append(cpp_flag(self.compiler))
            if has_flag(self.compiler, '-fvisibility=hidden'):
                opts.append('-fvisibility=hidden')
        elif ct == 'msvc':
            opts.append('/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version())
        for ext in self.extensions:
            ext.extra_compile_args = opts
        build_ext.build_extensions(self)

setup(
    name='xtensor_python_test',
    version=__version__,
    author='Sylvain Corlay',
    author_email='sylvain.corlay@gmail.com',
    url='https://github.com/pybind/python_example',
    description='An example project using xtensor-python',
    long_description='',
    ext_modules=ext_modules,
    install_requires=['pybind11>=2.0.1'],
    cmdclass={'build_ext': BuildExt},
    zip_safe=False,
)


text:
import type { Nullable } from "core/types";
import type { IExplorerExtensibilityGroup } from "core/Debug/debugLayer";

import { Tools } from "../../tools";
import * as ReactDOM from "react-dom";
import * as React from "react";
import type { GlobalState } from "../../globalState";
import { DragOverLocation } from "../../globalState";
import { ControlTreeItemComponent } from "./entities/gui/controlTreeItemComponent";
import type { Observer } from "core/Misc/observable";
import { Container } from "gui/2D/controls/container";

import expandedIcon from "../../imgs/expandedIcon.svg";
import collapsedIcon from "../../imgs/collapsedIcon.svg";
// eslint-disable-next-line @typescript-eslint/naming-convention
const CONTROL_HEIGHT = 32;

export interface ITreeItemSelectableComponentProps {
    entity: any;
    selectedEntities: any[];
    mustExpand?: boolean;
    offset: number;
    globalState: GlobalState;
    extensibilityGroups?: IExplorerExtensibilityGroup[];
    filter: Nullable<string>;
}

export interface ITreeItemSelectableComponentState {
    expand: boolean;
    dragOver: boolean;
    isSelected: boolean;
    isHovered: boolean;
    dragOverLocation: DragOverLocation;
}

export class TreeItemSelectableComponent extends React.Component<ITreeItemSelectableComponentProps, ITreeItemSelectableComponentState> {
    private _onSelectionChangedObservable: Nullable<Observer<any>>;
    private _onDraggingEndObservable: Nullable<Observer<any>>;
    private _onDraggingStartObservable: Nullable<Observer<any>>;
    /** flag flipped onDragEnter if dragOver is already true
     * prevents dragLeave from immediately setting dragOver to false
     * required to make dragging work as expected
     * see: see: https://github.com/transformation-dev/matrx/tree/master/packages/dragster
     */
    private _secondDragEnter = false;
    constructor(props: ITreeItemSelectableComponentProps) {
        super(props);

        this.state = {
            expand: true,
            dragOver: false,
            dragOverLocation: DragOverLocation.NONE,
            isHovered: false,
            isSelected: this.props.selectedEntities.includes(this.props.entity),
        };

        this._onSelectionChangedObservable = props.globalState.onSelectionChangedObservable.add(() => {
            this.setState({ isSelected: this.props.globalState.selectedControls.includes(this.props.entity) });
        });

        this._onDraggingEndObservable = props.globalState.onDraggingEndObservable.add(() => {
            this.setState({ dragOverLocation: DragOverLocation.NONE });
        });
        this._onDraggingStartObservable = props.globalState.onDraggingStartObservable.add(() => {
            this.forceUpdate();
        });
    }

    switchExpandedState(): void {
        this.props.entity.reservedDataStore.setExpandedState(!this.props.entity.reservedDataStore.isExpanded);
        this.setState({ expand: !this.state.expand });
    }

    shouldComponentUpdate(nextProps: ITreeItemSelectableComponentProps, nextState: { isSelected: boolean }) {
        //if the next entity is going to be selected then we want to highlight it so update
        if (nextProps.selectedEntities.includes(nextProps.entity)) {
            nextState.isSelected = true;
            return true;
        } else {
            nextState.isSelected = false;
        }
        if (Tools.LookForItems(nextProps.entity, nextProps.selectedEntities)) {
            return true;
        }

        return true;
    }

    scrollIntoView() {
        const element = ReactDOM.findDOMNode(this) as Element;

        if (element) {
            element.scrollIntoView(false);
        }
    }

    componentWillUnmount() {
        this.props.globalState.onSelectionChangedObservable.remove(this._onSelectionChangedObservable);
        this.props.globalState.onDraggingEndObservable.remove(this._onDraggingEndObservable);
        this.props.globalState.onDraggingStartObservable.remove(this._onDraggingStartObservable);
    }

    onSelect() {
        const entity = this.props.entity;
        this.props.globalState.select(entity);
        this.props.globalState.selectionLock = true;
    }

    renderChildren(isExpanded: boolean, offset = true) {
        const entity = this.props.entity;

        if ((!entity.getChildren && !entity.children) || !isExpanded) {
            return null;
        }

        const children = Tools.SortAndFilter(entity, entity.getChildren ? entity.getChildren() : entity.children);
        if (entity.typeName === "StackPanel" || entity.typeName === "VirtualKeyboard") {
            children.reverse();
        }
        return children.map((item, i) => {
            if (item.name == "Art-Board-Background") {
                return null;
            }

            return (
                <TreeItemSelectableComponent
                    globalState={this.props.globalState}
                    mustExpand={this.props.mustExpand}
                    extensibilityGroups={this.props.extensibilityGroups}
                    selectedEntities={this.props.selectedEntities}
                    key={i}
                    offset={this.props.offset + (offset ? 2 : 0)}
                    entity={item}
                    filter={this.props.filter}
                />
            );
        });
    }

    render() {
        if (
            this.props.entity === this.props.globalState.workbench.trueRootContainer ||
            this.props.entity === this.props.globalState.workbench.visibleRegionContainer ||
            this.props.entity === this.props.globalState.workbench.panAndZoomContainer
        ) {
            return this.renderChildren(true, false);
        }
        const marginStyle = {
            paddingLeft: 10 * (this.props.offset + 0.5) - 20 + "px",
        };
        const lineMarginStyle = {
            marginLeft: 10 * (this.props.offset + 0.5) - 20 + "px",
        };
        let entity = this.props.entity;

        if (!entity.reservedDataStore) {
            entity.reservedDataStore = {
                isExpanded: true,
                setExpandedState: (expanded: boolean) => (entity.reservedDataStore.isExpanded = expanded),
            };
        }

        const isExpanded = entity.reservedDataStore.isExpanded || Tools.LookForItems(this.props.entity, this.props.selectedEntities);

        entity.reservedDataStore.isExpanded = isExpanded;

        const chevron = isExpanded ?  : ;

        let children = entity.getClassName() === "MultiMaterial" ? [] : Tools.SortAndFilter(entity, entity.getChildren ? entity.getChildren() : entity.children);
        let hasChildren = children.length > 0;

        if (this.props.filter) {
            const lowerCaseFilter = this.props.filter.toLowerCase();
            if (!entity.name || entity.name.toLowerCase().indexOf(lowerCaseFilter) === -1) {
                if (!hasChildren) {
                    return null;
                }

                if (entity.getDescendants) {
                    if (
                        entity.getDescendants(false, (n: any) => {
                            return n.name && n.name.toLowerCase().indexOf(lowerCaseFilter) !== -1;
                        }).length === 0
                    ) {
                        return null;
                    }
                }
            }
        }

        let className = "itemContainer"; //setting class name plus whatever extras based on states
        className += this.state.isSelected && this.props.globalState.draggedControl === null ? " selected" : "";
        className += this.state.isHovered && this.props.globalState.draggedControl === null ? " hover" : "";
        className += this.state.dragOver && this.state.dragOverLocation == DragOverLocation.CENTER && entity instanceof Container ? " parent" : "";
        className += this.props.globalState.draggedControl === this.props.entity ? " dragged" : "";
        className += this.state.dragOver && this.state.dragOverLocation == DragOverLocation.ABOVE && entity.parent ? " seAbove" : "";
        className += this.state.dragOver && this.state.dragOverLocation == DragOverLocation.BELOW && entity.parent ? " seBelow" : "";

        const styleName = className === "itemContainer seAbove" || className === "itemContainer seBelow" ? lineMarginStyle : marginStyle;

        return (

 {
                        this.onSelect();
                    }}
                    onPointerEnter={() => this.setState({ isHovered: true })}
                    onPointerLeave={() => this.setState({ isHovered: false })}
                    onDragStart={() => {
                        this.props.globalState.draggedControl = this.props.entity;
                        this.props.globalState.onDraggingStartObservable.notifyObservers();
                    }}
                    onDragEnd={() => {
                        this.props.globalState.onDraggingEndObservable.notifyObservers();
                    }}
                    draggable={entity.parent ? true : false}
                    onDrop={(event) => {
                        this.drop();
                        event.preventDefault();
                    }}
                    onDragEnter={(event) => {
                        event.preventDefault();
                        this.dragOver(event);
                    }}
                    onDragOver={(event) => this.updateDragOverLocation(event)}
                    onDragLeave={() => {
                        // don't immediately set dragOver to false
                        if (this._secondDragEnter) {
                            this._secondDragEnter = false;
                        } else {
                            this.setState({ dragOver: false });
                        }
                    }}
                >
                    {hasChildren && (

 {
                                this.switchExpandedState();
                                if (event.shiftKey) {
                                    while (hasChildren) {
                                        this.renderChildren(true);
                                        entity = entity.children[0];
                                        children =
                                            entity.getClassName() === "MultiMaterial"
                                                ? []
                                                : Tools.SortAndFilter(entity, entity.getChildren ? entity.getChildren() : entity.children);
                                        hasChildren = children.length > 0;
                                        entity.reservedDataStore.isExpanded = true;
                                    }
                                }
                            }}
                        >
                            {chevron}

                    )}

                    <ControlTreeItemComponent
                        globalState={this.props.globalState}
                        extensibilityGroups={this.props.extensibilityGroups}
                        control={entity}
                        onClick={() => {}}
                        isHovered={this.state.isHovered}
                        isDragOver={this.state.dragOver}
                        dragOverLocation={this.state.dragOverLocation}
                    />

                {this.renderChildren(isExpanded)}

        );
    }

    dragOver(event: React.DragEvent<HTMLDivElement>): void {
        this.updateDragOverLocation(event);
        // if we've already hovered the element, record a new drag event
        if (this.state.dragOver) {
            this._secondDragEnter = true;
        } else {
            this.setState({ dragOver: true });
        }
    }

    updateDragOverLocation(event: React.DragEvent<HTMLDivElement>) {
        //check the positions of the mouse cursor.
        const target = event.target as HTMLElement;
        const rect = target.getBoundingClientRect();
        const y = event.clientY - rect.top;

        if (this.props.entity instanceof Container) {
            if (y < CONTROL_HEIGHT / 5) {
                //split in fifths
                this.setState({ dragOverLocation: DragOverLocation.ABOVE });
            } else if (y > (4 * CONTROL_HEIGHT) / 5) {
                this.setState({ dragOverLocation: DragOverLocation.BELOW });
            } else {
                this.setState({ dragOverLocation: DragOverLocation.CENTER });
            }
        } else {
            if (y < CONTROL_HEIGHT / 2) {
                //split in half
                this.setState({ dragOverLocation: DragOverLocation.ABOVE });
            } else {
                this.setState({ dragOverLocation: DragOverLocation.BELOW });
            }
        }
    }

    drop(): void {
        this.props.globalState.onDropObservable.notifyObservers();
        const control = this.props.entity;
        if (this.props.globalState.draggedControl != control) {
            this.props.globalState.draggedControlDirection = this.state.dragOverLocation;
            this.props.globalState.onParentingChangeObservable.notifyObservers(this.props.entity);
        }
        this.props.globalState.draggedControl = null;
        this.setState({ dragOverLocation: DragOverLocation.NONE, dragOver: false });
        this._secondDragEnter = false;
    }
}


text:
#include "laserBeacon.h"
#include "beaconSystem.h"
#include "laserBeaconDevice.h"
#include "laserBeaconDeviceInterface.h"
#include "commonBeaconDeviceInterface.h"

#include "../../common/commons.h"

#include "../../common/io/inputStream.h"
#include "../../common/io/outputStream.h"
#include "../../common/io/printWriter.h"
#include "../../common/io/reader.h"
#include "../../common/io/ioUtils.h"

#include "../../common/log/logger.h"
#include "../../common/log/logLevel.h"

#include "../../common/serial/serial.h"

#include "../../device/device.h"

#include "../../robot/robotDetector.h"

#include "../../drivers/jennic/jennic5139Driver.h"
#include "../../drivers/beacon/beaconLaserDriver.h"

#include "../../main/beaconBoard/beaconBoard.h"

void deviceBeaconInit() {
    initLaserBeacon();
}

void deviceBeaconShutDown() {
    stopLaserBeacon();
}

bool deviceBeaconIsOk() {
    return true;
}

void deviceBeaconHandleRawData(char commandHeader, InputStream* inputStream, OutputStream* outputStream) {
    // Init Coordinater
    if (commandHeader == COMMAND_INIT_JENNIC_AS_COORDINATER) {
        appendAck(outputStream);
        append(outputStream, COMMAND_INIT_JENNIC_AS_COORDINATER);
        initJennic5139Coordinater();
    }// Send immediately position to router (even if beacon system is disabled)
    else if (commandHeader == COMMAND_SEND_ROBOT_POSITION_FROM_COORDINATER_TO_ROUTER) {
        appendAck(outputStream);
        append(outputStream, COMMAND_SEND_ROBOT_POSITION_FROM_COORDINATER_TO_ROUTER);
        Point* point = getOpponentRobotPosition();
        notifyRobotPosition(point);
    }// Get the last detected position of the robot
    else if (commandHeader == COMMAND_BEACON_POSITION) {
        // Computes position
        Point* point = getOpponentRobotPosition();
        appendAck(outputStream);

        appendRobotPosition(outputStream, COMMAND_BEACON_POSITION, point);
        // Get the configuration of the both laser
    } else if (commandHeader == COMMAND_BEACON_CONFIGURATION) {
        appendAck(outputStream);
        append(outputStream, COMMAND_BEACON_CONFIGURATION);

        OutputStream* logOutputStream = getInfoOutputStreamLogger();
        printBeaconSystemConfiguration(logOutputStream);
        // Set the configuration of the system
    } else if (commandHeader == COMMAND_BEACON_SET_CONFIGURATION) {
        appendAck(outputStream);

        float distanceBetweenBeacon = readHex4(inputStream);
        checkIsSeparator(inputStream);
        float calibrationX = readHex4(inputStream);
        checkIsSeparator(inputStream);
        float calibrationY = readHex4(inputStream);

        setDistanceBetweenBeacon(distanceBetweenBeacon);
        setCalibrationPoint(calibrationX, calibrationY);

        append(outputStream, COMMAND_BEACON_SET_CONFIGURATION);
        // Calibration
    } else if (commandHeader == COMMAND_BEACON_CALIBRATION) {
        appendAck(outputStream);
        doBeaconCalibration();
        append(outputStream, COMMAND_BEACON_CALIBRATION);
        // Jennic Remote (router) Light on / off
    } else if (commandHeader == COMMAND_ROUTER_LIGHT) {
        appendAck(outputStream);
        unsigned char status = readHex2(inputStream);
        jennic5139RemoteLight(JENNIC_ROUTER_MAC_ADDRESS, JENNIC_LED_ALL, status != 0);
        append(outputStream, COMMAND_ROUTER_LIGHT);
    }// Run the servo of the beacon system
    else if (commandHeader == COMMAND_BEACON_SERVO_RUN) {
        appendAck(outputStream);
        setBeaconSystemEnabled(true);
        append(outputStream, COMMAND_BEACON_SERVO_RUN);
    }// Stop the servo of the beacon system
    else if (commandHeader == COMMAND_BEACON_SERVO_STOP) {
        appendAck(outputStream);
        setBeaconSystemEnabled(false);
        append(outputStream, COMMAND_BEACON_SERVO_STOP);
    }
}

static DeviceDescriptor descriptor = {
    .deviceInit = &deviceBeaconInit,
    .deviceShutDown = &deviceBeaconShutDown,
    .deviceIsOk = &deviceBeaconIsOk,
    .deviceHandleRawData = &deviceBeaconHandleRawData,
};

DeviceDescriptor* getBeaconDeviceDescriptor() {
    return &descriptor;
}


text:
var saveAlertTypes = function (alertTypesIDs, emailList, checkedValues) {

    jagg.post("/site/blocks/manage-alerts/ajax/manage-alerts.jag", {
        action: "saveAlertTypes",
        checkedList: alertTypesIDs.toString(),
        emailList: emailList,
        checkedValues: checkedValues.toString()

    }, function (result) {

        //console.log(result);
        if (!result.error) {

            jagg.message({content: i18n.t("info.successfullySaved"), type: "info"});
            $("#unsubscribeBtn").show();

        }else {
            if (result.message == "AuthenticateError") {
                jagg.showLogin();
            } else {
                jagg.message({content:result.message,type:"error"});
            }
        }
    }, "json");

}

var unSubscribeAlerts = function() {

    jagg.post("/site/blocks/manage-alerts/ajax/manage-alerts.jag", {
        action: "unSubscribe"
    }, function (result) {

        //console.log(result);
        if (!result.error) {

            jagg.message({content: i18n.t("info.successfullySaved"), type: "info"});

            $(":checkbox").each(function () {
                $(this).removeAttr('checked');
            });

            $("#tokenfield").tagsinput('removeAll');
            $("#unsubscribeBtn").hide();

        }else {
            if (result.message == "AuthenticateError") {
                jagg.showLogin();
            } else {
                jagg.message({content:result.message,type:"error"});
            }
        }
    }, "json");

}

$(document).ready(function () {

    var notChecked = [], checked = [], checkedValues = [];
    $(":checkbox").each(function () {
        id = this.value;
        values = this.id;
        this.checked ? checked.push(id) : notChecked.push(id);
        if (this.checked) {
            checkedValues.push(values);
        }

    });

    if (checkedValues.length > 0) {

        $("#unsubscribeBtn").show();
    }

    $('#tokenfield').on('beforeItemAdd', function (event) {
        /* Validate url */

        var re = /\S+@\S+\.\S+/
        var valid = re.test(event.item)

        if (!valid) {
            event.cancel = true;
        }
        else {
            event.cancel = false;
        }
    });

    $("#cancelBtn").click(function () {

        location.reload();

    });

    $("#unsubscribeBtn").click(function () {

        unSubscribeAlerts();

    });
    $("#saveBtn").click(function () {

        if ($(".token").hasClass("invalid")) {
            jagg.message({content: i18n.t("errorMsgs.invalidEmailEntered") , type: "error"});
        } else {

            var notChecked = [], checked = [], checkedValues = [];
            $(":checkbox").each(function () {
                id = this.value;
                values = this.id;
                this.checked ? checked.push(id) : notChecked.push(id);
                if (this.checked) {
                    checkedValues.push(values);
                }

            });

            if (checkedValues.length > 0) {
                var emailList = $("#tokenfield").val();
                if(emailList) {
                    saveAlertTypes(checked, emailList, checkedValues);
                }else{
                    jagg.message({content: i18n.t("errorMsgs.atleastOneEmailNeeded") , type: "error"});
                }
            } else {
                jagg.message({content: i18n.t("errorMsgs.atLeastOneAlertTypeNeeded") , type: "error"});
            }
        }
    });

});


text:
import plugins_manager
from base_crawler import BaseCrawler, BaseFrame

class HostFrame(BaseFrame):

    def __init__(self, feature_types, namespace):
        BaseFrame.__init__(self, feature_types)
        self.metadata['namespace'] = namespace
        self.metadata['system_type'] = 'host'

class HostCrawler(BaseCrawler):

    def __init__(self,
                 features=['os', 'cpu'], namespace='',
                 plugin_places=['plugins'], options={}):
        BaseCrawler.__init__(
            self,
            features=features,
            plugin_places=plugin_places)
        plugins_manager.reload_host_crawl_plugins(
            features, plugin_places, options)
        self.plugins = plugins_manager.get_host_crawl_plugins(
            features=features)
        self.namespace = namespace

    def crawl(self, ignore_plugin_exception=True):
        """
        Crawl the host with all the plugins loaded on __init__

        :param ignore_plugin_exception: just ignore exceptions on a plugin
        :return: a list generator with a frame object
        """
        frame = HostFrame(self.features, self.namespace)
        for (plugin_obj, plugin_args) in self.plugins:
            try:
                frame.add_features(plugin_obj.crawl(**plugin_args))
            except Exception as exc:
                if not ignore_plugin_exception:
                    raise exc
        yield frame


text:
namespace phosphor
{
namespace logging
{
namespace test
{

using namespace sdbusplus::xyz::openbmc_project::Common::Error;

TEST_F(TestRemoteLogging, testGoodAddress)
{
    config->address("1.1.1.1");
    EXPECT_EQ(config->address(), "1.1.1.1");

    config->address("abcd:ef01::01");
    EXPECT_EQ(config->address(), "abcd:ef01::01");
}

TEST_F(TestRemoteLogging, testBadAddress)
{
    EXPECT_THROW(config->address("this is not_an_IP!"), InvalidArgument);
}

} // namespace test
} // namespace logging
} // namespace phosphor


text:
dependencies = {}
table.insert(dependencies, {os_constants.os_url("master/main.lua"), "main", false})
table.insert(dependencies, {os_constants.os_url("master/rebootall.lua"), "rebootall", false} )
table.insert(dependencies, {os_constants.os_url("master/helloall.lua"), "helloall", false} )

print("Preparing to update..")
math.randomseed(os.time())
os.sleep(math.random(5))
if api_os.update(dependencies) == true then
    print "Update Successful, Launching main .."
    os.sleep(1)
    shell.run("clear")
    if not shell.run("main") then
        if not shell.run("backup") then
            print()
            print()
            print("---------BLUE SCREEN---------")
            print("-----------------------------")
            print("System completely fucked up..")
            print(" will reboot in 120 seconds")
            print("-----------------------------")
            os.sleep(120)
            os.restart()
        end
    end
else
    print("Update failed. Retry in 10 seconds")
    os.sleep(10)
    os.reboot()
end