text:
from __future__ import absolute_import

import pytest
import zipfile
from mock import patch

from six import BytesIO

from django.core.urlresolvers import reverse
from django.core.files.uploadedfile import SimpleUploadedFile

from sentry.testutils import TransactionTestCase
from sentry.models import File, ProjectDebugFile
from sentry import eventstore
from sentry.testutils.helpers.datetime import iso_format, before_now

from tests.symbolicator import get_fixture_path, insta_snapshot_stacktrace_data

REAL_RESOLVING_EVENT_DATA = {
    "platform": "cocoa",
    "debug_meta": {
        "images": [
            {
                "type": "apple",
                "arch": "x86_64",
                "uuid": "502fc0a5-1ec1-3e47-9998-684fa139dca7",
                "image_vmaddr": "0x0000000100000000",
                "image_size": 4096,
                "image_addr": "0x0000000100000000",
                "name": "Foo.app/Contents/Foo",
            }
        ],
        "sdk_info": {
            "dsym_type": "macho",
            "sdk_name": "macOS",
            "version_major": 10,
            "version_minor": 12,
            "version_patchlevel": 4,
        },
    },
    "exception": {
        "values": [
            {
                "stacktrace": {
                    "frames": [
                        {"platform": "foobar", "function": "hi"},
                        {"function": "unknown", "instruction_addr": "0x0000000100000fa0"},
                    ]
                },
                "type": "Fail",
                "value": "fail",
            }
        ]
    },
    "timestamp": iso_format(before_now(seconds=1)),
}

class ResolvingIntegrationTestBase(object):
    def get_event(self):
        return eventstore.get_events(filter_keys={"project_id": [self.project.id]})[0]

    def test_real_resolving(self):
        url = reverse(
            "sentry-api-0-dsym-files",
            kwargs={
                "organization_slug": self.project.organization.slug,
                "project_slug": self.project.slug,
            },
        )

        self.login_as(user=self.user)

        out = BytesIO()
        f = zipfile.ZipFile(out, "w")
        f.write(get_fixture_path("hello.dsym"), "dSYM/hello")
        f.close()

        response = self.client.post(
            url,
            {
                "file": SimpleUploadedFile(
                    "symbols.zip", out.getvalue(), content_type="application/zip"
                )
            },
            format="multipart",
        )
        assert response.status_code == 201, response.content
        assert len(response.data) == 1

        resp = self._postWithHeader(dict(project=self.project.id, **REAL_RESOLVING_EVENT_DATA))
        assert resp.status_code == 200

        event = self.get_event()

        assert event.data["culprit"] == "main"
        insta_snapshot_stacktrace_data(self, event.data)

    def test_debug_id_resolving(self):
        file = File.objects.create(
            name="crash.pdb", type="default", headers={"Content-Type": "text/x-breakpad"}
        )

        path = get_fixture_path("windows.sym")
        with open(path) as f:
            file.putfile(f)

        ProjectDebugFile.objects.create(
            file=file,
            object_name="crash.pdb",
            cpu_name="x86",
            project=self.project,
            debug_id="3249d99d-0c40-4931-8610-f4e4fb0b6936-1",
            code_id="5AB380779000",
        )

        self.login_as(user=self.user)

        event_data = {
            "contexts": {
                "device": {"arch": "x86"},
                "os": {"build": u"", "name": "Windows", "type": "os", "version": u"10.0.14393"},
            },
            "debug_meta": {
                "images": [
                    {
                        "id": u"3249d99d-0c40-4931-8610-f4e4fb0b6936-1",
                        "image_addr": "0x2a0000",
                        "image_size": 36864,
                        "name": u"C:\\projects\\breakpad-tools\\windows\\Release\\crash.exe",
                        "type": "symbolic",
                    }
                ]
            },
            "exception": {
                "stacktrace": {
                    "frames": [
                        {
                            "function": "<unknown>",
                            "instruction_addr": "0x2a2a3d",
                            "package": u"C:\\projects\\breakpad-tools\\windows\\Release\\crash.exe",
                        }
                    ]
                },
                "thread_id": 1636,
                "type": u"EXCEPTION_ACCESS_VIOLATION_WRITE",
                "value": u"Fatal Error: EXCEPTION_ACCESS_VIOLATION_WRITE",
            },
            "platform": "native",
            "timestamp": iso_format(before_now(seconds=1)),
        }

        resp = self._postWithHeader(event_data)
        assert resp.status_code == 200

        event = self.get_event()
        assert event.data["culprit"] == "main"
        insta_snapshot_stacktrace_data(self, event.data)

    def test_missing_dsym(self):
        self.login_as(user=self.user)

        resp = self._postWithHeader(dict(project=self.project.id, **REAL_RESOLVING_EVENT_DATA))
        assert resp.status_code == 200

        event = self.get_event()
        assert event.data["culprit"] == "unknown"
        insta_snapshot_stacktrace_data(self, event.data)

    def test_missing_debug_images(self):
        self.login_as(user=self.user)

        payload = dict(project=self.project.id, **REAL_RESOLVING_EVENT_DATA)
        del payload["debug_meta"]

        resp = self._postWithHeader(payload)
        assert resp.status_code == 200

        event = self.get_event()
        assert event.data["culprit"] == "unknown"
        insta_snapshot_stacktrace_data(self, event.data)

class SymbolicatorResolvingIntegrationTest(ResolvingIntegrationTestBase, TransactionTestCase):
    # For these tests to run, write `symbolicator.enabled: true` into your
    # `~/.sentry/config.yml` and run `sentry devservices up`

    @pytest.fixture(autouse=True)
    def initialize(self, live_server):
        self.project.update_option("sentry:builtin_symbol_sources", [])
        new_prefix = live_server.url

        with patch("sentry.auth.system.is_internal_ip", return_value=True), self.options(
            {"system.url-prefix": new_prefix}
        ):

            # Run test case:
            yield

redpajama_set_name: RedPajamaGithub


text:
package com.microsoft.azure.management.compute.v2020_06_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * This is the disk image encryption base class.
 */
public class DiskImageEncryption {
    /**
     * A relative URI containing the resource ID of the disk encryption set.
     */
    @JsonProperty(value = "diskEncryptionSetId")
    private String diskEncryptionSetId;

    /**
     * Get a relative URI containing the resource ID of the disk encryption set.
     *
     * @return the diskEncryptionSetId value
     */
    public String diskEncryptionSetId() {
        return this.diskEncryptionSetId;
    }

    /**
     * Set a relative URI containing the resource ID of the disk encryption set.
     *
     * @param diskEncryptionSetId the diskEncryptionSetId value to set
     * @return the DiskImageEncryption object itself.
     */
    public DiskImageEncryption withDiskEncryptionSetId(String diskEncryptionSetId) {
        this.diskEncryptionSetId = diskEncryptionSetId;
        return this;
    }

}


text:
import React from 'react';
import Card from 'infra/component/Card';
import { timeRangeToString } from 'infra/service/util';
import type { TimeRangeMetric } from '../service/timeRangeMetric';

type TimeRangeSummaryProps = {
  metric: TimeRangeMetric,
}

class TimeRangeSummary extends React.Component<*, TimeRangeSummaryProps, *> {

  props: TimeRangeSummaryProps

  render() {
    const { metric } = this.props;

    return (
      <Card title={`Time Range Summary, ${timeRangeToString(metric.dateStart, metric.dateEnd)}`}>

              Total posts

              {metric.postsMetric.totalPosts()}

              Shares: {metric.postsMetric.totalShares()}

              Likes: {metric.postsMetric.totalLikes()}

              Total comments

              {metric.postsMetric.totalComments()}

              Likes: {metric.commentsMetric.totalLikes()}

              Total members

              {metric.usersMetric.totalMembers()}

              Member posting: {metric.usersMetric.uniqueUsersPosts().length}

              Member commenting: {metric.usersMetric.uniqueUsersComments().length}

      </Card>
    );
  }

}

export default TimeRangeSummary;


text:
{# Information pages list page. #}

{% extends "base.html" %}

{% block head_title %}Information pages{% end %}
{% block body_title %}Information pages{% end %}

{% block main_content %}

    Name
    Title
    Menu
    Modified
    Created

  {% for info in all_infos %}

      {{ info['name'] }}

    {{ info.get('title') or '-' }}
    {{ info.get('menu') or '-' }}

      {{ info['modified'] }}

        {% module Icon('logs', label=True) %}

    {{ info['created'] }}

  {% end %}

{% end %}{# block main_content #}

{% if is_admin %}
{% block action_content %}
<form action="{{ reverse_url('info_create') }}"
      method="GET" role="form">
  <button type="submit" class="btn btn-primary btn-block">
     Create</button>
</form>
{% end %} {# block action_content #}
{% end %}


text:
namespace blink {

class LayoutPoint;

class PLATFORM_EXPORT DoublePoint {
  DISALLOW_NEW();

 public:
  DoublePoint() : m_x(0), m_y(0) {}
  DoublePoint(double x, double y) : m_x(x), m_y(y) {}
  DoublePoint(const IntPoint& p) : m_x(p.x()), m_y(p.y()) {}
  DoublePoint(const FloatPoint& p) : m_x(p.x()), m_y(p.y()) {}
  explicit DoublePoint(const LayoutPoint&);

  explicit DoublePoint(const IntSize& size)
      : m_x(size.width()), m_y(size.height()) {}

  explicit DoublePoint(const FloatSize&);

  explicit DoublePoint(const DoubleSize& size)
      : m_x(size.width()), m_y(size.height()) {}

  static DoublePoint zero() { return DoublePoint(); }

  DoublePoint expandedTo(const DoublePoint& other) const {
    return DoublePoint(std::max(m_x, other.m_x), std::max(m_y, other.m_y));
  }

  DoublePoint shrunkTo(const DoublePoint& other) const {
    return DoublePoint(std::min(m_x, other.m_x), std::min(m_y, other.m_y));
  }

  double x() const { return m_x; }
  double y() const { return m_y; }
  void setX(double x) { m_x = x; }
  void setY(double y) { m_y = y; }

  void move(const DoubleSize& s) {
    m_x += s.width();
    m_y += s.height();
  }

  void move(double x, double y) {
    m_x += x;
    m_y += y;
  }

  void moveBy(const DoublePoint& p) {
    m_x += p.x();
    m_y += p.y();
  }

  void scale(float sx, float sy) {
    m_x *= sx;
    m_y *= sy;
  }

  DoublePoint scaledBy(float scale) const {
    return DoublePoint(m_x * scale, m_y * scale);
  }

  String toString() const;

 private:
  double m_x, m_y;
};

inline bool operator==(const DoublePoint& a, const DoublePoint& b) {
  return a.x() == b.x() && a.y() == b.y();
}

inline bool operator!=(const DoublePoint& a, const DoublePoint& b) {
  return a.x() != b.x() || a.y() != b.y();
}

inline DoublePoint& operator+=(DoublePoint& a, const DoubleSize& b) {
  a.setX(a.x() + b.width());
  a.setY(a.y() + b.height());
  return a;
}

inline DoublePoint& operator-=(DoublePoint& a, const DoubleSize& b) {
  a.setX(a.x() - b.width());
  a.setY(a.y() - b.height());
  return a;
}

inline DoublePoint operator+(const DoublePoint& a, const DoubleSize& b) {
  return DoublePoint(a.x() + b.width(), a.y() + b.height());
}

inline DoubleSize operator-(const DoublePoint& a, const DoublePoint& b) {
  return DoubleSize(a.x() - b.x(), a.y() - b.y());
}

inline DoublePoint operator-(const DoublePoint& a) {
  return DoublePoint(-a.x(), -a.y());
}

inline DoublePoint operator-(const DoublePoint& a, const DoubleSize& b) {
  return DoublePoint(a.x() - b.width(), a.y() - b.height());
}

inline IntPoint roundedIntPoint(const DoublePoint& p) {
  return IntPoint(clampTo<int>(roundf(p.x())), clampTo<int>(roundf(p.y())));
}

inline IntPoint ceiledIntPoint(const DoublePoint& p) {
  return IntPoint(clampTo<int>(ceil(p.x())), clampTo<int>(ceil(p.y())));
}

inline IntPoint flooredIntPoint(const DoublePoint& p) {
  return IntPoint(clampTo<int>(floor(p.x())), clampTo<int>(floor(p.y())));
}

inline FloatPoint toFloatPoint(const DoublePoint& a) {
  return FloatPoint(a.x(), a.y());
}

inline DoubleSize toDoubleSize(const DoublePoint& a) {
  return DoubleSize(a.x(), a.y());
}

// Redeclared here to avoid ODR issues.
// See platform/testing/GeometryPrinters.h.
void PrintTo(const DoublePoint&, std::ostream*);

}  // namespace blink

#endif


text:
package org.jsmart.zerocode.tests.postgres;

import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;

public class ExtensionB implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback {

    @Override
    public void afterEach(ExtensionContext extensionContext) throws Exception {
        System.out.println("ExtentionB - afterEach");
    }

    @Override
    public void beforeEach(ExtensionContext extensionContext) throws Exception {
        System.out.println("ExtentionB - beforeEach");

    }

    @Override
    public void afterAll(ExtensionContext extensionContext) throws Exception {
        System.out.println("ExtentionB - afterAll");

    }

    @Override
    public void beforeAll(ExtensionContext extensionContext) throws Exception {
        System.out.println("ExtentionB - beforeAll");

    }
}


text:
package net.collaud.fablab.manager.data;

import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 *
 * @author Gaetan Collaud <gaetancollaud@gmail.com>
 */
@Entity
@Table(name = "t_group")
@Getter
@Setter
@ToString
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class GroupEO extends AbstractDataEO<Long> implements Serializable {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "group_id", nullable = false)
	private Long id;

	@JsonIgnore
	@Column(name = "technicalname", nullable = false)
	private String technicalname;

	@Column(name = "name", nullable = false)
	private String name;

	@JsonIgnore
	@ManyToMany(mappedBy = "groups", fetch = FetchType.LAZY)
	private Set<UserEO> users;

	@ManyToMany(mappedBy = "groups", fetch = FetchType.LAZY)
	private Set<RoleEO> roles;

}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$rules['post'] = array();
$rules['user'] = array();


text:
package com.prom.by;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import com.prom.by.R.id;
import com.prom.by.R.layout;
import org.androidannotations.api.SdkVersionHelper;
import org.androidannotations.api.view.HasViews;
import org.androidannotations.api.view.OnViewChangedListener;
import org.androidannotations.api.view.OnViewChangedNotifier;

public final class SingleOrderActivity_
    extends SingleOrderActivity
    implements HasViews, OnViewChangedListener
{

    private final OnViewChangedNotifier onViewChangedNotifier_ = new OnViewChangedNotifier();
    public final static String ORDER_POSITION_EXTRA = "order_position";
    public final static String ORDERS_EXTRA = "orders";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        OnViewChangedNotifier previousNotifier = OnViewChangedNotifier.replaceNotifier(onViewChangedNotifier_);
        init_(savedInstanceState);
        super.onCreate(savedInstanceState);
        OnViewChangedNotifier.replaceNotifier(previousNotifier);
        setContentView(layout.activity_order);
    }

    private void init_(Bundle savedInstanceState) {
        OnViewChangedNotifier.registerOnViewChangedListener(this);
        injectExtras_();
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    @Override
    public void setContentView(View view, LayoutParams params) {
        super.setContentView(view, params);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    public static SingleOrderActivity_.IntentBuilder_ intent(Context context) {
        return new SingleOrderActivity_.IntentBuilder_(context);
    }

    public static SingleOrderActivity_.IntentBuilder_ intent(android.app.Fragment fragment) {
        return new SingleOrderActivity_.IntentBuilder_(fragment);
    }

    public static SingleOrderActivity_.IntentBuilder_ intent(android.support.v4.app.Fragment supportFragment) {
        return new SingleOrderActivity_.IntentBuilder_(supportFragment);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (((SdkVersionHelper.getSdkInt()< 5)&&(keyCode == KeyEvent.KEYCODE_BACK))&&(event.getRepeatCount() == 0)) {
            onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onViewChanged(HasViews hasViews) {
        pager = ((ViewPager) hasViews.findViewById(id.pager));
        setAdapter();
    }

    private void injectExtras_() {
        Bundle extras_ = getIntent().getExtras();
        if (extras_!= null) {
            if (extras_.containsKey(ORDER_POSITION_EXTRA)) {
                orderPosition = extras_.getInt(ORDER_POSITION_EXTRA);
            }
            if (extras_.containsKey(ORDERS_EXTRA)) {
                orders = extras_.getBundle(ORDERS_EXTRA);
            }
        }
    }

    @Override
    public void setIntent(Intent newIntent) {
        super.setIntent(newIntent);
        injectExtras_();
    }

    public static class IntentBuilder_ {

        private Context context_;
        private final Intent intent_;
        private android.app.Fragment fragment_;
        private android.support.v4.app.Fragment fragmentSupport_;

        public IntentBuilder_(Context context) {
            context_ = context;
            intent_ = new Intent(context, SingleOrderActivity_.class);
        }

        public IntentBuilder_(android.app.Fragment fragment) {
            fragment_ = fragment;
            context_ = fragment.getActivity();
            intent_ = new Intent(context_, SingleOrderActivity_.class);
        }

        public IntentBuilder_(android.support.v4.app.Fragment fragment) {
            fragmentSupport_ = fragment;
            context_ = fragment.getActivity();
            intent_ = new Intent(context_, SingleOrderActivity_.class);
        }

        public Intent get() {
            return intent_;
        }

        public SingleOrderActivity_.IntentBuilder_ flags(int flags) {
            intent_.setFlags(flags);
            return this;
        }

        public void start() {
            context_.startActivity(intent_);
        }

        public void startForResult(int requestCode) {
            if (fragmentSupport_!= null) {
                fragmentSupport_.startActivityForResult(intent_, requestCode);
            } else {
                if (fragment_!= null) {
                    fragment_.startActivityForResult(intent_, requestCode);
                } else {
                    if (context_ instanceof Activity) {
                        ((Activity) context_).startActivityForResult(intent_, requestCode);
                    } else {
                        context_.startActivity(intent_);
                    }
                }
            }
        }

        public SingleOrderActivity_.IntentBuilder_ orderPosition(int orderPosition) {
            intent_.putExtra(ORDER_POSITION_EXTRA, orderPosition);
            return this;
        }

        public SingleOrderActivity_.IntentBuilder_ orders(Bundle orders) {
            intent_.putExtra(ORDERS_EXTRA, orders);
            return this;
        }

    }

}


text:
#import "NSValueTransformer_NegateBoolean.h"
#import <Foundation/NSValue.h>

@implementation NSValueTransformer_NegateBoolean

+(Class)transformedValueClass {
   return [NSNumber class];
}

+(BOOL)allowsReverseTransformation {
   return YES;
}

-transformedValue:value {
   BOOL result=![value boolValue];

   return [NSNumber numberWithBool:result];
}

@end


text:
author: robmyers
comments: true
date: 2011-02-09 20:03:49+00:00
layout: post
slug: freeing_art_history_urinal
title: 'Freeing Art History: Urinal'
wordpress_id: 1920
categories:
- Art
- Art History
- Free Culture
- Projects
---

I commissioned the ultra-talented [cwebber](http://dustycloud.org/) to make a 3D model of a urinal suitable for 3D printing and signing. It's licenced under the Creative Commons [Attribution-ShareAlike 3.0 Unported licence](http://creativecommons.org/licenses/by-sa/3.0/). Here's a picture of it:

[![urinal.png](/assets/assets_c/2011/02/urinal-thumb-400x352-83.png)](/weblog/2011/02/09/urinal.png)You can download the original Blender file [here](/git/?p=urinal.git;a=blob;f=urinal.blend;h=c55a04ee64ff4eb3267e05726bfafa2e828713fd;hb=bd365bc8db80deb943cd56052eeef4728e37a003).

And there's a version suitable for 3D printing available for download [here](/git/?p=urinal.git;a=blob;f=urinal.x3d;h=cad050efe5887da3f787cdbf2c4f4e97afcd636e;hb=bd365bc8db80deb943cd56052eeef4728e37a003).

Which you can also download from thingiverse [here](http://www.thingiverse.com/thing:6261).

(You'll need to scale it to fit your printer.)

If you don't have a 3D printer yet, you can order a 3D print of the model from Shapeways [here](http://www.shapeways.com/model/212121/). If it's too large/expensive you can upload and print a smaller version.

Next I'd like to commission a 3D printable model of a glass ampoule suitable for containing a small volume of air from a town such as Paris...


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dream.work.dao.TokenDao">
    <insert id="insertToken">
        REPLACE  INTO token_uid (token, end_time, uid)
        VALUES (#{token}, #{endTime}, #{uid})
    </insert>
    <select id="getEndTime" resultType="Long">
        SELECT end_time
        FROM token_uid
        WHERE token = #{token}
    </select>
    <select id="getUid" resultType="String">
        SELECT uid
        FROM token_uid
        WHERE token = #{token}
    </select>
</mapper>


text:
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */

/*
    Vamp

    An API for audio analysis and feature extraction plugins.

    Centre for Digital Music, Queen Mary, University of London.
    Copyright 2006 Chris Cannam.

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use, copy,
    modify, merge, publish, distribute, sublicense, and/or sell copies
    of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
    ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
    CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

    Except as contained in this notice, the names of the Centre for
    Digital Music; Queen Mary, University of London; and Chris Cannam
    shall not be used in advertising or otherwise to promote the sale,
    use or other dealings in this Software without prior written
    authorization.
*/

#include "PluginAdapter.h"

#include <cstring>
#include <cstdlib>

#if ( VAMP_SDK_MAJOR_VERSION != 2 || VAMP_SDK_MINOR_VERSION != 6 )
#error Unexpected version of Vamp SDK header included
#endif

//#define DEBUG_PLUGIN_ADAPTER 1

_VAMP_SDK_PLUGSPACE_BEGIN(PluginAdapter.cpp)

namespace Vamp {

class PluginAdapterBase::Impl
{
public:
    Impl(PluginAdapterBase *);
    ~Impl();

    const VampPluginDescriptor *getDescriptor();

protected:
    PluginAdapterBase *m_base;

    static VampPluginHandle vampInstantiate(const VampPluginDescriptor *desc,
                                            float inputSampleRate);

    static void vampCleanup(VampPluginHandle handle);

    static int vampInitialise(VampPluginHandle handle, unsigned int channels,
                             unsigned int stepSize, unsigned int blockSize);

    static void vampReset(VampPluginHandle handle);

    static float vampGetParameter(VampPluginHandle handle, int param);
    static void vampSetParameter(VampPluginHandle handle, int param, float value);

    static unsigned int vampGetCurrentProgram(VampPluginHandle handle);
    static void vampSelectProgram(VampPluginHandle handle, unsigned int program);

    static unsigned int vampGetPreferredStepSize(VampPluginHandle handle);
    static unsigned int vampGetPreferredBlockSize(VampPluginHandle handle);
    static unsigned int vampGetMinChannelCount(VampPluginHandle handle);
    static unsigned int vampGetMaxChannelCount(VampPluginHandle handle);

    static unsigned int vampGetOutputCount(VampPluginHandle handle);

    static VampOutputDescriptor *vampGetOutputDescriptor(VampPluginHandle handle,
                                                       unsigned int i);

    static void vampReleaseOutputDescriptor(VampOutputDescriptor *desc);

    static VampFeatureList *vampProcess(VampPluginHandle handle,
                                        const float *const *inputBuffers,
                                        int sec,
                                        int nsec);

    static VampFeatureList *vampGetRemainingFeatures(VampPluginHandle handle);

    static void vampReleaseFeatureSet(VampFeatureList *fs);

    void checkOutputMap(Plugin *plugin);
    void markOutputsChanged(Plugin *plugin);

    void cleanup(Plugin *plugin);
    unsigned int getOutputCount(Plugin *plugin);
    VampOutputDescriptor *getOutputDescriptor(Plugin *plugin,
                                             unsigned int i);
    VampFeatureList *process(Plugin *plugin,
                             const float *const *inputBuffers,
                             int sec, int nsec);
    VampFeatureList *getRemainingFeatures(Plugin *plugin);
    VampFeatureList *convertFeatures(Plugin *plugin,
                                     const Plugin::FeatureSet &features);

    // maps both plugins and descriptors to adapters
    typedef std::map<const void *, Impl *> AdapterMap;
    static AdapterMap *m_adapterMap;
    static Impl *lookupAdapter(VampPluginHandle);

    bool m_populated;
    VampPluginDescriptor m_descriptor;
    Plugin::ParameterList m_parameters;
    Plugin::ProgramList m_programs;

    typedef std::map<Plugin *, Plugin::OutputList *> OutputMap;
    OutputMap m_pluginOutputs;

    std::map<Plugin *, VampFeatureList *> m_fs;
    std::map<Plugin *, std::vector<size_t> > m_fsizes;
    std::map<Plugin *, std::vector<std::vector<size_t> > > m_fvsizes;
    void resizeFS(Plugin *plugin, int n);
    void resizeFL(Plugin *plugin, int n, size_t sz);
    void resizeFV(Plugin *plugin, int n, int j, size_t sz);
};

PluginAdapterBase::PluginAdapterBase()
{
    m_impl = new Impl(this);
}

PluginAdapterBase::~PluginAdapterBase()
{
    delete m_impl;
}

const VampPluginDescriptor *
PluginAdapterBase::getDescriptor()
{
    return m_impl->getDescriptor();
}

PluginAdapterBase::Impl::Impl(PluginAdapterBase *base) :
    m_base(base),
    m_populated(false)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl[" << this << "]::Impl" << std::endl;
#endif
}

const VampPluginDescriptor *
PluginAdapterBase::Impl::getDescriptor()
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl[" << this << "]::getDescriptor" << std::endl;
#endif

    if (m_populated) return &m_descriptor;

    Plugin *plugin = m_base->createPlugin(48000);

    if (!plugin) {
        std::cerr << "PluginAdapterBase::Impl::getDescriptor: Failed to create plugin" << std::endl;
        return 0;
    }

    if (plugin->getVampApiVersion() != VAMP_API_VERSION) {
        std::cerr << "Vamp::PluginAdapterBase::Impl::getDescriptor: ERROR: "
                  << "API version " << plugin->getVampApiVersion()
                  << " for\nplugin \"" << plugin->getIdentifier() << "\" "
                  << "differs from version "
                  << VAMP_API_VERSION << " for adapter.\n"
                  << "This plugin is probably linked against a different version of the Vamp SDK\n"
                  << "from the version it was compiled with.  It will need to be re-linked correctly\n"
                  << "before it can be used." << std::endl;
        delete plugin;
        return 0;
    }

    m_parameters = plugin->getParameterDescriptors();
    m_programs = plugin->getPrograms();

    m_descriptor.vampApiVersion = plugin->getVampApiVersion();
    m_descriptor.identifier = strdup(plugin->getIdentifier().c_str());
    m_descriptor.name = strdup(plugin->getName().c_str());
    m_descriptor.description = strdup(plugin->getDescription().c_str());
    m_descriptor.maker = strdup(plugin->getMaker().c_str());
    m_descriptor.pluginVersion = plugin->getPluginVersion();
    m_descriptor.copyright = strdup(plugin->getCopyright().c_str());

    m_descriptor.parameterCount = m_parameters.size();
    m_descriptor.parameters = (const VampParameterDescriptor **)
        malloc(m_parameters.size() * sizeof(VampParameterDescriptor));

    unsigned int i;

    for (i = 0; i < m_parameters.size(); ++i) {
        VampParameterDescriptor *desc = (VampParameterDescriptor *)
            malloc(sizeof(VampParameterDescriptor));
        desc->identifier = strdup(m_parameters[i].identifier.c_str());
        desc->name = strdup(m_parameters[i].name.c_str());
        desc->description = strdup(m_parameters[i].description.c_str());
        desc->unit = strdup(m_parameters[i].unit.c_str());
        desc->minValue = m_parameters[i].minValue;
        desc->maxValue = m_parameters[i].maxValue;
        desc->defaultValue = m_parameters[i].defaultValue;
        desc->isQuantized = m_parameters[i].isQuantized;
        desc->quantizeStep = m_parameters[i].quantizeStep;
        desc->valueNames = 0;
        if (desc->isQuantized && !m_parameters[i].valueNames.empty()) {
            desc->valueNames = (const char **)
                malloc((m_parameters[i].valueNames.size()+1) * sizeof(char *));
            for (unsigned int j = 0; j < m_parameters[i].valueNames.size(); ++j) {
                desc->valueNames[j] = strdup(m_parameters[i].valueNames[j].c_str());
            }
            desc->valueNames[m_parameters[i].valueNames.size()] = 0;
        }
        m_descriptor.parameters[i] = desc;
    }

    m_descriptor.programCount = m_programs.size();
    m_descriptor.programs = (const char **)
        malloc(m_programs.size() * sizeof(const char *));

    for (i = 0; i < m_programs.size(); ++i) {
        m_descriptor.programs[i] = strdup(m_programs[i].c_str());
    }

    if (plugin->getInputDomain() == Plugin::FrequencyDomain) {
        m_descriptor.inputDomain = vampFrequencyDomain;
    } else {
        m_descriptor.inputDomain = vampTimeDomain;
    }

    m_descriptor.instantiate = vampInstantiate;
    m_descriptor.cleanup = vampCleanup;
    m_descriptor.initialise = vampInitialise;
    m_descriptor.reset = vampReset;
    m_descriptor.getParameter = vampGetParameter;
    m_descriptor.setParameter = vampSetParameter;
    m_descriptor.getCurrentProgram = vampGetCurrentProgram;
    m_descriptor.selectProgram = vampSelectProgram;
    m_descriptor.getPreferredStepSize = vampGetPreferredStepSize;
    m_descriptor.getPreferredBlockSize = vampGetPreferredBlockSize;
    m_descriptor.getMinChannelCount = vampGetMinChannelCount;
    m_descriptor.getMaxChannelCount = vampGetMaxChannelCount;
    m_descriptor.getOutputCount = vampGetOutputCount;
    m_descriptor.getOutputDescriptor = vampGetOutputDescriptor;
    m_descriptor.releaseOutputDescriptor = vampReleaseOutputDescriptor;
    m_descriptor.process = vampProcess;
    m_descriptor.getRemainingFeatures = vampGetRemainingFeatures;
    m_descriptor.releaseFeatureSet = vampReleaseFeatureSet;

    if (!m_adapterMap) {
        m_adapterMap = new AdapterMap;
    }
    (*m_adapterMap)[&m_descriptor] = this;

    delete plugin;

    m_populated = true;
    return &m_descriptor;
}

PluginAdapterBase::Impl::~Impl()
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl[" << this << "]::~Impl" << std::endl;
#endif

    if (!m_populated) return;

    free((void *)m_descriptor.identifier);
    free((void *)m_descriptor.name);
    free((void *)m_descriptor.description);
    free((void *)m_descriptor.maker);
    free((void *)m_descriptor.copyright);

    for (unsigned int i = 0; i < m_descriptor.parameterCount; ++i) {
        const VampParameterDescriptor *desc = m_descriptor.parameters[i];
        free((void *)desc->identifier);
        free((void *)desc->name);
        free((void *)desc->description);
        free((void *)desc->unit);
        if (desc->valueNames) {
            for (unsigned int j = 0; desc->valueNames[j]; ++j) {
                free((void *)desc->valueNames[j]);
            }
            free((void *)desc->valueNames);
        }
    }
    free((void *)m_descriptor.parameters);

    for (unsigned int i = 0; i < m_descriptor.programCount; ++i) {
        free((void *)m_descriptor.programs[i]);
    }
    free((void *)m_descriptor.programs);

    if (m_adapterMap) {

        m_adapterMap->erase(&m_descriptor);

        if (m_adapterMap->empty()) {
            delete m_adapterMap;
            m_adapterMap = 0;
        }
    }
}

PluginAdapterBase::Impl *
PluginAdapterBase::Impl::lookupAdapter(VampPluginHandle handle)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::lookupAdapter(" << handle << ")" << std::endl;
#endif

    if (!m_adapterMap) return 0;
    AdapterMap::const_iterator i = m_adapterMap->find(handle);
    if (i == m_adapterMap->end()) return 0;
    return i->second;
}

VampPluginHandle
PluginAdapterBase::Impl::vampInstantiate(const VampPluginDescriptor *desc,
                                         float inputSampleRate)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampInstantiate(" << desc << ")" << std::endl;
#endif

    if (!m_adapterMap) {
        m_adapterMap = new AdapterMap();
    }

    if (m_adapterMap->find(desc) == m_adapterMap->end()) {
        std::cerr << "WARNING: PluginAdapterBase::Impl::vampInstantiate: Descriptor " << desc << " not in adapter map" << std::endl;
        return 0;
    }

    Impl *adapter = (*m_adapterMap)[desc];
    if (desc != &adapter->m_descriptor) return 0;

    Plugin *plugin = adapter->m_base->createPlugin(inputSampleRate);
    if (plugin) {
        (*m_adapterMap)[plugin] = adapter;
    }

#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampInstantiate(" << desc << "): returning handle " << plugin << std::endl;
#endif

    return plugin;
}

void
PluginAdapterBase::Impl::vampCleanup(VampPluginHandle handle)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampCleanup(" << handle << ")" << std::endl;
#endif

    Impl *adapter = lookupAdapter(handle);
    if (!adapter) {
        delete ((Plugin *)handle);
        return;
    }
    adapter->cleanup(((Plugin *)handle));
}

int
PluginAdapterBase::Impl::vampInitialise(VampPluginHandle handle,
                                        unsigned int channels,
                                        unsigned int stepSize,
                                        unsigned int blockSize)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampInitialise(" << handle << ", " << channels << ", " << stepSize << ", " << blockSize << ")" << std::endl;
#endif

    Impl *adapter = lookupAdapter(handle);
    if (!adapter) return 0;
    bool result = ((Plugin *)handle)->initialise(channels, stepSize, blockSize);
    adapter->markOutputsChanged((Plugin *)handle);
    return result ? 1 : 0;
}

void
PluginAdapterBase::Impl::vampReset(VampPluginHandle handle)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampReset(" << handle << ")" << std::endl;
#endif

    ((Plugin *)handle)->reset();
}

float
PluginAdapterBase::Impl::vampGetParameter(VampPluginHandle handle,
                                    int param)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampGetParameter(" << handle << ", " << param << ")" << std::endl;
#endif

    Impl *adapter = lookupAdapter(handle);
    if (!adapter) return 0.0;
    Plugin::ParameterList &list = adapter->m_parameters;
    return ((Plugin *)handle)->getParameter(list[param].identifier);
}

void
PluginAdapterBase::Impl::vampSetParameter(VampPluginHandle handle,
                                    int param, float value)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampSetParameter(" << handle << ", " << param << ", " << value << ")" << std::endl;
#endif

    Impl *adapter = lookupAdapter(handle);
    if (!adapter) return;
    Plugin::ParameterList &list = adapter->m_parameters;
    ((Plugin *)handle)->setParameter(list[param].identifier, value);
    adapter->markOutputsChanged((Plugin *)handle);
}

unsigned int
PluginAdapterBase::Impl::vampGetCurrentProgram(VampPluginHandle handle)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampGetCurrentProgram(" << handle << ")" << std::endl;
#endif

    Impl *adapter = lookupAdapter(handle);
    if (!adapter) return 0;
    Plugin::ProgramList &list = adapter->m_programs;
    std::string program = ((Plugin *)handle)->getCurrentProgram();
    for (unsigned int i = 0; i < list.size(); ++i) {
        if (list[i] == program) return i;
    }
    return 0;
}

void
PluginAdapterBase::Impl::vampSelectProgram(VampPluginHandle handle,
                                           unsigned int program)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampSelectProgram(" << handle << ", " << program << ")" << std::endl;
#endif

    Impl *adapter = lookupAdapter(handle);
    if (!adapter) return;

    Plugin::ProgramList &list = adapter->m_programs;
    ((Plugin *)handle)->selectProgram(list[program]);

    adapter->markOutputsChanged((Plugin *)handle);
}

unsigned int
PluginAdapterBase::Impl::vampGetPreferredStepSize(VampPluginHandle handle)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampGetPreferredStepSize(" << handle << ")" << std::endl;
#endif

    return ((Plugin *)handle)->getPreferredStepSize();
}

unsigned int
PluginAdapterBase::Impl::vampGetPreferredBlockSize(VampPluginHandle handle)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampGetPreferredBlockSize(" << handle << ")" << std::endl;
#endif

    return ((Plugin *)handle)->getPreferredBlockSize();
}

unsigned int
PluginAdapterBase::Impl::vampGetMinChannelCount(VampPluginHandle handle)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampGetMinChannelCount(" << handle << ")" << std::endl;
#endif

    return ((Plugin *)handle)->getMinChannelCount();
}

unsigned int
PluginAdapterBase::Impl::vampGetMaxChannelCount(VampPluginHandle handle)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampGetMaxChannelCount(" << handle << ")" << std::endl;
#endif

    return ((Plugin *)handle)->getMaxChannelCount();
}

unsigned int
PluginAdapterBase::Impl::vampGetOutputCount(VampPluginHandle handle)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampGetOutputCount(" << handle << ")" << std::endl;
#endif

    Impl *adapter = lookupAdapter(handle);

//    std::cerr << "vampGetOutputCount: handle " << handle << " -> adapter "<< adapter << std::endl;

    if (!adapter) return 0;
    return adapter->getOutputCount((Plugin *)handle);
}

VampOutputDescriptor *
PluginAdapterBase::Impl::vampGetOutputDescriptor(VampPluginHandle handle,
                                                 unsigned int i)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampGetOutputDescriptor(" << handle << ", " << i << ")" << std::endl;
#endif

    Impl *adapter = lookupAdapter(handle);

//    std::cerr << "vampGetOutputDescriptor: handle " << handle << " -> adapter "<< adapter << std::endl;

    if (!adapter) return 0;
    return adapter->getOutputDescriptor((Plugin *)handle, i);
}

void
PluginAdapterBase::Impl::vampReleaseOutputDescriptor(VampOutputDescriptor *desc)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampReleaseOutputDescriptor(" << desc << ")" << std::endl;
#endif

    if (desc->identifier) free((void *)desc->identifier);
    if (desc->name) free((void *)desc->name);
    if (desc->description) free((void *)desc->description);
    if (desc->unit) free((void *)desc->unit);
    if (desc->hasFixedBinCount && desc->binNames) {
        for (unsigned int i = 0; i < desc->binCount; ++i) {
            if (desc->binNames[i]) {
                free((void *)desc->binNames[i]);
            }
        }
    }
    if (desc->binNames) free((void *)desc->binNames);
    free((void *)desc);
}

VampFeatureList *
PluginAdapterBase::Impl::vampProcess(VampPluginHandle handle,
                                     const float *const *inputBuffers,
                                     int sec,
                                     int nsec)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampProcess(" << handle << ", " << sec << ", " << nsec << ")" << std::endl;
#endif

    Impl *adapter = lookupAdapter(handle);
    if (!adapter) return 0;
    return adapter->process((Plugin *)handle, inputBuffers, sec, nsec);
}

VampFeatureList *
PluginAdapterBase::Impl::vampGetRemainingFeatures(VampPluginHandle handle)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampGetRemainingFeatures(" << handle << ")" << std::endl;
#endif

    Impl *adapter = lookupAdapter(handle);
    if (!adapter) return 0;
    return adapter->getRemainingFeatures((Plugin *)handle);
}

void
PluginAdapterBase::Impl::vampReleaseFeatureSet(VampFeatureList *)
{
#ifdef DEBUG_PLUGIN_ADAPTER
    std::cerr << "PluginAdapterBase::Impl::vampReleaseFeatureSet" << std::endl;
#endif
}

void
PluginAdapterBase::Impl::cleanup(Plugin *plugin)
{
    if (m_fs.find(plugin) != m_fs.end()) {
        size_t outputCount = 0;
        if (m_pluginOutputs[plugin]) {
            outputCount = m_pluginOutputs[plugin]->size();
        }
        VampFeatureList *list = m_fs[plugin];
        for (unsigned int i = 0; i < outputCount; ++i) {
            for (unsigned int j = 0; j < m_fsizes[plugin][i]; ++j) {
                if (list[i].features[j].v1.label) {
                    free(list[i].features[j].v1.label);
                }
                if (list[i].features[j].v1.values) {
                    free(list[i].features[j].v1.values);
                }
            }
            if (list[i].features) free(list[i].features);
        }
        m_fs.erase(plugin);
        m_fsizes.erase(plugin);
        m_fvsizes.erase(plugin);
    }

    if (m_pluginOutputs.find(plugin) != m_pluginOutputs.end()) {
        delete m_pluginOutputs[plugin];
        m_pluginOutputs.erase(plugin);
    }

    if (m_adapterMap) {
        m_adapterMap->erase(plugin);

        if (m_adapterMap->empty()) {
            delete m_adapterMap;
            m_adapterMap = 0;
        }
    }

    delete ((Plugin *)plugin);
}

void
PluginAdapterBase::Impl::checkOutputMap(Plugin *plugin)
{
    OutputMap::iterator i = m_pluginOutputs.find(plugin);

    if (i == m_pluginOutputs.end() || !i->second) {

        m_pluginOutputs[plugin] = new Plugin::OutputList
            (plugin->getOutputDescriptors());

//        std::cerr << "PluginAdapterBase::Impl::checkOutputMap: Have " << m_pluginOutputs[plugin]->size() << " outputs for plugin " << plugin->getIdentifier() << std::endl;
    }
}

void
PluginAdapterBase::Impl::markOutputsChanged(Plugin *plugin)
{
    OutputMap::iterator i = m_pluginOutputs.find(plugin);

//    std::cerr << "PluginAdapterBase::Impl::markOutputsChanged" << std::endl;

    if (i != m_pluginOutputs.end()) {

        Plugin::OutputList *list = i->second;
        m_pluginOutputs.erase(i);
        delete list;
    }
}

unsigned int
PluginAdapterBase::Impl::getOutputCount(Plugin *plugin)
{
    checkOutputMap(plugin);

    return m_pluginOutputs[plugin]->size();
}

VampOutputDescriptor *
PluginAdapterBase::Impl::getOutputDescriptor(Plugin *plugin,
                                             unsigned int i)
{
    checkOutputMap(plugin);

    Plugin::OutputDescriptor &od =
        (*m_pluginOutputs[plugin])[i];

    VampOutputDescriptor *desc = (VampOutputDescriptor *)
        malloc(sizeof(VampOutputDescriptor));

    desc->identifier = strdup(od.identifier.c_str());
    desc->name = strdup(od.name.c_str());
    desc->description = strdup(od.description.c_str());
    desc->unit = strdup(od.unit.c_str());
    desc->hasFixedBinCount = od.hasFixedBinCount;
    desc->binCount = od.binCount;

    if (od.hasFixedBinCount && od.binCount > 0
        // We would like to do "&& !od.binNames.empty()" here -- but we
        // can't, because it will crash older versions of the host adapter
        // which try to copy the names across whenever the bin count is
        // non-zero, regardless of whether they exist or not
        ) {
        desc->binNames = (const char **)
            malloc(od.binCount * sizeof(const char *));

        for (unsigned int i = 0; i < od.binCount; ++i) {
            if (i < od.binNames.size()) {
                desc->binNames[i] = strdup(od.binNames[i].c_str());
            } else {
                desc->binNames[i] = 0;
            }
        }
    } else {
        desc->binNames = 0;
    }

    desc->hasKnownExtents = od.hasKnownExtents;
    desc->minValue = od.minValue;
    desc->maxValue = od.maxValue;
    desc->isQuantized = od.isQuantized;
    desc->quantizeStep = od.quantizeStep;

    switch (od.sampleType) {
    case Plugin::OutputDescriptor::OneSamplePerStep:
        desc->sampleType = vampOneSamplePerStep; break;
    case Plugin::OutputDescriptor::FixedSampleRate:
        desc->sampleType = vampFixedSampleRate; break;
    case Plugin::OutputDescriptor::VariableSampleRate:
        desc->sampleType = vampVariableSampleRate; break;
    }

    desc->sampleRate = od.sampleRate;
    desc->hasDuration = od.hasDuration;

    return desc;
}

VampFeatureList *
PluginAdapterBase::Impl::process(Plugin *plugin,
                                 const float *const *inputBuffers,
                                 int sec, int nsec)
{
//    std::cerr << "PluginAdapterBase::Impl::process" << std::endl;
    RealTime rt(sec, nsec);
    checkOutputMap(plugin);
    return convertFeatures(plugin, plugin->process(inputBuffers, rt));
}

VampFeatureList *
PluginAdapterBase::Impl::getRemainingFeatures(Plugin *plugin)
{
//    std::cerr << "PluginAdapterBase::Impl::getRemainingFeatures" << std::endl;
    checkOutputMap(plugin);
    return convertFeatures(plugin, plugin->getRemainingFeatures());
}

VampFeatureList *
PluginAdapterBase::Impl::convertFeatures(Plugin *plugin,
                                         const Plugin::FeatureSet &features)
{
    int lastN = -1;

    int outputCount = 0;
    if (m_pluginOutputs[plugin]) outputCount = m_pluginOutputs[plugin]->size();

    resizeFS(plugin, outputCount);
    VampFeatureList *fs = m_fs[plugin];

//    std::cerr << "PluginAdapter(v2)::convertFeatures: NOTE: sizeof(Feature) == " << sizeof(Plugin::Feature) << ", sizeof(VampFeature) == " << sizeof(VampFeature) << ", sizeof(VampFeatureList) == " << sizeof(VampFeatureList) << std::endl;

    for (Plugin::FeatureSet::const_iterator fi = features.begin();
         fi != features.end(); ++fi) {

        int n = fi->first;

//        std::cerr << "PluginAdapterBase::Impl::convertFeatures: n = " << n << std::endl;

        if (n >= int(outputCount)) {
            std::cerr << "WARNING: PluginAdapterBase::Impl::convertFeatures: Too many outputs from plugin (" << n+1 << ", only should be " << outputCount << ")" << std::endl;
            continue;
        }

        if (n > lastN + 1) {
            for (int i = lastN + 1; i < n; ++i) {
                fs[i].featureCount = 0;
            }
        }

        const Plugin::FeatureList &fl = fi->second;

        size_t sz = fl.size();
        if (sz > m_fsizes[plugin][n]) resizeFL(plugin, n, sz);
        fs[n].featureCount = sz;

        for (size_t j = 0; j < sz; ++j) {

//            std::cerr << "PluginAdapterBase::Impl::convertFeatures: j = " << j << std::endl;

            VampFeature *feature = &fs[n].features[j].v1;

            feature->hasTimestamp = fl[j].hasTimestamp;
            feature->sec = fl[j].timestamp.sec;
            feature->nsec = fl[j].timestamp.nsec;
            feature->valueCount = fl[j].values.size();

            VampFeatureV2 *v2 = &fs[n].features[j + sz].v2;

            v2->hasDuration = fl[j].hasDuration;
            v2->durationSec = fl[j].duration.sec;
            v2->durationNsec = fl[j].duration.nsec;

            if (feature->label) free(feature->label);

            if (fl[j].label.empty()) {
                feature->label = 0;
            } else {
                feature->label = strdup(fl[j].label.c_str());
            }

            if (feature->valueCount > m_fvsizes[plugin][n][j]) {
                resizeFV(plugin, n, j, feature->valueCount);
            }

            for (unsigned int k = 0; k < feature->valueCount; ++k) {
//                std::cerr << "PluginAdapterBase::Impl::convertFeatures: k = " << k << std::endl;
                feature->values[k] = fl[j].values[k];
            }
        }

        lastN = n;
    }

    if (lastN == -1) return 0;

    if (int(outputCount) > lastN + 1) {
        for (int i = lastN + 1; i < int(outputCount); ++i) {
            fs[i].featureCount = 0;
        }
    }

//    std::cerr << "PluginAdapter(v2)::convertFeatures: NOTE: have " << outputCount << " outputs" << std::endl;
//    for (int i = 0; i < outputCount; ++i) {
//        std::cerr << "PluginAdapter(v2)::convertFeatures: NOTE: output " << i << " has " << fs[i].featureCount << " features" << std::endl;
//    }

    return fs;
}

void
PluginAdapterBase::Impl::resizeFS(Plugin *plugin, int n)
{
//    std::cerr << "PluginAdapterBase::Impl::resizeFS(" << plugin << ", " << n << ")" << std::endl;

    int i = m_fsizes[plugin].size();
    if (i >= n) return;

//    std::cerr << "resizing from " << i << std::endl;

    m_fs[plugin] = (VampFeatureList *)realloc
        (m_fs[plugin], n * sizeof(VampFeatureList));

    while (i < n) {
        m_fs[plugin][i].featureCount = 0;
        m_fs[plugin][i].features = 0;
        m_fsizes[plugin].push_back(0);
        m_fvsizes[plugin].push_back(std::vector<size_t>());
        i++;
    }
}

void
PluginAdapterBase::Impl::resizeFL(Plugin *plugin, int n, size_t sz)
{
//    std::cerr << "PluginAdapterBase::Impl::resizeFL(" << plugin << ", " << n << ", "
//              << sz << ")" << std::endl;

    size_t i = m_fsizes[plugin][n];
    if (i >= sz) return;

//    std::cerr << "resizing from " << i << std::endl;

    m_fs[plugin][n].features = (VampFeatureUnion *)realloc
        (m_fs[plugin][n].features, 2 * sz * sizeof(VampFeatureUnion));

    while (m_fsizes[plugin][n] < sz) {
        m_fs[plugin][n].features[m_fsizes[plugin][n]].v1.hasTimestamp = 0;
        m_fs[plugin][n].features[m_fsizes[plugin][n]].v1.valueCount = 0;
        m_fs[plugin][n].features[m_fsizes[plugin][n]].v1.values = 0;
        m_fs[plugin][n].features[m_fsizes[plugin][n]].v1.label = 0;
        m_fs[plugin][n].features[m_fsizes[plugin][n] + sz].v2.hasDuration = 0;
        m_fvsizes[plugin][n].push_back(0);
        m_fsizes[plugin][n]++;
    }
}

void
PluginAdapterBase::Impl::resizeFV(Plugin *plugin, int n, int j, size_t sz)
{
//    std::cerr << "PluginAdapterBase::Impl::resizeFV(" << plugin << ", " << n << ", "
//              << j << ", " << sz << ")" << std::endl;

    size_t i = m_fvsizes[plugin][n][j];
    if (i >= sz) return;

//    std::cerr << "resizing from " << i << std::endl;

    m_fs[plugin][n].features[j].v1.values = (float *)realloc
        (m_fs[plugin][n].features[j].v1.values, sz * sizeof(float));

    m_fvsizes[plugin][n][j] = sz;
}

PluginAdapterBase::Impl::AdapterMap *
PluginAdapterBase::Impl::m_adapterMap = 0;

}

_VAMP_SDK_PLUGSPACE_END(PluginAdapter.cpp)


text:
import React, {FunctionComponent, useEffect} from 'react'
import {connect, ConnectedProps, useDispatch} from 'react-redux'
import {withRouter, RouteComponentProps} from 'react-router-dom'

// Components
import {Overlay, SpinnerContainer, TechnoSpinner} from '@influxdata/clockface'
import CheckEOHeader from 'src/checks/components/CheckEOHeader'
import TimeMachine from 'src/timeMachine/components/TimeMachine'

// Actions
import {createCheckFromTimeMachine} from 'src/checks/actions/thunks'
import {setActiveTimeMachine} from 'src/timeMachine/actions'
import {
  resetAlertBuilder,
  updateName,
  initializeAlertBuilder,
} from 'src/alerting/actions/alertBuilder'

// Utils
import {createView} from 'src/views/helpers'

// Types
import {AppState, RemoteDataState, CheckViewProperties} from 'src/types'

type ReduxProps = ConnectedProps<typeof connector>
type Props = ReduxProps & RouteComponentProps<{orgID: string}>

const NewCheckOverlay: FunctionComponent<Props> = ({
  status,
  match: {
    params: {orgID},
  },
  checkName,
  history,
  onSaveCheckFromTimeMachine,
  onResetAlertBuilder,
  onUpdateAlertBuilderName,
}) => {
  const dispatch = useDispatch()

  useEffect(() => {
    const view = createView<CheckViewProperties>('threshold')
    dispatch(initializeAlertBuilder('threshold'))
    dispatch(
      setActiveTimeMachine('alerting', {
        view,
      })
    )
  }, [dispatch])

  const handleClose = () => {
    history.push(`/orgs/${orgID}/alerting`)
    onResetAlertBuilder()
  }

  return (
    <Overlay visible={true} className="veo-overlay">

        <SpinnerContainer
          spinnerComponent={<TechnoSpinner />}
          loading={status || RemoteDataState.Loading}
        >
          <CheckEOHeader
            key={checkName}
            name={checkName}
            onSetName={onUpdateAlertBuilderName}
            onCancel={handleClose}
            onSave={onSaveCheckFromTimeMachine}
          />

            <TimeMachine />

        </SpinnerContainer>

    </Overlay>
  )
}

const mstp = ({alertBuilder: {name, status}}: AppState) => {
  return {checkName: name, status}
}

const mdtp = {
  onSaveCheckFromTimeMachine: createCheckFromTimeMachine as any,
  onResetAlertBuilder: resetAlertBuilder,
  onUpdateAlertBuilderName: updateName,
}

const connector = connect(mstp, mdtp)

export default connector(withRouter(NewCheckOverlay))


text:
package com.github.mikhailerofeev.runity.domain.entities;

import com.github.mikhailerofeev.runity.domain.values.ParamValueWithVersionId;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;

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

/**
 * @author m-erofeev
 * @since 25.04.14
 */
public class Employee {

    @Id
    private String id;
    private String name;

    //detalisation for mongo purpose
    private Map<String, ArrayList<ParamValueWithVersionId>> param2valueAndVersion;
    private Map<String, Pair<Integer, Integer>> paramRating;

    //for seriazation purposes
    Employee() {

    }

    public Employee(String name) {
        this.name = name;
        param2valueAndVersion = Maps.newHashMap();
        paramRating = Maps.newHashMap();
    }

    public Employee(String name, Map<String, ArrayList<ParamValueWithVersionId>> param2valueAndVersion) {
        this.name = name;
        this.param2valueAndVersion = param2valueAndVersion;
        paramRating = Maps.newHashMap();
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Map<String, ArrayList<ParamValueWithVersionId>> getParam2valueAndVersion() {
        return Collections.unmodifiableMap(param2valueAndVersion);
    }

    @Override
    public String toString() {
        return new Gson().toJson(this);
    }

    public void addParam(String names, ParamValueWithVersionId newValue) {
        ArrayList<ParamValueWithVersionId> values = param2valueAndVersion.get(names);
        if (values == null) {
            values = Lists.newArrayList();
            param2valueAndVersion.put(names, values);
        }
        if (newValue.isActual()) {
            for (ParamValueWithVersionId value : values) {
                value.setActual(false);
            }
        }
        values.add(newValue);
    }

    public String getActualParamVaue(String paramName) {
        final List<ParamValueWithVersionId> values = param2valueAndVersion.get(paramName);
        if (values == null) {
            return null;
        }
        for (ParamValueWithVersionId paramValueWithVersionId : values) {
            if (paramValueWithVersionId.isActual()) {
                return paramValueWithVersionId.getValue();
            }
        }
        return null;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Employee)) return false;

        Employee employee = (Employee) o;

        if (id != null ? !id.equals(employee.id) : employee.id != null) return false;
        if (name != null ? !name.equals(employee.name) : employee.name != null) return false;
        if (param2valueAndVersion != null ? !param2valueAndVersion.equals(employee.param2valueAndVersion) : employee.param2valueAndVersion != null)
            return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (param2valueAndVersion != null ? param2valueAndVersion.hashCode() : 0);
        return result;
    }

    public Map<String, Pair<Integer, Integer>> getParamRating() {
        return paramRating;
    }

    public void addParamRating(String param) {
        this.paramRating.put(param, Pair.of(0, 0));
    }
    public void setParamRating(Map<String, Pair<Integer, Integer>> paramRating) {
        if(paramRating == null) {
            this.paramRating = Maps.newHashMap();
        }else{
            this.paramRating = paramRating;
        }
    }

    public void increaseParamRating(String param) {
        Pair<Integer, Integer> rating = this.paramRating.get(param);
        Pair<Integer, Integer> newRating = Pair.of(rating.getKey() + 1, rating.getValue());
        this.paramRating.remove(param);
        this.paramRating.put(param, newRating);
    }

    public void decreaseParamRating(String param) {
        Pair<Integer, Integer> rating = this.paramRating.get(param);
        Pair<Integer, Integer> newRating = Pair.of(rating.getKey(), rating.getValue() + 1);
        this.paramRating.remove(param);
        this.paramRating.put(param, newRating);
    }
}


text:
import { module } from 'substance-test'

import TestHTMLImporter from '../model/TestHTMLImporter'
import DOMElement from '../../ui/DefaultDOMElement'

const test = module('model/HTMLImporter')

var CONTENT = '0123456789'

test("Importing paragraph", function(t) {
  let importer = new TestHTMLImporter()
  var html = '
' + CONTENT + '
'
  var el = DOMElement.parseHTML(html)
  var node = importer.convertElement(el)
  t.deepEqual(node.toJSON(), {
    id: "p1",
    type: "paragraph",
    content: CONTENT
  }, 'paragraph should have been imported correctly')
  t.end()
})

test("Importing paragraph with strong", function(t) {
  let importer = new TestHTMLImporter()
  var html = '
0123456789
'
  var el = DOMElement.parseHTML(html)
  importer.convertElement(el)
  var doc = importer.generateDocument()
  var p1 = doc.get('p1')
  var s1 = doc.get('s1')
  t.equal(CONTENT, p1.content, 'paragraph should have correct content')
  t.equal('456', s1.getText(), 'annotation should provide correct text')
  t.end()
})

test("Importing h1", function(t) {
  let importer = new TestHTMLImporter()
  var html = '
' + CONTENT + '
'
  var el = DOMElement.parseHTML(html)
  var node = importer.convertElement(el)
  t.deepEqual(node.toJSON(), {
    id: "h1",
    type: "heading",
    level: 1,
    content: CONTENT
  }, 'heading should have been imported correctly')
  t.end()
})

test("Importing h2", function(t) {
  let importer = new TestHTMLImporter()
  var html = '
' + CONTENT + '
'
  var el = DOMElement.parseHTML(html)
  var node = importer.convertElement(el)
  t.deepEqual(node.toJSON(), {
    id: "h2",
    type: "heading",
    level: 2,
    content: CONTENT
  }, 'heading should have been imported correctly')
  t.end()
})


text:
import {LoginComponent} from "./login.component";
import {SignupComponent} from "./signup.component";

export const AUTH_DECLARATIONS = [
  LoginComponent,
  SignupComponent,
];


text:
import * as sinon from 'sinon';
import { context } from 'mocha-typescript';

interface InlineSpy {
    target: object;
    func: string;
}

interface DefinedSpy extends InlineSpy {
    restore: sinon.SinonSpy;
}

/**
 * a unit test base class
 */
export class UnitTestContext {

    // the private context save storage
    @context
    private objectStore: { [index: string]: any } = {};

    // the registered spies in the context
    @context
    private spies: DefinedSpy[] = [];

    /**
     * add a var to the class context
     *
     * @param name the name, important to get it later
     * @param obj the object to store
     */
    public add(name: string, obj: any): void {

        this.objectStore[name] = obj;
    }

    /**
     * get a var from the context
     *
     * @param name the name
     */
    public get<T = any>(name: string): T {

        return this.objectStore[name] as T;
    }

    /**
     * creates a sinon spy on the target object and watches the function
     *
     * @param target the object to spy on
     * @param func the function name to spy on (do not work for static functions)
     */
    public addSpy(target: object, func: string): void {

        // spy on the target
        const newSpyFunction = sinon.stub(target, func);

        // save the spie
        if (newSpyFunction)
            this.spies.push({
                target,
                func,
                restore: newSpyFunction
            });
    }

    /**
     * get a sinon spy from a spied object
     *
     * @param target the spied object
     * @param func the spied function name
     */
    public getSpy(target: { [func: string]: any }, func: string): sinon.SinonSpy {

        // check if the object is a spy
        const spy = this.spies.find((theSpy) => theSpy.target === target && theSpy.func === func);

        // does the spy exist
        if (!spy) {
            throw new Error('Never spied on function ' + func);
        }

        // cast the spy
        return (spy.target as any)[spy.func] as sinon.SinonSpy;
    }

    /**
     * remove the given spies
     *
     * @param spies the spies to remove
     */
    public removeSpy(...spies: InlineSpy[]): void {

        // restore all
        spies.forEach((spy) => {

            // find defined spy
            spy = this.spies.find((s) => s.target === spy.target && s.func === spy.func);

            // parse the target
            const target = (spy.target as any)[spy.func];

            // check if the restore function is available
            if (typeof target.restore === 'function') {

                // restore using it dedicated function
                target.restore();
            } else {

                // restore using the original function
                (spy.target as any)[spy.func] = (spy as DefinedSpy).restore;
            }
        });
    }

    /**
     * removes all spies from this text
     */
    public removeAllSpies(): void {

        this.removeSpy(...this.spies);
    }

}


text:
<html>
<head>
<meta http-equiv="refresh" content="0; URL=as_jdbc-translators.html" />
</head>
</html>


text:
'use strict';

/* Controllers */

var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', function ($scope) {
  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.',
	 'age': 1},
    {'name': 'Motorola XOOM™ with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.',
	 'age': 2},
    {'name': 'MOTOROLA XOOM™',
     'snippet': 'The Next, Next Generation tablet.',
	 'age': 3}
  ];

  $scope.orderProp = 'age';
});


text:
<script type="text/javascript">
  function changeTimeZone(zone) {
    idx = zone.selectedIndex;
    document.getElementById('timeZoneForm').submit();
  }
</script>
<form id="timeZoneForm">
  <?php
    include_once 'utils.inc';
    if (array_key_exists('edited_user_timezone', $_REQUEST) && !empty($_REQUEST['edited_user_timezone'])) {
      $_SESSION['ls_timezone'] = $_REQUEST['edited_user_timezone'];
    } else {
      if (!isset($_SESSION['ls_timezone'])){
        $_SESSION['ls_timezone'] = 'GMT';
      }
    }

  date_default_timezone_set($_SESSION['ls_timezone']);

  print date('m/d/Y H:i:s') . "<br>Timezone: ";
  print get_tz_options(date_default_timezone_get(), "edited_user_timezone", "Timezone", "", "changeTimeZone(this);");
  ?>
</form>


text:
srcdir=`dirname $0`

# name of the current package
PKG_NAME=`basename \`(cd $srcdir; pwd)\``

# default configure options
conf_flags="--enable-debug --with-debug"

DIE=0
libtool=0
gettext=0
run_automake=0
libtoolize=libtoolize

if which glibtoolize >/dev/null 2>&1 ; then
    libtoolize=glibtoolize
fi

missing() {
  echo
  echo "**Error**: You must have \`$1' installed to compile $PKG_NAME."
  echo "Download the appropriate package for your distribution,"
  echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/"
  DIE=1
}

(aclocal --version) < /dev/null > /dev/null 2>&1 || missing aclocal
(autoconf --version) < /dev/null > /dev/null 2>&1 || missing autoconf

grep "^AM_GNU_GETTEXT" $srcdir/configure.ac >/dev/null && gettext=1
grep "^AC_PROG_LIBTOOL" $srcdir/configure.ac >/dev/null && libtool=1
grep "^AM_INIT_AUTOMAKE" $srcdir/configure.ac >/dev/null && run_automake=1

if test "$gettext" -eq 1; then
  grep "sed.*POTFILES" $srcdir/configure.ac >/dev/null || \
  (gettextize --version) < /dev/null > /dev/null 2>&1 || missing gettext
fi

if test "$libtool" -eq 1; then
  ($libtoolize --version) < /dev/null > /dev/null 2>&1 || missing libtool
fi

if test "$DIE" -eq 1; then
  exit 1
fi

if test -z "$*"; then
  echo "**Warning**: I am going to run \`configure' with default arguments."
  echo "If you wish to pass any others to it, please specify them on the"
  echo \`$0\'" command line."
  echo
else
  unset conf_flags
fi

if test  "$gettext" -eq 1; then
  echo "Running gettextize...  Ignore non-fatal messages."
  echo "no" | gettextize --force --copy
fi

if test  "$libtool" -eq 1; then
  echo "Running libtoolize..."
  $libtoolize --force --copy
fi

echo "Running aclocal..."
aclocal -I m4

echo "Running autoheader..."
autoheader
echo "Running autoconf ..."
autoconf

if test  "$run_automake" -eq 1; then
  echo "Running automake..."
  automake --add-missing --foreign --force --copy
fi

if test x$NOCONFIGURE = x; then
  echo Running $srcdir/configure $conf_flags "$@" ...
  $srcdir/configure $conf_flags "$@" \
  && echo Now type \`make\' to compile $PKG_NAME
else
  echo Skipping configure process.
fi

#if which jade >/dev/null; then
#	echo "Generate documentation ..."
#	(cd doc && make doc)
#fi


text:
/*
	Extern implementation of Nit module time
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include "core__time._ffi.h"
#ifdef ANDROID
	#include <android/log.h>
	#define PRINT_ERROR(...) (void)__android_log_print(ANDROID_LOG_WARN, "Nit", __VA_ARGS__)
#else
	#define PRINT_ERROR(...) fprintf(stderr, __VA_ARGS__)
#endif
#define CString_to_s core__time___CString_to_s
#define String_to_cstring core__time___String_to_cstring
long core__time___Sys_get_time___impl( Sys self )
{
#line 24 "../lib/core/time.nit"

 return time(NULL); }


text:
using namespace lldb;
using namespace lldb_private;

ScriptInterpreter::ScriptInterpreter (CommandInterpreter &interpreter, lldb::ScriptLanguage script_lang) :
    m_interpreter (interpreter),
    m_script_lang (script_lang)
{
}

ScriptInterpreter::~ScriptInterpreter ()
{
}

CommandInterpreter &
ScriptInterpreter::GetCommandInterpreter ()
{
    return m_interpreter;
}

void
ScriptInterpreter::CollectDataForBreakpointCommandCallback
(
    BreakpointOptions *bp_options,
    CommandReturnObject &result
)
{
    result.SetStatus (eReturnStatusFailed);
    result.AppendError ("ScriptInterpreter::GetScriptCommands(StringList &) is not implemented.");
}

void
ScriptInterpreter::CollectDataForWatchpointCommandCallback
(
    WatchpointOptions *bp_options,
    CommandReturnObject &result
)
{
    result.SetStatus (eReturnStatusFailed);
    result.AppendError ("ScriptInterpreter::GetScriptCommands(StringList &) is not implemented.");
}

std::string
ScriptInterpreter::LanguageToString (lldb::ScriptLanguage language)
{
    std::string return_value;

    switch (language)
    {
        case eScriptLanguageNone:
            return_value = "None";
            break;
        case eScriptLanguagePython:
            return_value = "Python";
            break;
    }

    return return_value;
}

std::unique_ptr<ScriptInterpreterLocker>
ScriptInterpreter::AcquireInterpreterLock ()
{
    return std::unique_ptr<ScriptInterpreterLocker>(new ScriptInterpreterLocker());
}

void
ScriptInterpreter::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
{
#ifndef LLDB_DISABLE_PYTHON
    ScriptInterpreterPython::InitializeInterpreter (python_swig_init_callback);
#endif // #ifndef LLDB_DISABLE_PYTHON
}

void
ScriptInterpreter::TerminateInterpreter ()
{
#ifndef LLDB_DISABLE_PYTHON
    ScriptInterpreterPython::TerminateInterpreter ();
#endif // #ifndef LLDB_DISABLE_PYTHON
}