text:
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
// Developed by Minigraph
//
// Author:  James Stanard
//

#include "pch.h"
#include "SystemTime.h"
#include "Display.h"
#include "TextRenderer.h"
#include "GraphRenderer.h"
#include "GameInput.h"
#include "GpuTimeManager.h"
#include "CommandContext.h"
#include <vector>
#include <unordered_map>
#include <array>

using namespace Graphics;
using namespace GraphRenderer;
using namespace Math;
using namespace std;

#define PERF_GRAPH_ERROR uint32_t(0xFFFFFFFF)
namespace EngineProfiling
{
    bool Paused = false;
}

class StatHistory
{
public:
    StatHistory()
    {
        for (uint32_t i = 0; i < kHistorySize; ++i)
            m_RecentHistory[i] = 0.0f;
        for (uint32_t i = 0; i < kExtendedHistorySize; ++i)
            m_ExtendedHistory[i] = 0.0f;
        m_Average = 0.0f;
        m_Minimum = 0.0f;
        m_Maximum = 0.0f;
    }

    void RecordStat( uint32_t FrameIndex, float Value )
    {
        m_RecentHistory[FrameIndex % kHistorySize] = Value;
        m_ExtendedHistory[FrameIndex % kExtendedHistorySize] = Value;
        m_Recent = Value;

        uint32_t ValidCount = 0;
        m_Minimum = FLT_MAX;
        m_Maximum = 0.0f;
        m_Average = 0.0f;

        for (float val : m_RecentHistory)
        {
            if (val > 0.0f)
            {
                ++ValidCount;
                m_Average += val;
                m_Minimum = min(val, m_Minimum);
                m_Maximum = max(val, m_Maximum);
            }
        }

        if (ValidCount > 0)
            m_Average /= (float)ValidCount;
        else
            m_Minimum = 0.0f;
    }

    float GetLast(void) const { return m_Recent; }
    float GetMax(void) const { return m_Maximum; }
    float GetMin(void) const { return m_Minimum; }
    float GetAvg(void) const { return m_Average; }

    const float* GetHistory(void) const { return m_ExtendedHistory; }
    uint32_t GetHistoryLength(void) const { return kExtendedHistorySize; }

private:
    static const uint32_t kHistorySize = 64;
    static const uint32_t kExtendedHistorySize = 256;
    float m_RecentHistory[kHistorySize];
    float m_ExtendedHistory[kExtendedHistorySize];
    float m_Recent;
    float m_Average;
    float m_Minimum;
    float m_Maximum;
};

class StatPlot
{
public:
    StatPlot(StatHistory& Data, Color Col = Color(1.0f, 1.0f, 1.0f))
        : m_StatData(Data), m_PlotColor(Col)
    {
    }

    void SetColor( Color Col )
    {
        m_PlotColor = Col;
    }

private:
    StatHistory& m_StatData;
    Color m_PlotColor;
};

class StatGraph
{
public:
    StatGraph(const wstring& Label, D3D12_RECT Window)
        : m_Label(Label), m_Window(Window), m_BGColor(0.0f, 0.0f, 0.0f, 0.2f)
    {
    }

    void SetLabel(const wstring& Label)
    {
        m_Label = Label;
    }

    void SetWindow(D3D12_RECT Window)
    {
        m_Window = Window;
    }

    uint32_t AddPlot( const StatPlot& P )
    {
        uint32_t Idx = (uint32_t)m_Stats.size();
        m_Stats.push_back(P);
        return Idx;
    }

    StatPlot& GetPlot( uint32_t Handle );

    void Draw( GraphicsContext& Context );

private:
    wstring m_Label;
    D3D12_RECT m_Window;
    vector<StatPlot> m_Stats;
    Color m_BGColor;
    float m_PeakValue;
};

class GraphManager
{
public:

private:
    vector<StatGraph> m_Graphs;
};

class GpuTimer
{
public:

    GpuTimer::GpuTimer()
    {
        m_TimerIndex = GpuTimeManager::NewTimer();
    }

    void Start(CommandContext& Context)
    {
        GpuTimeManager::StartTimer(Context, m_TimerIndex);
    }

    void Stop(CommandContext& Context)
    {
        GpuTimeManager::StopTimer(Context, m_TimerIndex);
    }

    float GpuTimer::GetTime(void)
    {
        return GpuTimeManager::GetTime(m_TimerIndex);
    }

    uint32_t GetTimerIndex(void)
    {
        return m_TimerIndex;
    }
private:

    uint32_t m_TimerIndex;
};

class NestedTimingTree
{
public:
    NestedTimingTree( const wstring& name, NestedTimingTree* parent = nullptr )
        : m_Name(name), m_Parent(parent), m_IsExpanded(false), m_IsGraphed(false), m_GraphHandle(PERF_GRAPH_ERROR) {}

    NestedTimingTree* GetChild( const wstring& name )
    {
        auto iter = m_LUT.find(name);
        if (iter != m_LUT.end())
            return iter->second;

        NestedTimingTree* node = new NestedTimingTree(name, this);
        m_Children.push_back(node);
        m_LUT[name] = node;
        return node;
    }

    NestedTimingTree* NextScope( void )
    {
        if (m_IsExpanded && m_Children.size() > 0)
            return m_Children[0];

        return m_Parent->NextChild(this);
    }

    NestedTimingTree* PrevScope( void )
    {
        NestedTimingTree* prev = m_Parent->PrevChild(this);
        return prev == m_Parent ? prev : prev->LastChild();
    }

    NestedTimingTree* FirstChild( void )
    {
        return m_Children.size() == 0 ? nullptr : m_Children[0];
    }

    NestedTimingTree* LastChild( void )
    {
        if (!m_IsExpanded || m_Children.size() == 0)
            return this;

        return m_Children.back()->LastChild();
    }

    NestedTimingTree* NextChild( NestedTimingTree* curChild )
    {
        ASSERT(curChild->m_Parent == this);

        for (auto iter = m_Children.begin(); iter != m_Children.end(); ++iter)
        {
            if (*iter == curChild)
            {
                auto nextChild = iter; ++nextChild;
                if (nextChild != m_Children.end())
                    return *nextChild;
            }
        }

        if (m_Parent != nullptr)
            return m_Parent->NextChild(this);
        else
            return &sm_RootScope;
    }

    NestedTimingTree* PrevChild( NestedTimingTree* curChild )
    {
        ASSERT(curChild->m_Parent == this);

        if (*m_Children.begin() == curChild)
        {
            if (this == &sm_RootScope)
                return sm_RootScope.LastChild();
            else
                return this;
        }

        for (auto iter = m_Children.begin(); iter != m_Children.end(); ++iter)
        {
            if (*iter == curChild)
            {
                auto prevChild = iter; --prevChild;
                return *prevChild;
            }
        }

        ERROR("All attempts to find a previous timing sample failed");
        return nullptr;
    }

    void StartTiming( CommandContext* Context )
    {
        m_StartTick = SystemTime::GetCurrentTick();
        if (Context == nullptr)
            return;

        m_GpuTimer.Start(*Context);

        Context->PIXBeginEvent(m_Name.c_str());
    }

    void StopTiming( CommandContext* Context )
    {
        m_EndTick = SystemTime::GetCurrentTick();
        if (Context == nullptr)
            return;

        m_GpuTimer.Stop(*Context);

        Context->PIXEndEvent();
    }

    void GatherTimes(uint32_t FrameIndex)
    {
        if (sm_SelectedScope == this)
        {
            GraphRenderer::SetSelectedIndex(m_GpuTimer.GetTimerIndex());
        }
        if (EngineProfiling::Paused)
        {
            for (auto node : m_Children)
                node->GatherTimes(FrameIndex);
            return;
        }
        m_CpuTime.RecordStat(FrameIndex, 1000.0f * (float)SystemTime::TimeBetweenTicks(m_StartTick, m_EndTick));
        m_GpuTime.RecordStat(FrameIndex, 1000.0f * m_GpuTimer.GetTime());

        for (auto node : m_Children)
            node->GatherTimes(FrameIndex);

        m_StartTick = 0;
        m_EndTick = 0;
    }

    void SumInclusiveTimes(float& cpuTime, float& gpuTime)
    {
        cpuTime = 0.0f;
        gpuTime = 0.0f;
        for (auto iter = m_Children.begin(); iter != m_Children.end(); ++iter)
        {
            cpuTime += (*iter)->m_CpuTime.GetLast();
            gpuTime += (*iter)->m_GpuTime.GetLast();
        }
    }

    static void PushProfilingMarker( const wstring& name, CommandContext* Context );
    static void PopProfilingMarker( CommandContext* Context );
    static void Update( void );
    static void UpdateTimes( void )
    {
        uint32_t FrameIndex = (uint32_t)Graphics::GetFrameCount();

        GpuTimeManager::BeginReadBack();
        sm_RootScope.GatherTimes(FrameIndex);
        s_FrameDelta.RecordStat(FrameIndex, GpuTimeManager::GetTime(0));
        GpuTimeManager::EndReadBack();

        float TotalCpuTime, TotalGpuTime;
        sm_RootScope.SumInclusiveTimes(TotalCpuTime, TotalGpuTime);
        s_TotalCpuTime.RecordStat(FrameIndex, TotalCpuTime);
        s_TotalGpuTime.RecordStat(FrameIndex, TotalGpuTime);

        GraphRenderer::Update(XMFLOAT2(TotalCpuTime, TotalGpuTime), 0, GraphType::Global);
    }

    static float GetTotalCpuTime(void) { return s_TotalCpuTime.GetAvg(); }
    static float GetTotalGpuTime(void) { return s_TotalGpuTime.GetAvg(); }
    static float GetFrameDelta(void) { return s_FrameDelta.GetAvg(); }

    static void Display( TextContext& Text, float x )
    {
        float curX = Text.GetCursorX();
        Text.DrawString("  ");
        float indent = Text.GetCursorX() - curX;
        Text.SetCursorX(curX);
        sm_RootScope.DisplayNode( Text, x - indent, indent );
        sm_RootScope.StoreToGraph();
    }

    void Toggle()
    {
        //if (m_GraphHandle == PERF_GRAPH_ERROR)
        //    m_GraphHandle = GraphRenderer::InitGraph(GraphType::Profile);
        //m_IsGraphed = GraphRenderer::ManageGraphs(m_GraphHandle, GraphType::Profile);
    }
    bool IsGraphed(){ return m_IsGraphed;}

private:

    void DisplayNode( TextContext& Text, float x, float indent );
    void StoreToGraph(void);
    void DeleteChildren( void )
    {
        for (auto node : m_Children)
            delete node;
        m_Children.clear();
    }

    wstring m_Name;
    NestedTimingTree* m_Parent;
    vector<NestedTimingTree*> m_Children;
    unordered_map<wstring, NestedTimingTree*> m_LUT;
    int64_t m_StartTick;
    int64_t m_EndTick;
    StatHistory m_CpuTime;
    StatHistory m_GpuTime;
    bool m_IsExpanded;
    GpuTimer m_GpuTimer;
    bool m_IsGraphed;
    GraphHandle m_GraphHandle;
    static StatHistory s_TotalCpuTime;
    static StatHistory s_TotalGpuTime;
    static StatHistory s_FrameDelta;
    static NestedTimingTree sm_RootScope;
    static NestedTimingTree* sm_CurrentNode;
    static NestedTimingTree* sm_SelectedScope;

    static bool sm_CursorOnGraph;

};

StatHistory NestedTimingTree::s_TotalCpuTime;
StatHistory NestedTimingTree::s_TotalGpuTime;
StatHistory NestedTimingTree::s_FrameDelta;
NestedTimingTree NestedTimingTree::sm_RootScope(L"");
NestedTimingTree* NestedTimingTree::sm_CurrentNode = &NestedTimingTree::sm_RootScope;
NestedTimingTree* NestedTimingTree::sm_SelectedScope = &NestedTimingTree::sm_RootScope;
bool NestedTimingTree::sm_CursorOnGraph = false;
namespace EngineProfiling
{
    BoolVar DrawFrameRate("Display Frame Rate", true);
    BoolVar DrawProfiler("Display Profiler", false);
    //BoolVar DrawPerfGraph("Display Performance Graph", false);
    const bool DrawPerfGraph = false;

    void Update( void )
    {
        if (GameInput::IsFirstPressed( GameInput::kStartButton )
            || GameInput::IsFirstPressed( GameInput::kKey_space ))
        {
            Paused = !Paused;
        }
        NestedTimingTree::UpdateTimes();
    }

    void BeginBlock(const wstring& name, CommandContext* Context)
    {
        NestedTimingTree::PushProfilingMarker(name, Context);
    }

    void EndBlock(CommandContext* Context)
    {
        NestedTimingTree::PopProfilingMarker(Context);
    }

    bool IsPaused()
    {
        return Paused;
    }

    void DisplayFrameRate( TextContext& Text )
    {
        if (!DrawFrameRate)
            return;

        float cpuTime = NestedTimingTree::GetTotalCpuTime();
        float gpuTime = NestedTimingTree::GetTotalGpuTime();
        float frameRate = 1.0f / NestedTimingTree::GetFrameDelta();

        Text.DrawFormattedString( "CPU %7.3f ms, GPU %7.3f ms, %3u Hz\n",
            cpuTime, gpuTime, (uint32_t)(frameRate + 0.5f));
    }

    void DisplayPerfGraph( GraphicsContext& Context )
    {
        if (DrawPerfGraph)
            GraphRenderer::RenderGraphs(Context, GraphType::Global );
    }

    void Display( TextContext& Text, float x, float y, float /*w*/, float /*h*/ )
    {
        Text.ResetCursor(x, y);

        if (DrawProfiler)
        {
            //Text.GetCommandContext().SetScissor((uint32_t)Floor(x), (uint32_t)Floor(y), (uint32_t)Ceiling(w), (uint32_t)Ceiling(h));

            NestedTimingTree::Update();

            Text.SetColor( Color(0.5f, 1.0f, 1.0f) );
            Text.DrawString("Engine Profiling");
            Text.SetColor(Color(0.8f, 0.8f, 0.8f));
            Text.SetTextSize(20.0f);
            Text.DrawString("           CPU    GPU");
            Text.SetTextSize(24.0f);
            Text.NewLine();
            Text.SetTextSize(20.0f);
            Text.SetColor( Color(1.0f, 1.0f, 1.0f) );

            NestedTimingTree::Display( Text, x );
        }

        Text.GetCommandContext().SetScissor(0, 0, g_DisplayWidth, g_DisplayHeight);
    }

} // EngineProfiling

void NestedTimingTree::PushProfilingMarker( const wstring& name, CommandContext* Context )
{
    sm_CurrentNode = sm_CurrentNode->GetChild(name);
    sm_CurrentNode->StartTiming(Context);
}

void NestedTimingTree::PopProfilingMarker( CommandContext* Context )
{
    sm_CurrentNode->StopTiming(Context);
    sm_CurrentNode = sm_CurrentNode->m_Parent;
}

void NestedTimingTree::Update( void )
{
    ASSERT(sm_SelectedScope != nullptr, "Corrupted profiling data structure");

    if (sm_SelectedScope == &sm_RootScope)
    {
        sm_SelectedScope = sm_RootScope.FirstChild();
        if (sm_SelectedScope == &sm_RootScope)
            return;
    }

    if (GameInput::IsFirstPressed( GameInput::kDPadLeft )
        || GameInput::IsFirstPressed( GameInput::kKey_left ))
    {
        //if still on graphs go back to text
        if (sm_CursorOnGraph)
            sm_CursorOnGraph = !sm_CursorOnGraph;
        else
            sm_SelectedScope->m_IsExpanded = false;
    }
    else if (GameInput::IsFirstPressed( GameInput::kDPadRight )
        || GameInput::IsFirstPressed( GameInput::kKey_right ))
    {
        if (sm_SelectedScope->m_IsExpanded == true && !sm_CursorOnGraph)
            sm_CursorOnGraph = true;
        else
            sm_SelectedScope->m_IsExpanded = true;
        //if already expanded go over to graphs

    }
    else if (GameInput::IsFirstPressed( GameInput::kDPadDown )
        || GameInput::IsFirstPressed( GameInput::kKey_down ))
    {
        sm_SelectedScope = sm_SelectedScope ? sm_SelectedScope->NextScope() : nullptr;
    }
    else if (GameInput::IsFirstPressed( GameInput::kDPadUp )
        || GameInput::IsFirstPressed( GameInput::kKey_up ))
    {
        sm_SelectedScope = sm_SelectedScope ? sm_SelectedScope->PrevScope() : nullptr;
    }
    else if (GameInput::IsFirstPressed( GameInput::kAButton )
        || GameInput::IsFirstPressed( GameInput::kKey_return ))
    {
        sm_SelectedScope->Toggle();
    }

}

void NestedTimingTree::DisplayNode( TextContext& Text, float leftMargin, float indent )
{
    if (this == &sm_RootScope)
    {
        m_IsExpanded = true;
        sm_RootScope.FirstChild()->m_IsExpanded = true;
    }
    else
    {
        if (sm_SelectedScope == this && !sm_CursorOnGraph)
            Text.SetColor( Color(1.0f, 1.0f, 0.5f) );
        else
            Text.SetColor( Color(1.0f, 1.0f, 1.0f) );

        Text.SetLeftMargin(leftMargin);
        Text.SetCursorX(leftMargin);

        if (m_Children.size() == 0)
            Text.DrawString("  ");
        else if (m_IsExpanded)
            Text.DrawString("- ");
        else
            Text.DrawString("+ ");

        Text.DrawString(m_Name.c_str());
        Text.SetCursorX(leftMargin + 300.0f);
        Text.DrawFormattedString("%6.3f %6.3f   ", m_CpuTime.GetAvg(), m_GpuTime.GetAvg());

        if (IsGraphed())
        {
            Text.SetColor(GraphRenderer::GetGraphColor(m_GraphHandle, GraphType::Profile));
            Text.DrawString("  []\n");
        }
        else
            Text.DrawString("\n");
    }

    if (!m_IsExpanded)
        return;

    for (auto node : m_Children)
        node->DisplayNode(Text, leftMargin + indent, indent);
}

void NestedTimingTree::StoreToGraph(void)
{
    if (m_GraphHandle != PERF_GRAPH_ERROR)
        GraphRenderer::Update( XMFLOAT2(m_CpuTime.GetLast(), m_GpuTime.GetLast()), m_GraphHandle, GraphType::Profile);

    for (auto node : m_Children)
        node->StoreToGraph();
}


text:
<?php

/**
 * This class defines the structure of the 'food' table.
 *
 *
 *
 * This map class is used by Propel to do runtime db structure discovery.
 * For example, the createSelectSql() method checks the type of a given column used in an
 * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
 * (i.e. if it's a text column type).
 *
 * @package    propel.generator.fbapp.map
 */
class FoodTableMap extends TableMap
{

    /**
     * The (dot-path) name of this class
     */
    const CLASS_NAME = 'fbapp.map.FoodTableMap';

    /**
     * Initialize the table attributes, columns and validators
     * Relations are not initialized by this method since they are lazy loaded
     *
     * @return void
     * @throws PropelException
     */
    public function initialize()
    {
        // attributes
        $this->setName('food');
        $this->setPhpName('Food');
        $this->setClassname('Food');
        $this->setPackage('fbapp');
        $this->setUseIdGenerator(true);
        // columns
        $this->addPrimaryKey('AutoCtr', 'Autoctr', 'INTEGER', true, null, null);
        $this->addColumn('FOODI', 'Foodi', 'VARCHAR', false, 30, null);
        $this->addColumn('FOODII', 'Foodii', 'VARCHAR', false, 30, null);
        $this->addColumn('FOODIII', 'Foodiii', 'VARCHAR', false, 50, null);
        $this->addColumn('GenFood', 'Genfood', 'VARCHAR', false, 50, null);
        $this->addColumn('SpecFood', 'Specfood', 'VARCHAR', false, 50, null);
        $this->addColumn('ComName', 'Comname', 'VARCHAR', false, 70, null);
        $this->addColumn('Stage', 'Stage', 'VARCHAR', false, 50, null);
        $this->addColumn('Rank', 'Rank', 'FLOAT', false, null, null);
        $this->addColumn('FoodIRank', 'Foodirank', 'FLOAT', false, null, null);
        $this->addColumn('FoodIIRank', 'Foodiirank', 'FLOAT', false, null, null);
        $this->addColumn('FoodIIIRank', 'Foodiiirank', 'FLOAT', false, null, null);
        $this->addColumn('Troph', 'Troph', 'DOUBLE', false, null, null);
        $this->addColumn('TrophSe', 'Trophse', 'DOUBLE', false, null, null);
        $this->addColumn('Refno', 'Refno', 'INTEGER', false, null, null);
        $this->addColumn('Remark', 'Remark', 'VARCHAR', false, 150, null);
        $this->addColumn('MaxLength', 'Maxlength', 'FLOAT', false, null, null);
        $this->addColumn('MinLength', 'Minlength', 'FLOAT', false, null, null);
        $this->addColumn('FoodFlag', 'Foodflag', 'TINYINT', false, null, null);
        $this->addColumn('PredFlag', 'Predflag', 'TINYINT', false, null, null);
        $this->addColumn('NewTroph', 'Newtroph', 'TINYINT', false, null, null);
        $this->addColumn('TS', 'Ts', 'TIMESTAMP', false, null, null);
        // validators
    } // initialize()

    /**
     * Build the RelationMap objects for this table relationships
     */
    public function buildRelations()
    {
    } // buildRelations()

} // FoodTableMap

redpajama_set_name: RedPajamaGithub


text:
__author__ = 'admin'
from webmocker.mock_helper import pretender_defaults

class Request:

  def __init__(self):
    self.url = pretender_defaults.url
    self.headers = {}
    self.body = pretender_defaults.request_body
    self.method = pretender_defaults.method

  def set_request_entities(self,request_json):
    from webmocker.mock_helper import pretend_helpers
    self.url = pretend_helpers.get_url_from_json(request_json)                                                    # get the URL from the json
    self.method = request_json['method'] if 'method' in request_json else pretender_defaults.method         # get the request method from the json
    self.body = pretend_helpers.get_body_from_json(request_json)                                                  # get the request body from the json
    self.headers = pretend_helpers.get_headers_from_json(request_json)                                            # get the request headers from the json


text:
#ifndef MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_AREA_H
#define MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_AREA_H

#include <stdint.h>
#include <stdbool.h>

// Implementations are in area.c
typedef struct _displayio_area_t displayio_area_t;

struct _displayio_area_t {
    int16_t x1;
    int16_t y1;
    int16_t x2; // Second point is exclusive.
    int16_t y2;
    const displayio_area_t *next; // Next area in the linked list.
};

typedef struct {
    uint16_t x;
    uint16_t y;
    int8_t dx;
    int8_t dy;
    uint8_t scale;
    uint16_t width;
    uint16_t height;
    bool mirror_x;
    bool mirror_y;
    bool transpose_xy;
} displayio_buffer_transform_t;

extern displayio_buffer_transform_t null_transform;

bool displayio_area_empty(const displayio_area_t *a);
void displayio_area_copy_coords(const displayio_area_t *src, displayio_area_t *dest);
void displayio_area_canon(displayio_area_t *a);
void displayio_area_union(const displayio_area_t *a,
    const displayio_area_t *b,
    displayio_area_t *u);
void displayio_area_copy(const displayio_area_t *src, displayio_area_t *dst);
void displayio_area_scale(displayio_area_t *area, uint16_t scale);
void displayio_area_shift(displayio_area_t *area, int16_t dx, int16_t dy);
bool displayio_area_compute_overlap(const displayio_area_t *a,
    const displayio_area_t *b,
    displayio_area_t *overlap);
uint16_t displayio_area_width(const displayio_area_t *area);
uint16_t displayio_area_height(const displayio_area_t *area);
uint32_t displayio_area_size(const displayio_area_t *area);
bool displayio_area_equal(const displayio_area_t *a, const displayio_area_t *b);
void displayio_area_transform_within(bool mirror_x, bool mirror_y, bool transpose_xy,
    const displayio_area_t *original,
    const displayio_area_t *whole,
    displayio_area_t *transformed);

#endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_AREA_H


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

//
// Scenario2.xaml.h
// Declaration of the Scenario2 class
//

#pragma once

#include "pch.h"
#include "Scenario2.g.h"
#include "MainPage.xaml.h"

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Networking::Sockets;
using namespace Windows::Storage::Streams;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::Web;

namespace SDKTemplate
{
    namespace WebSocket
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
    	[Windows::Foundation::Metadata::WebHostHidden]
        public ref class Scenario2 sealed
        {
        public:
            Scenario2();

        protected:
            virtual void OnNavigatedTo(NavigationEventArgs^ e) override;
        private:
            ~Scenario2();

    		MainPage^ rootPage;
            StreamWebSocket^ streamWebSocket;
            IBuffer^ readBuffer;
            IBuffer^ sendBuffer;
            int bytesReceived;
            int dataSent;
            CRITICAL_SECTION criticalSection;

            void Start_Click(Object^ sender, RoutedEventArgs^ e);
            void Stop_Click(Object^ sender, RoutedEventArgs^ e);
            void Scenario2ReceiveData();
            void Scenario2SendData();
            void Scenario2Closed(IWebSocket^ sender, WebSocketClosedEventArgs^ args);
            void HandleException(Exception^ exception);
            void MarshalText(TextBox^ output, String^ value);
            void MarshalText(TextBox^ output, String^ value, bool append);
        };
    }
}


text:
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["children", "shadow", "itemsLayout"];
import { createScopedElement } from "../../lib/jsxRuntime";
import * as React from "react";
import { getClassName } from "../../helpers/getClassName";
import { classNames } from "../../lib/classNames";
import { usePlatform } from "../../hooks/usePlatform";
import "./Tabbar.css";

/**
 * @see https://vkcom.github.io/VKUI/#/Tabbar
 */
export var Tabbar = function Tabbar(_ref) {
  var children = _ref.children,
      _ref$shadow = _ref.shadow,
      shadow = _ref$shadow === void 0 ? true : _ref$shadow,
      itemsLayout = _ref.itemsLayout,
      restProps = _objectWithoutProperties(_ref, _excluded);

  var platform = usePlatform();

  var getItemsLayout = function getItemsLayout() {
    switch (itemsLayout) {
      case "horizontal":
      case "vertical":
        return itemsLayout;

      default:
        return React.Children.count(children) > 2 ? "vertical" : "horizontal";
    }
  };

  return createScopedElement("div", _extends({
    // eslint-disable-next-line vkui/no-object-expression-in-arguments
    vkuiClass: classNames(getClassName("Tabbar", platform), "Tabbar--l-".concat(getItemsLayout()), {
      "Tabbar--shadow": shadow
    })
  }, restProps), createScopedElement("div", {
    vkuiClass: "Tabbar__in"
  }, children));
};
//# sourceMappingURL=Tabbar.js.map


text:
struct deps_entry_t
{
    pal::string_t library_type;
    pal::string_t library_name;
    pal::string_t library_version;
    pal::string_t library_hash;
    pal::string_t asset_type;
    pal::string_t asset_name;
    pal::string_t relative_path;
    bool is_serviceable;

    // Given a "base" dir, yield the relative path in the package layout.
    bool to_full_path(const pal::string_t& root, pal::string_t* str) const;

    // Given a "base" dir, yield the relative path in the package layout only if
    // the hash matches contents of the hash file.
    bool to_hash_matched_path(const pal::string_t& root, pal::string_t* str) const;
};

// Probe paths to be resolved for ordering
struct probe_paths_t
{
    pal::string_t tpa;
    pal::string_t native;
    pal::string_t culture;
};

class deps_resolver_t
{
public:
    deps_resolver_t(const arguments_t& args)
        : m_svc(args.dotnet_servicing)
    {
        m_deps_valid = parse_deps_file(args);
    }

    bool valid() { return m_deps_valid; }

    bool resolve_probe_paths(
      const pal::string_t& app_dir,
      const pal::string_t& package_dir,
      const pal::string_t& package_cache_dir,
      const pal::string_t& clr_dir,
      probe_paths_t* probe_paths);

private:

    bool load();

    bool parse_deps_file(const arguments_t& args);

    // Resolve order for TPA lookup.
    void resolve_tpa_list(
        const pal::string_t& app_dir,
        const pal::string_t& package_dir,
        const pal::string_t& package_cache_dir,
        const pal::string_t& clr_dir,
        pal::string_t* output);

    // Resolve order for culture and native DLL lookup.
    void resolve_probe_dirs(
        const pal::string_t& asset_type,
        const pal::string_t& app_dir,
        const pal::string_t& package_dir,
        const pal::string_t& package_cache_dir,
        const pal::string_t& clr_dir,
        pal::string_t* output);

    // Populate local assemblies from app_dir listing.
    void get_local_assemblies(const pal::string_t& dir);

    // Servicing index to resolve serviced assembly paths.
    servicing_index_t m_svc;

    // Map of simple name -> full path of local assemblies populated in priority
    // order of their extensions.
    std::unordered_map<pal::string_t, pal::string_t> m_local_assemblies;

    // Entries in the dep file
    std::vector<deps_entry_t> m_deps_entries;

    // The dep file path
    pal::string_t m_deps_path;

    // Is the deps file valid
    bool m_deps_valid;
};

#endif // DEPS_RESOLVER_H


text:
(function() {
    'use strict';

    angular
        .module('falconcmsApp')
        .config(translationConfig);

    translationConfig.$inject = ['$translateProvider', 'tmhDynamicLocaleProvider'];

    function translationConfig($translateProvider, tmhDynamicLocaleProvider) {
        // Initialize angular-translate
        $translateProvider.useLoader('$translatePartialLoader', {
            urlTemplate: 'i18n/{lang}/{part}.json'
        });

        $translateProvider.preferredLanguage('en');
        $translateProvider.useStorage('translationStorageProvider');
        $translateProvider.useSanitizeValueStrategy('escaped');
        $translateProvider.addInterpolation('$translateMessageFormatInterpolation');

        tmhDynamicLocaleProvider.localeLocationPattern('i18n/angular-locale_{{locale}}.js');
        tmhDynamicLocaleProvider.useCookieStorage();
        tmhDynamicLocaleProvider.storageKey('NG_TRANSLATE_LANG_KEY');
    }
})();


text:
//---------------------------------------------------------------------------
//	Greenplum Database
//	Copyright (C) 2008 Greenplum, Inc.
//
//	@filename:
//		types.h
//
//	@doc:
//		Type definitions for gpos to avoid using native types directly;
//
//		TODO: 03/15/2008; the seletion of basic types which then
//		get mapped to internal types should be done by autoconf or other
//		external tools; for the time being these are hard-coded; cpl asserts
//		are used to make sure things are failing if compiled with a different
//		compiler.
//---------------------------------------------------------------------------
#ifndef GPOS_types_H
#define GPOS_types_H

#include <limits.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>

#include <iostream>

#include "gpos/assert.h"

#define GPOS_SIZEOF(x) ((gpos::ULONG) sizeof(x))
#define GPOS_ARRAY_SIZE(x) (GPOS_SIZEOF(x) / GPOS_SIZEOF(x[0]))
#define GPOS_OFFSET(T, M) ((gpos::ULONG)(SIZE_T) & (((T *) 0x1)->M) - 1)

/* wide character string literate */
#define GPOS_WSZ_LIT(x) L##x

namespace gpos
{
// Basic types to be used instead of built-ins
// Add types as needed;

typedef unsigned char BYTE;
typedef char CHAR;
// ignore signed char for the moment

// wide character type
typedef wchar_t WCHAR;

typedef bool BOOL;

// numeric types

typedef size_t SIZE_T;
typedef ssize_t SSIZE_T;
typedef mode_t MODE_T;

// define ULONG,ULLONG as types which implement standard's
// requirements for ULONG_MAX and ULLONG_MAX; eliminate standard's slack
// by fixed sizes rather than min requirements

typedef uint32_t ULONG;
GPOS_CPL_ASSERT(4 == sizeof(ULONG));
enum
{
	ulong_max = ((::gpos::ULONG) -1)
};

typedef uint64_t ULLONG;
GPOS_CPL_ASSERT(8 == sizeof(ULLONG));
enum
{
	ullong_max = ((::gpos::ULLONG) -1)
};

typedef uintptr_t ULONG_PTR;
#define ULONG_PTR_MAX (gpos::ullong_max)

typedef uint16_t USINT;
typedef int16_t SINT;
typedef int32_t INT;
typedef int64_t LINT;
typedef intptr_t INT_PTR;

GPOS_CPL_ASSERT(2 == sizeof(USINT));
GPOS_CPL_ASSERT(2 == sizeof(SINT));
GPOS_CPL_ASSERT(4 == sizeof(INT));
GPOS_CPL_ASSERT(8 == sizeof(LINT));

enum
{
	int_max = ((::gpos::INT)(gpos::ulong_max >> 1)),
	int_min = (-gpos::int_max - 1)
};

enum
{
	lint_max = ((::gpos::LINT)(gpos::ullong_max >> 1)),
	lint_min = (-gpos::lint_max - 1)
};

enum
{
	usint_max = ((::gpos::USINT) -1)
};

enum
{
	sint_max = ((::gpos::SINT)(gpos::usint_max >> 1)),
	sint_min = (-gpos::sint_max - 1)
};

typedef double DOUBLE;

// holds for all platforms
GPOS_CPL_ASSERT(sizeof(ULONG_PTR) == sizeof(void *));

// variadic parameter list type
typedef va_list VA_LIST;

// enum for results on OS level (instead of using a global error variable)
enum GPOS_RESULT
{
	GPOS_OK = 0,

	GPOS_FAILED = 1,
	GPOS_OOM = 2,
	GPOS_NOT_FOUND = 3,
	GPOS_TIMEOUT = 4
};

// enum for locale encoding
enum ELocale
{
	ELocInvalid,  // invalid key for hashtable iteration
	ElocEnUS_Utf8,
	ElocGeDE_Utf8,

	ElocSentinel
};
}  // namespace gpos

#endif	// !GPOS_types_H

// EOF


text:
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';

import { Configuration } from './configuration';
import { Submission } from './submission';

import { ConfigurationsService } from './configurations.service';

@Component( {
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

    constructor( private configurationsService: ConfigurationsService ) { }

    ngOnInit(): void {
        this.fetchConfigs();

    }

    setRows( rows: Submission[] ) {
        this.rows = rows;
        if ( rows.length > 0 ) {
            this.currentConfig = rows[0].config.clone();
            this.selected = [rows[0]];
        }
    }

    fetchConfigs(): void {
        this.configurationsService.getConfigurations().subscribe( rows => {
            this.setRows( rows );
        });
    }

    title = 'Postsai Commit Permissions';

    currentConfig = new Configuration( "- .* .* .* .* .*", "comment" );

    rows: Submission[];

    columns = [
        { prop: 'changetime', name: 'Activation Date', sortable: false },
        { prop: 'username', name: 'User', sortable: false },
        { prop: 'config.changeComment', name: 'Comment', sortable: false }
    ];

    selected: Submission[] = [];

    onSelect( event ) {
        if ( this.selected.length > 0 )
            this.currentConfig = this.selected[0].config.clone();
    }

    doSubmit( event ) {
        if ( this.rows.length > 0 && this.currentConfig.sameAs( this.rows[0].config ) )
            alert( "Not saved. Configuration is already active." );
        else if ( confirm( "Save new configuration?" ) ) {

            let newestInLast: number = ( this.rows.length > 0 ) ? this.rows[0].timestamp : 42;
            let added = this.currentConfig.clone();
            this.configurationsService.saveConfig( added ).subscribe( (result) => {
                this.configurationsService.getConfigurations().subscribe( rows => {
	                this.setRows( rows );
	                let newestInThis: number = ( this.rows.length > 1 ) ? this.rows[1].timestamp : 42;
	                if ( newestInThis != newestInLast )
	                    alert( "Changes have been submitted concurrently. Please revisit the configuration." );
	                });
				},
                err => {
					console.log(err);
                    alert( "Could not save configuration.\n\nMessage returned by server: '" + err.toString() + "'" );
                });
        }
    }
}


text:
using Newtonsoft.Json;

namespace AzureFromTheTrenches.Commanding.Http.Implementation
{
    internal class JsonCommandSerializer : IHttpCommandSerializer
    {
        public string Serialize(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public T Deserialize<T>(string serializedRepresentation)
        {
            return JsonConvert.DeserializeObject<T>(serializedRepresentation);
        }

        public string MimeType => "application/json";
    }
}


text:
require 'active_record'
require 'so2db/extensions'
require 'foreigner'

module SO2DB

  module FKHelper

    def add_fk(from_table, to_table, options={})
      begin
      AddForeignKeyMigration.new(from_table, to_table, options).up
      rescue
	puts $!.inspect
	#puts $@
        s = "Error creating foreign key from #{from_table} to #{to_table}"
        s << " on column #{options[:column]}" if options.has_key? :column
        puts s
      end
    end

  end

  class AddForeignKeyMigration < ActiveRecord::Migration

    def initialize(from_table, to_table, options)
      @from_table = from_table
      @to_table = to_table
      @options = options
    end

    def up
      add_foreign_key(@from_table, @to_table, @options)
    end

  end

  class CreateBasicTables < ActiveRecord::Migration

    def up
      create_table :badges do |t|
        t.integer :user_id
        t.string :name, :limit => 50
        t.timestamp :date
        t.integer :class
        t.boolean :tag_based
      end

      create_table :comments do |t|
        t.integer :post_id
        t.integer :score
        t.text :text
        t.timestamp :creation_date
        t.string :user_display_name, :limit => 30
        t.integer :user_id
      end

      create_table :posts do |t|
        t.integer :post_type_id
        t.integer :parent_id
        t.integer :accepted_answer_id
        t.timestamp :creation_date
        t.integer :score
        t.integer :view_count
        t.text :body
        t.integer :owner_user_id
        t.text :owner_display_name
        t.integer :last_editor_user_id
        t.string :last_editor_display_name, :limit => 40
        t.timestamp :last_edit_date
        t.timestamp :last_activity_date
        t.timestamp :community_owned_date
        t.timestamp :closed_date
        t.text :title
        t.string :tags, :limit => 150
        t.integer :answer_count
        t.integer :comment_count
        t.integer :favorite_count
      end

      create_table :post_history do |t|
        t.integer :post_history_type_id
        t.integer :post_id
        t.uuid :revision_guid
        t.timestamp :creation_date
        t.integer :user_id
        t.string :user_display_name, :limit => 40
        t.text :comment
        t.text :text
        t.integer :close_reason_id
      end

      create_table :users do |t|
        t.integer :reputation
        t.timestamp :creation_date
        t.text :display_name
        t.string :email_hash, :limit => 32
        t.timestamp :last_access_date
        t.string :website_url, :limit => 300
        t.string :location, :limit => 200
        t.integer :age
        t.text :about_me
        t.integer :views
        t.integer :up_votes
        t.integer :down_votes
        t.integer :account_id
      end

      create_table :votes do |t|
        #t.primary_key :id
        t.integer :post_id
        t.integer :vote_type_id
        t.timestamp :creation_date
        t.integer :user_id
        t.integer :bounty_amount
      end

      create_table :post_links do |t|
        t.date :creation_date
        t.integer :post_id
        t.integer :related_post_id
        t.integer :link_type_id
      end

      create_table :tags do |t|
        t.text :tag_name
        t.integer :count
        t.integer :excerpt_post_id
        t.integer :wiki_post_id
      end
    end

    def down
      [:votes, :badges, :comments, :post_history, :posts, :users, :post_links, :tags].each do |t|
        drop_table t
      end
    end

  end

  class CreateRelationships
    include FKHelper

    def up
      add_fk(:badges, :users)
      add_fk(:comments, :posts)
      add_fk(:comments, :users)
      add_fk(:posts, :posts, column: 'parent_id')

      # The following relationship is currently suspect, see
      # http://meta.stackoverflow.com/questions/131975/what-are-the-posttypeids-in-the-2011-12-data-dump
      add_fk(:posts, :posts, column: 'accepted_answer_id')

      add_fk(:posts, :users, column: 'owner_user_id')
      add_fk(:posts, :users, column: 'last_editor_user_id')
      add_fk(:post_history, :posts)
      add_fk(:post_history, :users)

      # In my experience, the following is also suspect
      add_fk(:votes, :posts)

      add_fk(:votes, :users)
    end

  end

  class CreateOptionals < ActiveRecord::Migration

    def up
      create_post_types
      create_post_history_types
      create_close_reasons
      create_vote_types
    end

    def create_post_types
      create_table :post_types do |t|
        #t.primary_key :id
        t.string :type_name, :limit => 24
      end

      { 1 => "Question",
        2 => "Answer",
        3 => "Wiki",
        4 => "TagWikiExcerpt",
        5 => "TagWiki",
        6 => "ModeratorNomination",
        7 => "WikiPlaceholder",
        8 => "PrivilegeWiki"
      }.each do |k,v|
        p = Models::PostType.new
        p.id = k
        p.type_name = v
        p.save
      end
    end

    def create_post_history_types
      create_table :post_history_types do |t|
        #t.primary_key :id
        t.string :name, :limit => 50
      end

      { 1  => "Initial Title",
        2  => "Initial Body",
        3  => "Initial Tags",
        4  => "Edit Title",
        5  => "Edit Body",
        6  => "Edit Tags",
        7  => "Rollback Title",
        8  => "Rollback Body",
        9  => "Rollback Tags",
        10 => "Post Closed",
        11 => "Post Reopened",
        12 => "Post Deleted",
        13 => "Post Undeleted",
        14 => "Post Locked",
        15 => "Post Unlocked",
        16 => "Community Owned",
        17 => "Post Migrated",
        18 => "Question Merged",
        19 => "Question Protected",
        20 => "Question Unprotected",
        22 => "Question Unmerged",
        24 => "Suggested Edit Applied",
        25 => "Post Tweeted",
        31 => "Discussion moved to chat",
        33 => "Post Notice Added",
        34 => "Post Notice Removed",
        35 => "Post Migrated Away",
        36 => "Post Migrated Here",
        37 => "Post Merge Source",
        38 => "Post Merge Destination"
      }.each do |k,v|
        p = Models::PostHistoryType.new
        p.id = k
        p.name = v
        p.save
      end
    end

    def create_close_reasons
      create_table :close_reasons do |t|
        #t.primary_key :id
        t.string :name, :limit => 50
      end

      { 1 => "Exact duplicate",
        2 => "off-topic",
        3 => "subjective",
        4 => "not a real question",
        7 => "too localized",
        10 => "General reference",
        20 => "Noise or pointless"
      }.each do |k,v|
        c = Models::CloseReason.new
        c.id = k
        c.name = v
        c.save
      end
    end

    def create_vote_types
      create_table :vote_types do |t|
        #t.primary_key :id
        t.string :name, :limit => 50
      end

      { 1 => "AcceptedByOriginator",
        2 =>"UpMod",
        3 => "DownMod",
        4 =>"Offensive",
        5 =>"Favorite",
        6 =>"Close",
        7 =>"Reopen",
        8 =>"BountyStart",
        9 =>"BountyClose",
        10 =>"Deletion",
        11 =>"Undeletion",
        12 =>"Spam",
        15 =>"ModeratorReview",
        16 =>"ApproveEditSuggestion"
      }.each do |k,v|
        vt = Models::VoteType.new
        vt.id = k
        vt.name = v
        vt.save
      end
    end

  end

  class CreateOptionalRelationships < ActiveRecord::Migration
    include FKHelper

    def up
      add_fk(:posts, :post_types)
      add_fk(:post_history, :post_history_types)
      add_fk(:post_history, :close_reasons)
      add_fk(:votes, :vote_types)
    end
  end

end


text:
import numpy as np
from scipy import signal
#import layout
import matplotlib.pylab as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.mplot3d import Axes3D
import os

#1D
dynamics = np.genfromtxt("total_excited_fraction.txt")
structure = np.genfromtxt("avg_struct.txt")

dyn_norm = (dynamics - np.mean(dynamics))/np.std(dynamics)
struct_norm = (structure - np.mean(structure))/(np.std(structure)*len(structure)*len(structure))

rand1 = np.random.rand(4000)
rand1_norm = (rand1 - np.mean(rand1))/np.std(rand1)

corr = np.correlate(np.ndarray.flatten(dyn_norm),np.ndarray.flatten(struct_norm),"full")
corr1= np.correlate(rand1_norm,np.ndarray.flatten(structure),"same")

plt.figure()
plt.plot(corr,'g')
plt.show()

#2D
rand2 = np.random.rand(200,200)
rand2_norm = (rand2 - np.mean(rand2))/np.std(rand2)

corr2D = signal.correlate2d(dyn_norm, struct_norm,"same")
corr2D2 = signal.correlate2d(struct_norm, rand2_norm,"same")

hf = plt.figure()
ha = hf.add_subplot(111,projection = "3d")
x = range(200)
y=x
X, Y = np.meshgrid(x, y)  # `plot_surface` expects `x` and `y` data to be 2D
ha.plot_surface(X, Y, corr2D)

plt.show()


text:
from django import template
from django.template.defaultfilters import stringfilter
from rest_framework.utils.formatting import markup_description

register = template.Library()

@register.filter(name='markdown')
@stringfilter
def markdown(value):
    return markup_description(value)


text:
from __future__ import print_function

import os

import pyos
import pyos.exceptions as exc

pyos.set_setting("identity_type", "rackspace")
creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
pyos.set_credential_file(creds_file)
dns = pyos.cloud_dns

PAGE_SIZE = 10
count = 0

def print_domains(domains):
    for domain in domains:
        print("Domain:", domain.name)
        print("  email:", domain.emailAddress)
        print("  created:", domain.created)
        print()

domains = dns.list(limit=PAGE_SIZE)
count += len(domains)
print_domains(domains)

# Loop until all domains are printed
while True:
    try:
        domains = dns.list_next_page()
        count += len(domains)
    except exc.NoMoreResults:
        break
    print_domains(domains)

print("There were a total of %s domain(s)." % count)


text:
begin
  require 'builder'
rescue LoadError
  gem 'builder'
  require 'builder'
end

module Cucumber
  module Formatter
    class Junit < Cucumber::Ast::Visitor

      def initialize(step_mother, io, options)
        super(step_mother)
        raise "You *must* specify --out DIR for the junit formatter" unless String === io && File.directory?(io)
        @reportdir = io
        @options = options
      end

      def visit_feature(feature)
        @failures = @errors = @tests = 0
        @builder = Builder::XmlMarkup.new( :indent => 2 )
        super

        @testsuite = Builder::XmlMarkup.new( :indent => 2 )
        @testsuite.instruct!
        @testsuite.testsuite(
          :failures => @failures,
          :errors => @errors,
          :tests => @tests,
          :name => @feature_name ) do
          @testsuite << @builder.target!
        end

        basename = File.basename(feature.file)[0...-File.extname(feature.file).length]
        feature_filename = File.join(@reportdir, "TEST-#{basename}.xml")
        File.open(feature_filename, 'w') { |file| file.write(@testsuite.target!) }
      end

      def visit_feature_name(name)
        lines = name.split(/\r?\n/)
        @feature_name = lines[0].sub(/Feature\:/, '').strip
      end

      def visit_scenario_name(keyword, name, file_colon_line, source_indent)
        @scenario = name
      end

      def visit_steps(steps)
        @steps_failed = false
        super
        @failures += 1 if @steps_failed
        @tests += 1
      end

      def visit_step_result(keyword, step_match, multiline_arg, status, exception, source_indent, background)
        step_name = keyword + " " + step_match.format_args(lambda{|param| "*#{param}*"})
        @builder.testcase(:classname => "#{@feature_name}.#{@scenario}", :name => step_name) do
          if status != :passed
            @builder.failure(:message => step_name) do
              @builder.text!(format_exception(exception)) if exception
            end
            @steps_failed = true
          end
        end
      end

      private

      def format_exception(exception)
        (["#{exception.message} (#{exception.class})"] + exception.backtrace).join("\n")
      end
    end

  end
end


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchlib.rankingexpression;

import com.yahoo.searchlib.rankingexpression.evaluation.Context;
import com.yahoo.searchlib.rankingexpression.evaluation.Value;
import com.yahoo.searchlib.rankingexpression.parser.ParseException;
import com.yahoo.searchlib.rankingexpression.parser.RankingExpressionParser;
import com.yahoo.searchlib.rankingexpression.parser.TokenMgrException;
import com.yahoo.searchlib.rankingexpression.rule.ExpressionNode;
import com.yahoo.searchlib.rankingexpression.rule.SerializationContext;
import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.evaluation.TypeContext;
import com.yahoo.text.Text;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Map;

/**
 *
A ranking expression. Ranking expressions are used to calculate a rank score for a searched instance from a set of
 * rank features.

 *
 *
A ranking expression wraps a expression node tree and may also optionally have a name.

 *
 *
The identity of a ranking expression is decided by both its name and expression tree. Two expressions which
 * looks the same in string form are the same.

 *
 *
Simple usage

try {
    MapContext context = new MapContext();
    context.put("one", 1d);
    RankingExpression expression = new RankingExpression("10*if(i>35,if(i>one,if(i>=670,4,8),if(i>8000,5,3)),if(i==478,90,91))");
    double result = expression.evaluate(context);
   }
catch (ParseException e) {
    throw new RuntimeException(e);
}

 *
 *
Or, usage optimized for repeated evaluation of the same expression

// Members in a class living across multiple evaluations
RankingExpression expression;
ArrayContext contextPrototype;

...

// Initialization of the above members (once)
// Create reusable, gbdt optimized expression and context.
// The expression is multithread-safe while the context created is not
try {
    RankingExpression expression = new RankingExpression("10*if(i>35,if(i>one,if(i>=670,4,8),if(i>8000,5,3)),if(i==478,90,91))");
    ArrayContext contextPrototype = new ArrayContext(expression);
    ExpressionOptimizer optimizer = new ExpressionOptimizer(); // Increases evaluation speed of gbdt form expressions by 3-4x
    OptimizationReport triviaAboutTheOptimization = optimizer.optimize(expression, contextPrototype);
}
catch (ParseException e) {
    throw new RuntimeException(e);
}

...

// Execution (many)
context = contextPrototype.clone(); // If evaluation is multithreaded - skip this if execution is single-threaded
context.put("one",1d);
double result = expression.evaluate(context);

 *
 * @author Simon Thoresen Hult
 * @author bratseth
 */
public class RankingExpression implements Serializable {

    private String name = "";
    private ExpressionNode root;
    private final static String RANKEXPRESSION = "rankingExpression(";
    private final static String RANKINGSCRIPT = ").rankingScript";
    private final static String EXPRESSION_NAME = ").expressionName";

    /** Creates an anonymous ranking expression by consuming from the reader */
    public RankingExpression(Reader reader) throws ParseException {
        root = parse(reader);
    }

    /**
     * Creates a new ranking expression by consuming from the reader
     *
     * @param name the name of the ranking expression
     * @param reader the reader that contains the string to parse.
     * @throws ParseException if the string could not be parsed.
     */
    public RankingExpression(String name, Reader reader) throws ParseException {
        this.name = name;
        root = parse(reader);
    }

    /**
     * Creates a new ranking expression by consuming from the reader
     *
     * @param name the name of the ranking expression
     * @param expression the expression to parse.
     * @throws ParseException if the string could not be parsed.
     */
    public RankingExpression(String name, String expression) throws ParseException {
        try {
            this.name = name;
            if (expression == null || expression.length() == 0) {
                throw new IllegalArgumentException("Empty ranking expressions are not allowed");
            }
            root = parse(new StringReader(expression));
        }
        catch (ParseException e) {
            ParseException p = new ParseException("Could not parse '" + Text.truncate(expression, 50) + "'");
            p.initCause(e);
            throw p;
        }
    }

    /**
     * Creates a ranking expression from a string
     *
     * @param expression The reader that contains the string to parse.
     * @throws ParseException if the string could not be parsed.
     */
    public RankingExpression(String expression) throws ParseException {
        this("", expression);
    }

    /**
     * Creates a ranking expression from a file. For convenience, the file.getName() up to any dot becomes the name of
     * this expression.
     *
     * @param file the name of the file whose content to parse.
     * @throws ParseException           if the string could not be parsed.
     * @throws IllegalArgumentException if the file could not be found
     */
    public RankingExpression(File file) throws ParseException {
        try {
            name = file.getName().split("\\.")[0];
            root = parse(new FileReader(file));
        }
        catch (FileNotFoundException e) {
            throw new IllegalArgumentException("Could not create a ranking expression", e);
        }
    }

    /**
     * Creates a named ranking expression from an expression root node.
     */
    public RankingExpression(String name, ExpressionNode root) {
        this.name = name;
        this.root = root;
    }

    /**
     * Creates a ranking expression from an expression root node.
     *
     * @param root The root node.
     */
    public RankingExpression(ExpressionNode root) {
        this.root = root;
    }

    /**
     * Parses the content of the reader object as an expression string.
     *
     * @param reader A reader object that contains an expression string.
     * @return An expression node that corresponds to the given string.
     * @throws ParseException if the string could not be parsed.
     */
    private static ExpressionNode parse(Reader reader) throws ParseException {
        try {
            return new RankingExpressionParser(reader).rankingExpression();
        }
        catch (TokenMgrException e) {
            throw new ParseException(e.getMessage());
        }
    }

    /** Returns a deep copy of this expression */
    public RankingExpression copy() {
        try {
            return new RankingExpression(name, root.toString());
        }
        catch (ParseException e) {
            throw new RuntimeException("Programming error: Could not parse serialized expression", e);
        }
    }

    /**
     * Returns the name of this ranking expression, or "" if no name is set.
     *
     * @return The name of this expression.
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the name of this ranking expression.
     *
     * @param name The name to set.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Returns the root of the expression tree of this expression.
     *
     * @return The root node.
     */
    public ExpressionNode getRoot() {
        return root;
    }

    /**
     * Sets the root of the expression tree of this expression.
     *
     * @param root The root node to set.
     */
    public void setRoot(ExpressionNode root) {
        this.root = root;
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof RankingExpression && toString().equals(obj.toString());
    }

    @Override
    public String toString() {
        if ("".equals(name)) {
            return root.toString();
        } else {
            return name + ": " + root.toString();
        }
    }

    /**
     * Creates the necessary rank properties required to implement this expression.
     *
     * @param context context for serialization
     * @return a list of named rank properties required to implement this expression
     */
    public Map<String, String> getRankProperties(SerializationContext context) {
        Deque<String> path = new LinkedList<>();
        String serializedRoot = root.toString(new StringBuilder(), context, path, null).toString();
        Map<String, String> serializedExpressions = context.serializedFunctions();
        serializedExpressions.put(propertyName(name), serializedRoot);
        return serializedExpressions;
    }

    /**
     * Returns the rank-property name for a given expression name.
     *
     * @param expressionName the expression name to mangle.
     * @return the property name.
     */
    public static String propertyName(String expressionName) {
        return RANKEXPRESSION + expressionName + RANKINGSCRIPT;
    }
    public static String propertyExpressionName(String expressionName) {
        return RANKEXPRESSION + expressionName + EXPRESSION_NAME;
    }
    public static String extractScriptName(String propertyName) {
        if (propertyName.startsWith(RANKEXPRESSION) && propertyName.endsWith(RANKINGSCRIPT)) {
            return propertyName.substring(RANKEXPRESSION.length(), propertyName.length() - RANKINGSCRIPT.length());
        }
        return null;
    }

    /**
     * Validates the type correctness of the given expression with the given context and
     * returns the type this expression will produce from the given type context
     *
     * @throws IllegalArgumentException if this expression is not type correct in this context
     */
    public TensorType type(TypeContext<Reference> context) {
        return root.type(context);
    }

    /**
     * Returns the value of evaluating this expression over the given context.
     *
     * @param context The variable bindings to use for this evaluation.
     * @return the evaluation result.
     * @throws IllegalArgumentException if there are variables which are not bound in the given map
     */
    public Value evaluate(Context context) {
        return root.evaluate(context);
    }

    /**
     * Creates a ranking expression from a string
     *
     * @throws IllegalArgumentException if the string is not a valid ranking expression
     */
    public static RankingExpression from(String expression) {
        try {
            return new RankingExpression(expression);
        }
        catch (ParseException e) {
            throw new IllegalStateException(e);
        }
    }

}


text:
package controller

import play.api.mvc._

object Application extends Controller
{
	def index = Action
	{
		Ok(
			view.html.index(
				name = "Play Tmpltr",
				repository = "https://github.com/Taig/Play-Tmpltr",
				source = "https://github.com/Taig/Play-Tmpltr/tree/master",
				documentation = "https://github.com/Taig/Play-Tmpltr/tree/master/documentation",
				scalaDoc = "http://taig.github.io/Play-Tmpltr/scaladoc/#com.taig.tmpltr.package"
			)
		)
	}
}


text:
var restify = require('restify');

var redis = require("redis");
var redisClient = redis.createClient();

var wxconfig = require('../config.js').wx;
var appid = wxconfig.appid; // 微信 apid
var appsecret = wxconfig.appsecret; // 微信 appsecret

var wxBaseHost = 'https://api.weixin.qq.com';
// var tokenURI = wxBaseHost + '/cgi-bin/token';

var tokenOptions = {
	grant_type: 'client_credential',
	appid: appid,
	secret: appsecret
};

// -----------------------------------------------------------------

var client = restify.createJsonClient({
  url: 'https://api.weixin.qq.com',
});

// -----------------------------------------------------------------

function log(info) {
  console.log("-----------------------------------");
  var length = arguments.length;
  for (var i = 0; i < length; i++) {
    console.log(arguments[i]);
  }
};

// -----------------------------------------------------------------

function WX() {
};
module.exports = WX;

// -----------------------------------------------------------------

WX.prototype.getAccessToken = function(callback) {
	log("getAccessToken: Hi , I am called.")
	var tokenURI = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appid + '&secret=' + appsecret;
	log(tokenURI)
	client.get(tokenURI, function(err, req, res, obj) {
		if(err) {
			log("getAccessToken: get access token error", err);
			callback("getAccessToken: get access token error", err);
		} else {
			var access_token = obj.access_token;
			var expires_in = obj.expires_in;
			callback(err, {access_token: access_token, expires_in: expires_in});
		}
	})
}

// -----------------------------------------------------------------
/**
 * 获取用户信息
 * @param  {json}   options  需要access_token 和openid
 * @param  {json} callback 返回用户信息
 */
WX.prototype.getUserInfo = function(options, callback) {
	log("getUserInfo: Hi, I am called.")
	if(!options
		|| !options.hasOwnProperty("access_token")
		|| !options.hasOwnProperty("openid")) {
		log("getUserInfo: options illegal", options);
		callback("getUserInfo: options illegal", null);
	} else {
		var self = this;
		log("options: ", options)
		var access_token = options.access_token;
		var openid = options.openid;

		log("start get user information")
		var userURI = wxBaseHost + '/cgi-bin/user/info?access_token=' + access_token + '&openid=' + openid ;
		// log(userURI)

		client.get(userURI, function(err, req, res, obj) {
			if(err) {
				log("getUserInfo: get user info error", err);
				callback(err, null);
			} else {
				log("getUserInfo: get user info succeed.");

				if(obj.hasOwnProperty("openid")){
					callback(null, {user: obj});
				} else if(obj.hasOwnProperty("errcode") && (obj.errcode === 40001) || obj.errcode === 42001 || obj.errcode === 40014){
					log("getUserInfo: get user info about error for user does not has openid", obj);
					setTimeout(function() {
						self.getSaveToken();
					}, 5000);
					callback(obj, null);
				} else {
					log("getUserInfo: unknown error", obj);
					callback("getUserInfo: unknown error", null);
				}
			}
		})
	}
}

// -----------------------------------------------------------------
/**
 * redis 数据库获取 access_token 获取用户信息,需要提供token
 */
WX.prototype.handleUser = function(options, callback) {
	log("handleUser: Hi I am called.");
	var self = this;
	if(!options
		|| !options.hasOwnProperty("openid")) {
		log("handleUser: options illegal", err);
		callback(err, null);
	} else {
		redisClient.hmget("token", "access_token", function(err, access_token) {
			if(err) {
				log("handleUser: get access_token from redis error", err);
				self.getSaveToken(); // 重新获取token
				callback("andleUser: get access_token from redis error", null);
			} else {
				log("handleUser: get access_token succeed");

				var userOptions = {
					access_token: access_token[0],
					openid: options.openid
				}

				self.getUserInfo(userOptions, function(err, user) {
					if(err) {
						log("handleUser: get user information error", err);
						call(err, null);
					} else {
						log("handleUser: get user succeed.");
						callback(null, user);
					}
				})
			}
		})
	}
}

// -----------------------------------------------------------------
// 存储access_token到数据库
WX.prototype.saveToken = function(options, callback) {
	var self = this;
	log("saveToken: Hi I am called.");
	var access_token = options.access_token;
	var expires_in = options.expires_in;
	var update_time = new Date();
	var tokenArray = [
	"token",
	"access_token",
	access_token,
	'expires_in',
	expires_in,
	'update_time',
	update_time
  ];
  log(tokenArray)
	redisClient.hmset(tokenArray, function(err) {
		if(err) {
			log("saveToken: save token error", tokenArray);
			callback(err);
		} else {
			log("saveToken: save token succeed");
			callback(null);
		}
	})
}

// -----------------------------------------------------------------
// access_token 维护函数,写得有些乱
WX.prototype.maintainToken = function() {
	log("maintainToken: I am called.");

	var self = this;

	redisClient.hgetall("token", function(err, token) {
		if(err) {
			log("maintainToken: no token exists , get new token");
			setTimeout(function() {
				self.getAccessToken(function(err, tokenObj) {
					if(err) {
						log("maintainToken: get access_token error", err);
						// 失败 5秒后继续维护token
						setTimeout(function() {
							self.maintainToken();
						}, 5000);
					} else {
						self.saveToken(tokenObj, function(err) {
							if(err) {
								log("maintainToken: save token obj error", err);
								setTimeout(function() {
									self.saveToken(tokenObj, function(err) {
										if(err) {
											setTimeout(function() {
												self.maintainToken();
											}, 5000);
										} else {
											// 完成存储后在时间节点到达后继续维护token
											setTimeout(function() {
												self.maintainToken();
											}, (tokenObj.expires_in - 60 * 10) * 1000)
										}
									});
								}, 5000);

							} else {
								log("maintainToken: save token obj succeed");
								// 完成存储后在时间节点到达后继续维护token
								setTimeout(function() {
									self.maintainToken();
								}, (tokenObj.expires_in - 60 * 10) * 1000)

							}
						})
					}
				});
			}, 5000);
		} else {
			log(token)
			var expires_in = 7200;
			if(token && token.hasOwnProperty("expires_in")) {
				expires_in = token.expires_in;
			}
			var update_time = new Date('1995-12-17T03:24:00');
			if(token && token.hasOwnProperty("update_time")) {
				update_time = token.update_time;
			}

			log(expires_in, update_time)
			var tokenLega = timeLegal(update_time, expires_in);
			if(typeof(update_time) === "string") {
				update_time = new Date(update_time);
			}

			if(tokenLega) {
				log("maintainToken: wait to get new token");
				var startTokenTime = parseInt(update_time.getTime())  + (expires_in - 10 * 60) * 1000 - (new Date()).getTime();

				setTimeout(function() {
					self.getAccessToken(function(err, tokenObj) {
						if(err) {
							log("maintainToken: maintaince new access_token error", err);
							// 重新执行维护程序
							setTimeout(function() {
								self.maintainToken();
							}, 5000);
						} else {
							self.saveToken(tokenObj, function(err) {
								if(err) {
									setTimeout(function() {
										self.maintainToken();
									}, 5000);
								} else {
									// 完成存储后在时间节点到达后继续维护token
									setTimeout(function() {
										self.maintainToken();
									}, (tokenObj.expires_in - 60 * 10) * 1000)
								}
							});
						}
					});
				}, startTokenTime);
			} else {
			log("maintainToken: start get new token");
				setTimeout(function() {
					self.getAccessToken(function(err, tokenObj) {
						if(err) {
							log("maintainToken: get new access_token error", err);
							setTimeout(function() {
								self.maintainToken();
							}, 5000);
						} else {
							self.saveToken(tokenObj, function(err) {
								if(err) {
									setTimeout(function() {
										self.maintainToken();
									}, 5000);
								} else {
									// 完成存储后在时间节点到达后继续维护token
									setTimeout(function() {
										self.maintainToken();
									}, (tokenObj.expires_in - 60 * 10) * 1000)
								}
							});
						}
					});
				}, 5000);
			}
		}
	})
}
// -----------------------------------------------------------------
// 判断当前时间下,token 是否有效
function timeLegal(time, expires_in) {
	log(time, typeof(time), time instanceof Date)
	if(typeof(time) === "string") {
		time = new Date(time);
	}
	var time1 = parseInt(time.getTime()) / 1000;
	var now = parseInt((new Date()).getTime()) / 1000;

	if(time1 + (expires_in - 10 * 60) > now) {
		return true;
	} else {
		return false;
	}
}

// -----------------------------------------------------------------
// 获取并存储access_token的临时方法,做当维护函数不能使用时,临时更新最新的access_token 使用
WX.prototype.getSaveToken = function() {
	var self = this;
	self.getAccessToken(function(err, tokenObj) {
		if(err) {
			log("getSaveToken: get access_token error", err);
			// 失败 5秒后继续维护token
			setTimeout(function() {
				self.getSaveToken();
			}, 5000);
		} else {
			self.saveToken(tokenObj, function(err) {
				if(err) {
					log("getSaveToken: save token obj error", err);
					setTimeout(function() {
						self.saveToken(tokenObj, function(err) {
							if(err) {
								setTimeout(function() {
									self.getSaveToken();
								}, 5000);
							} else {
								// 完成存储后在时间节点到达后继续维护token
								log("getSaveToken: save token succeed");
							}
						});
					}, 5000);

				} else {
					// 完成存储后在时间节点到达后继续维护token
					log("getSaveToken: now save token succeed.")
				}
			})
		}
	});
}

// -----------------------------------------------------------------


text:
package org.apache.airavata.workflow.engine.util;

public class Data {
    private String destination_path;
    private String verify_size;
    private String source_path;
    private boolean recursive;
    private String DATA_TYPE;

    public String getDestination_path() {
        return destination_path;
    }

    public void setDestination_path(String destination_path) {
        this.destination_path = destination_path;
    }

    public String getVerify_size() {
        return verify_size;
    }

    public void setVerify_size(String verify_size) {
        this.verify_size = verify_size;
    }

    public String getSource_path() {
        return source_path;
    }

    public void setSource_path(String source_path) {
        this.source_path = source_path;
    }

    public boolean getRecursive() {
        return recursive;
    }

    public void setRecursive(boolean recursive) {
        this.recursive = recursive;
    }

    public String getDATA_TYPE() {
        return DATA_TYPE;
    }

    public void setDATA_TYPE(String DATA_TYPE) {
        this.DATA_TYPE = DATA_TYPE;
    }
}


text:
package router

import (
	"net/http"
	"strings"

	"getmelange.com/backend/framework"
	"getmelange.com/backend/info"
)

// Router represents an HTTP multiplexer based on path prefixes.
type Router struct {
	globalPrefix string
	routes       map[string]Handler
}

// CreateRouter will create a new router that ignores the specified
// prefix.
func CreateRouter(globalPrefix string) *Router {
	return &Router{
		globalPrefix: globalPrefix,
		routes:       make(map[string]Handler),
	}
}

// AddRoute gives the router information about the routes it can
// serve.
func (r *Router) AddRoute(prefix string, handler interface{}) *Router {
	handlerInterface, handlerOk := handler.(Handler)
	getInterface, getOk := handler.(GetHandler)
	postInterface, postOk := handler.(PostHandler)

	if handlerOk {
		r.routes[prefix] = handlerInterface

		return r
	}

	if getOk || postOk {
		r.routes[prefix] = &selectionHandler{
			Get:  getInterface,
			Post: postInterface,
		}

		return r
	}

	panic("Cannot load a route that isn't a router.Handler, router.GetHandler, or router.PostHandler")
}

// Handle performs the actual routing.
func (r *Router) Handle(req *Request) framework.View {
	for route, handler := range r.routes {
		if strings.HasPrefix(req.URL.Path, r.globalPrefix+route) {
			return handler.Handle(req)
		}
	}

	return &framework.HTTPError{
		ErrorCode: 404,
		Message:   "Router is unable to found specified route.",
	}
}

func (r *Router) HandleRequest(req *http.Request, env *info.Environment) framework.View {
	return r.Handle(parseRequest(req, env))
}


text:
var path = require('path');
var config = require('madewithlove-webpack-config')({
  sourcePath: 'src',
  outputPath: 'builds/',
  linting: false,
});

// Webpack doesn't play nice with Socket.io
config.node = {
    fs: 'empty',
    tls: 'empty',
}

// We want to use the source code when available.
var pkgSrc = path.join(__dirname, '..', '..', 'src');
var pkgNodeModules = path.join(__dirname, '..', '..', 'node_modules');
var fs = require('fs');

if (fs.existsSync(pkgSrc) && fs.existsSync(pkgNodeModules)) {
    config.resolve = {alias: {'redux-socket-middleware': pkgSrc}};
    config.module.loaders.push({
        test:    /\.js$/,
        loader: 'babel-loader',
        include: pkgSrc,
        query: {
            presets: ['es2015', 'stage-0'],
            plugins: [
                'add-module-exports',
            ],
        },
    })
}

module.exports = config;


text:
import os
import sys
import json
import random

from common.HttpHelper import httpGet
from common.LoggerHelper import writeLog, writeErrorLog, writeWarningLog
import traceback

KEY = 'dacfb9273dd8cba740317191ad4daf6c'
KEY1 = 'a7b765f063397ce07d7558f81de31362'
KEY2 = 'fa7bdb2bca7f33b44945349bb5365df0'
KEY3 = 'fdce34a1793de302dcec426d62c7ef0f'
KEY4 = '54d9cf5b79601bf2e2382dc186c76524'
KEY5 = '6225b67b34395a2f0de8d4facb3e7f0a'

def getKey():
    randomNumber = random.randint(0, 5)
    if randomNumber == 0:
        return KEY
    elif randomNumber == 1:
        return KEY1
    elif randomNumber == 2:
        return KEY2
    elif randomNumber == 3:
        return KEY3
    elif randomNumber == 4:
        return KEY4
    else:
        return KEY5

# 计算时间和距离
def getDistanceAndTime(origin, destination):
    geoCode = getGeoCodes(origin + "|" + destination)
    return getDistanceAndTimeByLngLat(geoCode[0], geoCode[1])

def getDistanceAndTimeByLngLat(origin, destination):
    url = unicode('http://restapi.amap.com/v3/direction/driving?key={0}&origin={1}&destination={2}&strategy=9').format(
        getKey(), origin, destination)
    res = httpGet(url)

    jo = json.loads(res)
    if (int(jo['status']) == 0):
        writeWarningLog(unicode("【高德】驾车 路径规划失败, origin:{0},destination:{1},原因:{2}").format(origin, destination, jo))
        return (None, None)

    paths = jo['route']['paths']
    if (len(paths) <= 0):
        writeWarningLog(unicode("【高德】驾车 没有找到相关路径, origin:{0},destination:{1},原因:{2}").format(origin, destination, jo))
        return (None, None)

    distance = unicode("{0}公里").format(round(float(paths[0]['distance']) / 1000, 1))
    minutes = int(float(paths[0]['duration']) / 60)
    hour = int(minutes / 60)
    minute = int(minutes % 60)
    time = unicode("{0}分").format(minute) if hour <= 0 else unicode("{0}小时{1}分").format(hour, minute)

    return (distance, time)

def getGeoCodes(address):
    url = unicode("http://restapi.amap.com/v3/geocode/geo?key={0}&address={1}&batch=true").format(getKey(), address)
    res = httpGet(url)

    jo = json.loads(res)

    if (int(jo['status']) == 0):
        writeWarningLog(unicode("【高德】解析地址失败, address:{0}, 原因:{1}").format(address, jo))
        return (None, None)

    result = []
    for i in range(0, len(jo['geocodes'])):
        geoCodes = jo['geocodes'][i]
        result.append(geoCodes['location'])

    return result

def getDirectionByLngLat(origin, destination):
    url = unicode(
        'http://restapi.amap.com/v3/direction/transit/integrated?key={0}&origin={1}&destination={2}&strategy=0&city=天津市').format(
        getKey(), origin, destination)
    res = httpGet(url)

    try:
        jo = json.loads(res)
        if (int(jo['status']) == 0):
            writeWarningLog(unicode("【高德】公交 路径规划失败, origin:{0},destination:{1},原因:{2}").format(origin, destination, jo))
            return None

        transits = jo['route']['transits']
        if (len(transits) <= 0):
            writeWarningLog(
                unicode("【高德】公交规划 没有找到相关路径, origin:{0},destination:{1},原因:{2}").format(origin, destination, jo))
            return None

        transit = transits[0]  # 找第一条规划路线
        segments = transit['segments']  # 路径信息

        if (len(segments) <= 0):
            writeWarningLog(
                unicode("【高德】公交规划 没有找到路径信息, origin:{0},destination:{1},原因:{2}").format(origin, destination, jo))
            return None

        result = []
        for i in range(0, len(segments)):
            segment = segments[i]
            if i == 0:
                walkingDistance = round(float(segment['walking']['distance']) / 1000, 1)
                walkingTime = int(float(segment['walking']['duration']) / 60)
                result.append(unicode("步行{0}公里:约{1}分钟").format(walkingDistance, walkingTime))

                busName = segment['bus']['buslines'][0]['name']
                busDepartureStop = segment['bus']['buslines'][0]['departure_stop']['name']
                busArrivalStop = segment['bus']['buslines'][0]['arrival_stop']['name']
                totalStops = len(segment['bus']['buslines'][0]['via_stops']) + 1
                result.append(
                    unicode("({0}) {1} => {2} 共{3}站").format(busName, busDepartureStop, busArrivalStop, totalStops))
            elif i == len(segments) - 1:
                if segment['walking'] is not None:
                    if len(segment['walking']) <= 0:
                        continue
                    walkingDistance = round(float(segment['walking']['distance']) / 1000, 1)
                    walkingTime = int(float(segment['walking']['duration']) / 60)
                    result.append(unicode("步行{0}公里:约{1}分钟").format(walkingDistance, walkingTime))
            else:
                busName = segment['bus']['buslines'][0]['name']
                busDepartureStop = segment['bus']['buslines'][0]['departure_stop']['name']
                busArrivalStop = segment['bus']['buslines'][0]['arrival_stop']['name']
                totalStops = len(segment['bus']['buslines'][0]['via_stops']) + 1
                result.append(
                    unicode("({0}) {1} => {2} 共{3}站").format(busName, busDepartureStop, busArrivalStop, totalStops))
        return result
    except Exception, e:
        traceback.print_exc()
        print url
        print res
        return None


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 *
 * Generated from protobuf message google.cloud.compute.v1.BackendServicesScopedList
 */
class BackendServicesScopedList extends \Google\Protobuf\Internal\Message
{
    /**
     * A list of BackendServices contained in this scope.
     *
     * Generated from protobuf field repeated .google.cloud.compute.v1.BackendService backend_services = 388522409;
     */
    private $backend_services;
    /**
     * Informational warning which replaces the list of backend services when the list is empty.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.Warning warning = 50704284;
     */
    private $warning = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type \Google\Cloud\Compute\V1\BackendService[]|\Google\Protobuf\Internal\RepeatedField $backend_services
     *           A list of BackendServices contained in this scope.
     *     @type \Google\Cloud\Compute\V1\Warning $warning
     *           Informational warning which replaces the list of backend services when the list is empty.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Compute\V1\Compute::initOnce();
        parent::__construct($data);
    }

    /**
     * A list of BackendServices contained in this scope.
     *
     * Generated from protobuf field repeated .google.cloud.compute.v1.BackendService backend_services = 388522409;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getBackendServices()
    {
        return $this->backend_services;
    }

    /**
     * A list of BackendServices contained in this scope.
     *
     * Generated from protobuf field repeated .google.cloud.compute.v1.BackendService backend_services = 388522409;
     * @param \Google\Cloud\Compute\V1\BackendService[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setBackendServices($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Compute\V1\BackendService::class);
        $this->backend_services = $arr;

        return $this;
    }

    /**
     * Informational warning which replaces the list of backend services when the list is empty.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.Warning warning = 50704284;
     * @return \Google\Cloud\Compute\V1\Warning|null
     */
    public function getWarning()
    {
        return $this->warning;
    }

    public function hasWarning()
    {
        return isset($this->warning);
    }

    public function clearWarning()
    {
        unset($this->warning);
    }

    /**
     * Informational warning which replaces the list of backend services when the list is empty.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.Warning warning = 50704284;
     * @param \Google\Cloud\Compute\V1\Warning $var
     * @return $this
     */
    public function setWarning($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Compute\V1\Warning::class);
        $this->warning = $var;

        return $this;
    }

}


text:
/**
 * @name String
 * @class
 * @description
 * @requires Lass
 */
// javascript 1.0 link, anchor, lastIndexOf, slice
// javascript 1.1 valueOf
// javascript 1.2 fromCharCode, charAt, charCodeAt, concat, search
// test, contains, trim, toInt, toFloat, substitute
// String.prototype.trim  javascript 1.8.1
// ecma6 startsWith, endsWith, contains, codePointAt, repeat, fromCodePoint
;void function() {

    var LString = {
        /**
         * 去字符串两边的空格 version(1.8.1)
         * @param {String} string
         * @returns {String}
         */
        trim : function(string) {},
        /**
         * 去字符串左边空格 version(1.8.1)
         * @param {String} string
         * @return {String}
         */
        trimLeft : function(string) {},
        /**
         * 去字符串右边空格 version(1.8.1)
         * @param {String} string
         * @returns {String}
         */
        trimRight : function(string) {},
        /**
         * check string start with some word version(ecma6)
         * @param {String} string
         * @param {String} pattern
         * @param {Number} position
         * @return {Boolean}
         */
        startsWith : function(string, searchString, position) {},
        /**
         * check string end with some word version(ecma6)
         * @param {String} string
         * @param {String} pattern
         * @param {Number} position
         * @return {Boolean}
         */
        endsWith : function(string, searchString, position) {},
        /**
         * 重复字符串
         * @param {String} string
         * @param {Number} count 重复次数
         * @return {String}
         */
        repeat : function(string, count) {}
    };

    var slice = Array.prototype.slice;

    LString.trimLeft = (String.prototype.trimLeft) ? function(string) {
        return string.trimLeft();
    } :
    function(string) {
        return string.replace(/^\s\s*/, '');
    };

    LString.trimRight = (String.prototype.trimRight) ? function(string) {
        return string.trimRight();
    } :
    function(string) {
        var ws = /\s/,
            i = string.length;
        while(ws.test(string.charAt(--i)));
        return string.slice(0, i+1);
    };

    LString.trim = (String.prototype.trim) ? function(string) {
        return string.trim();
    } :
    function(string) {
        return LString.trimRight(LString.trimLeft(string));
    };

    LString.startsWith = (String.prototype.startsWith) ? function(string) {
        return String.prototype.startsWith.apply(string, slice.call(arguments, 1));
    } :
    function(string, searchString, position) {
        return string.slice((position || 0), string.length) === searchString;
    };

    LString.endsWith = (String.prototype.endsWith) ? function(string) {
        return String.prototype.endsWith.apply(string, slice.call(arguments, 1));
    } :
    function(string, searchString, position) {
        return string.slice(string.length - pattern.length, position) === pattern;
    };

    LString.repeat = (String.prototype.repeat) ? function(string) {
        return String.prototype.repeat.apply(string, slice.call(arguments, 1));
    } :
    function(string, count) {
        if (string === void 0 || string === null)
            throw new TypeError('array must not be null or undefined');

        count = count || 0;
        var str = '';

        if (count === 0) return '';
        count = parseInt(count, 10);

        while(count > 0) {
            str += string;
            --count;
        }

        return str;
    };

    this.register('L.String', LString);
}.call(L);


text:
This page demonstrates how to use Chronos benchmark tool to benchmark forecasting performance on platforms.

## Basic Usage
The benchmark tool is installed automatically when `bigdl-chronos` is installed. To get information about performance (currently for forecasting only) on the your own machine.

Run benchmark tool with default options using following command:
```bash
benchmark-chronos -l 96 -o 720
```
```eval_rst
.. note::
    **Required Options**:

     ``-l/--lookback`` and ``-o/--horizon`` are required options for Chronos benchmark tool. Use ``-l/--lookback`` to specify the history time steps while use ``-o/--horizon`` to specify the output time steps. For more details, please refer to `here <https://bigdl.readthedocs.io/en/latest/doc/Chronos/Overview/forecasting.html#regular-regression-rr-style>`_.
```
By default, the tool will load `tsinghua_electricity` dataset and train a `TCNForecaster` with input lookback and horizon parameters under `PyTorch` framework. As it loads, it prints information about hardware, environment variables and benchmark parameters. When benchmarking is completed, it reports the average throughput during training process. Users may be able to improve forecasting performance by following suggested changes on Nano environment variables.

Besides the default usage, more execution parameters can be set to obtain more benchmark results. Read on to learn more about the configuration options available in Chronos benchmark tool.

## Configuration Options
The benchmark tool provides various options for configuring execution parameters. Some key configuration options are introduced in this part and a list of all options is given in [**Advanced Options**](#advanced-options).

### Model
The tool provides several built-in time series forecasting models, including TCN, LSTM, Seq2Seq, NBeats and Autoformer. To specify which model to use, run benchmark tool with `-m/--model`. If not specified, TCN is used as the default.
```bash
benchmark-chronos -m lstm -l 96 -o 720
```

### Stage
Regarding a model, training and inference stages are most concerned. By setting `-s/--stage` parameter, users can obtain knowledge of throughput during training (`-s train`), throughput during inference (`-s throughput`) and latency of inference (`-s latency`). If not specified, train is used as the default.
```bash
benchmark-chronos -s latency -l 96 -o 720
```

### Dataset
Several built-in datasets can be chosen, including nyc_taxi and tsinghua_electricity. If users are with poor Internet connection and hard to download dataset, run benchmark tool with `-d synthetic_dataset` to use synthetic dataset. Default to be tsinghua_electricity if `-d/--dataset` parameter is not specified.
```bash
benchmark-chronos -d nyc_taxi -l 96 -o 720
```
```eval_rst
.. note::
    **Download tsinghua_electricity Dataset**:

     The tsinghua_electricity dataset does not support automatic downloading. Users can download manually from `here <https://github.com/thuml/Autoformer#get-started>`_ to path "~/.chronos/dataset/".
```

### Framework
Pytorch and tensorflow are both supported and can be specified by setting `-f torch` or `-f tensorflow`. And the default framework is pytorch.
```bash
benchmark-chronos -f tensorflow -l 96 -o 720
```
```eval_rst
.. note::
     NBeats and Autoformer does not support tensorflow backend now.
```

### Core number
By default, the benchmark tool will run on all physical cores. And users can explicitly specify the number of cores through `-c/--cores` parameter.
```bash
benchmark-chronos -c 4 -l 96 -o 720
```

### Lookback
Forecasting aims at predicting the future by using the knowledge from the history. The required option `-l/--lookback`corresponds to the length of historical data along time.
```bash
benchmark-chronos -l 96 -o 720
```

### Horizon
Forecasting aims at predicting the future by using the knowledge from the history. The required option `-o/--horizon`corresponds to the length of predicted data along time.
```bash
benchmark-chronos -l 96 -o 720
```

## Advanced Options
Besides, number of processes and epoches can be set by `--training_processes` and `--training_epochs`. Users can also tune batchsize during training and inference through `--training_batchsize` and `--inference_batchsize` respectively.
```bash
benchmark-chronos --training_processes 2 --training_epochs 3 --training_batchsize 32 --inference_batchsize 128 -l 96 -o 720
```

To speed up inference, accelerators like ONNXRuntime and OpenVINO are usually used. To benchmark inference performance with or without accelerator, run tool with `--inference_framework` to specify without accelerator (`--inference_framework torch`)or with ONNXRuntime (`--inference_framework onnx`) or with OpenVINO (`--inference_framework openvino`).
```bash
benchmark-chronos --inference_framework onnx -l 96 -o 720
```

When benchmark tool is run with `--ipex` enabled, intel-extension-for-pytorch will be used as accelerator for trainer.

If want to use quantized model to predict, just run the benchmark tool with `--quantize` enabled and the quantize framework can be specified by `--quantize_type`. The parameter`--quantize_type` need to be set as pytorch_ipex when users want to use pytorch_ipex as quantize type. Otherwise, the defaut quantize type will be selected according to `--inference_framework`. If pytorch is the inference framework, then pytorch_fx will be the default. If users choose ONNXRuntime as inference framework, onnxrt_qlinearops will be quantize type. And if OpenVINO is chosen, the openvino quantize type will be selected.
```bash
benchmark-chronos --ipex --quantize --quantize_type pytorch_ipex -l 96 -o 720
```

Moreover, if want to benchmark inference performance of a trained model, run benchmark tool with `--ckpt` to specify the checkpoint path of model. By default, the model for inference will be trained first according to input parameters.

Running the benchmark tool with `-h/--help` yields the following usage message, which contains all configuration options:
```bash
benchmark-chronos -h
```
```eval_rst
.. code-block:: python

    usage: benchmark-chronos.py [-h] [-m] [-s] [-d] [-f] [-c] -l lookback -o
                                horizon [--training_processes]
                                [--training_batchsize] [--training_epochs]
                                [--inference_batchsize] [--quantize]
                                [--inference_framework  [...]] [--ipex]
                                [--quantize_type] [--ckpt]

    Benchmarking Parameters

    optional arguments:
      -h, --help            show this help message and exit
      -m, --model           model name, choose from
                            tcn/lstm/seq2seq/nbeats/autoformer, default to "tcn".
      -s, --stage           stage name, choose from train/latency/throughput,
                            default to "train".
      -d, --dataset         dataset name, choose from
                            nyc_taxi/tsinghua_electricity/synthetic_dataset,
                            default to "tsinghua_electricity".
      -f, --framework       framework name, choose from torch/tensorflow, default
                            to "torch".
      -c, --cores           core number, default to all physical cores.
      -l lookback, --lookback lookback
                            required, the history time steps (i.e. lookback).
      -o horizon, --horizon horizon
                            required, the output time steps (i.e. horizon).
      --training_processes
                            number of processes when training, default to 1.
      --training_batchsize
                            batch size when training, default to 32.
      --training_epochs     number of epochs when training, default to 1.
      --inference_batchsize
                            batch size when infering, default to 1.
      --quantize            if use the quantized model to predict, default to
                            False.
      --inference_framework  [ ...]
                            predict without/with accelerator, choose from
                            torch/onnx/openvino, default to "torch" (i.e. predict
                            without accelerator).
      --ipex                if use ipex as accelerator for trainer, default to
                            False.
      --quantize_type       quantize framework, choose from
                            pytorch_fx/pytorch_ipex/onnxrt_qlinearops/openvino,
                            default to "pytorch_fx".
      --ckpt                checkpoint path of a trained model, e.g.
                            "checkpoints/tcn", default to "checkpoints/tcn".
```