text:
from uuid import uuid4

import requests
from isodate import duration_isoformat

from ngsi.models import ApiError

class Client(object):
    def __init__(self, host, port=1026):
        self.host = host
        self.port = port
        self._base_url = \
            'http://' + str(self.host) + ':' + str(self.port) + '/'
        self._headers = {
            'Accept': 'application/json',
            'Content-type': 'application/json'
        }
        self._api_url_v1 = self._base_url + 'v1/'

    def version(self):
        """
        Returns context broker version
        """
        response = requests.get(
            self._base_url + 'version',
            headers=self._headers)
        return response.json()['orion']

    def create_context(self, elements):
        return self._update_context(elements, action='APPEND')

    def get_context(self, entities, attributes=None):
        return self._query_context(entities, attributes)

    def update_context(self, elements):
        return self._update_context(elements, action='UPDATE')

    def subscribe_context(self,
                          entities,
                          callback_url,
                          duration,
                          notification_type,
                          attributes=None,
                          throttling=None):
        return self._subscribe_context(
            entities,
            callback_url,
            duration,
            notification_type,
            attributes,
            throttling
        )

    def update_context_subscription(self, subscription_id, **kwargs):
        return self._update_context_subscription(
            subscriptionId=subscription_id,
            **kwargs
        )

    def unsubscribe_context(self, subscription_id):
        return self._unsubscribe_context(
            subscriptionId=subscription_id
        )

    def _update_context(self, elements, action=None):
        data = {}
        data['contextElements'] = elements
        if action:
            data['updateAction'] = action
        return self._call_api(method='post', url='updateContext', json=data)

    def _query_context(self, entities, attributes=None):
        data = {}
        data['entities'] = entities
        if attributes:
            data['attributes'] = attributes
        return self._call_api(method='post', url='queryContext', json=data)

    def _subscribe_context(self,
                          entities,
                          callback_url,
                          duration,
                          notification_conditions,
                          attributes=None,
                          throttling=None):
        data = {}
        data['entities'] = entities
        data['reference'] = callback_url
        data['duration'] = duration_isoformat(duration)
        data['notifyConditions'] = notification_conditions
        if attributes:
            data['attributes'] = attributes
        if throttling:
            data['throttling'] = duration_isoformat(throttling)
        return self._call_api(method='post', url='subscribeContext', json=data)

    def _update_context_subscription(self, **kwargs):
        return self._call_api(
            method='post',
            url='updateContextSubscription',
            json=kwargs
        )

    def _unsubscribe_context(self, **kwargs):
        return self._call_api(
            method='post',
            url='unsubscribeContext',
            json=kwargs
        )

    def _call_api(self, method, url, params=None, json=None):
        """
        A simple wrapper around host requests
        """
        response = requests.request(
            method,
            self._api_url_v1+url,
            params=params,
            headers=self._headers,
            json=json
        )
        response.raise_for_status()
        json_response = response.json()
        if 'contextResponses' in json_response:
            return json_response['contextResponses']
        elif 'subscribeResponse' in json_response:
            return json_response['subscribeResponse']
        elif 'statusCode' in json_response:
            # unsubscribe context response
            if json_response['statusCode']['code']!='200':
                print json
                raise ApiError('Error code ' +
                                 json_response['statusCode']['code'] + ': ' +
                                 json_response['statusCode']['reasonPhrase'])
            return json_response
        elif 'errorCode' in json_response:
            error = json_response['errorCode']
            raise ApiError('Error code ' +
                             error['code'] + ': ' +
                             error['reasonPhrase'])


text:
require File.expand_path('spec_helper', File.dirname(__FILE__))
require File.expand_path('model_factory', File.dirname(__FILE__))

shared_examples_for "page with keyword and description" do
  it "should set the keywords meta tag" do
    do_get
    assert_xpath "//meta[@name='keywords'][@content='#{@keywords}']"
  end

  it "should set description meta tag" do
    do_get
    assert_xpath "//meta[@name='description'][@content='#{@description}']"
  end
end

shared_examples_for "page that can display menus" do
  it "should not display menu by default" do
    do_get
    last_response.should be_ok
    assert_not_selector "#sidebar ul.menu"
  end

  describe "and simple menu configured" do
    before(:each) do
      create_menu(@category.path)
    end

    it "should link to top level menu items" do
      do_get
      link_text = @category.link_text
      href = @category.abspath
      assert_selector "ul.menu a[@href$='#{href}']:contains('#{link_text}')"
    end
  end

  describe "and nested menu configured" do
    before(:each) do
      @level2 = create_category(path: "level-2", heading: "Level 2",
                                metadata: {'link text' => "Level 2 link"})
      @level3 = create_category(path: "level-3", heading: "Level 3")
      text = <<-EOF
#{@category.abspath}
  #{@level2.abspath}
    #{@level3.abspath}
      EOF
      create_menu(text)
    end

    it "should display first level of nested sub menus" do
      do_get
      assert_selector "ul.menu li ul li a:contains('#{@level2.link_text}')"
    end

    it "should not display nested menus to arbitrary depth" do
      do_get
      last_response.should be_ok
      assert_not_selector "ul.menu li ul li ul"
    end
  end

  describe "and menu links to home page" do
    before(:each) do
      text = <<-EOF
/
  #{@category.abspath}
EOF
      create_menu(text)
      template_path = File.expand_path(
        'templates', File.dirname(File.dirname(__FILE__)))
      @default_homepage_content = File.read(File.join(template_path,
                                                      'index.haml'))
    end

    it "should use 'Home' as the home page link if not otherwise specified" do
      create_page(
        path: 'index',
        ext: :haml,
        content: @default_homepage_content)
      do_get
      assert_selector "ul.menu a[@href='/']:contains('Home')"
    end

    it "should use the heading if it exists" do
      create_page(
        path: 'index',
        ext: :haml,
        heading: 'My heading',
        content: @default_homepage_content)
      do_get
      assert_selector "ul.menu a[@href='/']:contains('My heading')"
    end

    it "should use the link text if specified" do
      create_page(
        path: 'index',
        ext: :haml,
        heading: 'My heading',
        content: @default_homepage_content,
        metadata: {'link text'=>'My link text'})
      do_get
      assert_selector "ul.menu a[@href='/']:contains('My link text')"
    end
  end
end

describe "The layout" do
  include ModelFactory
  include RequestSpecHelper

  it "should not include GA JavaScript by default" do
    stub_configuration
    get "/"
    assert_not_selector "script", content: "ga('create', 'UA-1234'"
  end

  it "should include GA JavaScript if configured" do
    stub_config_key('google_analytics_code', 'UA-1234', rack_env: true)
    stub_configuration
    get "/"
    assert_selector 'script', content: "ga('create', 'UA-1234'"
  end
end

describe "The home page" do
  include ModelFactory
  include RequestSpecHelper

  before(:each) do
    stub_configuration
    template_path = File.expand_path(
        'templates', File.dirname(File.dirname(__FILE__)))
    create_category(
      path: 'index',
      ext: :haml,
      heading: 'Home',
      content: File.read(File.join(template_path, 'index.haml'))
    )
    create_category
  end

  after(:each) do
    remove_temp_directory
    Nesta::FileModel.purge_cache
  end

  def do_get
    get "/"
  end

  describe "when categories exist" do
    before(:each) do
      @category = create_category
    end

    it_should_behave_like "page that can display menus"
  end

  it "should render successfully" do
    do_get
    last_response.should be_ok
  end

  it "should display site title in hgroup tag" do
    do_get
    assert_selector 'hgroup h1', content: "My blog"
  end

  it "should display site subtitle in hgroup tag" do
    do_get
    assert_selector 'hgroup h2', content: "about stuff"
  end

  describe "when articles have no summary" do
    before(:each) do
      create_article
      do_get
    end

    it "should display full content of article" do
      assert_selector "p", content: "Content goes here"
    end

    it "should not display read more link" do
      last_response.should be_ok
      assert_not_selector "a", content: 'continue'
    end
  end

  describe "when articles have metadata" do
    before(:each) do
      @summary = 'Multiline\n\nsummary'
      @read_more = "Continue at your leisure"
      @article = create_article(metadata: {
        "summary" => @summary,
        "read more" => @read_more
      })
      do_get
    end

    it "should display link to article in h2 tag" do
      link_text = @article.link_text
      href = @article.abspath
      assert_selector "h1 a[@href$='#{href}']:contains('#{link_text}')"
    end

    it "should display article summary if available" do
      assert_selector 'p', content: @summary.split('\n\n').first
    end

    it "should display read more link" do
      assert_selector "a[@href$='#{@article.abspath}']", content: @read_more
    end
  end
end

describe "An article" do
  include ModelFactory
  include RequestSpecHelper

  before(:each) do
    stub_configuration
    @date = '07 September 2009'
    @keywords = 'things, stuff'
    @description = 'Page about stuff'
    @summary = 'Multiline\n\nsummary'
    @link_text = 'Link to page about stuff'
    @article = create_article(metadata: {
      'date' => @date.gsub('September', 'Sep'),
      'description' => @description,
      'keywords' => @keywords,
      'summary' => @summary,
      'link text' => @link_text
    })
  end

  after(:each) do
    remove_temp_directory
    Nesta::FileModel.purge_cache
  end

  def do_get
    get @article.abspath
  end

  it_should_behave_like "page with keyword and description"

  describe "when categories exist" do
    before(:each) do
      @category = create_category
    end

    it_should_behave_like "page that can display menus"
  end

  it "should render successfully" do
    do_get
    last_response.should be_ok
  end

  it "should display the heading" do
    do_get
    assert_selector 'h1', content: 'My article'
  end

  it "should use link text for title tag" do
    do_get
    assert_selector 'title', content: @link_text
  end

  it "should display the date" do
    do_get
    assert_selector 'time', content: @date
  end

  it "should display the content" do
    do_get
    assert_selector 'p', content: 'Content goes here'
  end

  describe "that is assigned to categories" do
    before(:each) do
      create_category(heading: 'Apple', path: 'the-apple')
      @category = create_category(heading: 'Banana', path: 'banana')
      @article = create_article(
        path: "#{@category.path}/article",
        metadata: { 'categories' => 'banana, the-apple' }
      )
    end

    it "should render successfully" do
      do_get
      last_response.should be_ok
    end

    it "should link to each category" do
      do_get
      assert_selector "p.meta a[href='/banana']", content: "Banana"
      assert_selector "p.meta a[href='/the-apple']", content: "Apple"
    end

    it "should link to a category in breadcrumb" do
      do_get
      href = @category.abspath
      link_text = @category.link_text
      assert_selector "nav.breadcrumb a[href='#{href}']", content: link_text
    end

    it "should not include Disqus comments by default" do
      do_get
      last_response.should be_ok
      assert_not_selector '#disqus_thread'
    end
  end

  describe "that is configured to show Disqus comments" do
    before(:each) do
      stub_config_key("disqus_short_name", "mysite")
      @category = create_category
    end

    it "should display Disqus comments" do
      do_get
      assert_selector '#disqus_thread'
      assert_selector 'script[@src*="mysite.disqus.com/embed.js"]'
    end
  end
end

describe "A page" do
  include ModelFactory
  include RequestSpecHelper

  before(:each) do
    stub_configuration
  end

  after(:each) do
    remove_temp_directory
    Nesta::FileModel.purge_cache
  end

  def do_get
    get @category.abspath
  end

  describe "that doesn't exist" do
    it "should render the 404 page" do
      get "/no-such-page"
      last_response.should be_not_found
    end
  end

  describe "that has meta data" do
    before(:each) do
      @title = 'Different title'
      @content = "Page content"
      @description = "Page about stuff"
      @keywords = "things, stuff"
      @articles_heading = "Posts about this stuff"
      @category = create_category(
        content: "# My category\n\n#{@content}",
        metadata: {
          'title' => @title,
          'description' => @description,
          'keywords' => @keywords,
          'articles heading' => @articles_heading
        }
      )
    end

    it_should_behave_like "page with keyword and description"
    it_should_behave_like "page that can display menus"

    describe "whose URL ends in /" do
      it "should be redirected, removing the slash" do
        get @category.abspath + '/'
        last_response.should be_redirect
      end
    end

    it "should render successfully" do
      do_get
      last_response.should be_ok
    end

    it "should display the heading" do
      do_get
      assert_selector 'h1', content: @category.heading
    end

    it "should use title metadata to set heading" do
      do_get
      assert_selector 'title', content: @title
    end

    it "should display the content" do
      do_get
      assert_selector "p", content: @content
    end

    describe "with associated pages" do
      before(:each) do
        @category1 = create_category(
          path: 'category1',
          heading: 'Category 1',
          metadata: {
            'categories' => 'category-prefix/my-category:-1'
          }
        )
        @category2 = create_category(
          path: 'category2',
          heading: 'Category 2',
          metadata: {
            'categories' => 'category-prefix/my-category:1'
          }
        )
      end

      it "should list highest priority pages at the top" do
        do_get
        assert_selector 'li:nth-child(1) h1 a', content: 'Category 2'
        assert_selector 'li:nth-child(2) h1 a', content: 'Category 1'
      end
    end

    describe "with associated articles" do
      before(:each) do
        @article = create_article(
          path: "another-page",
          heading: "Categorised",
          metadata: { categories: @category.path,
                         'link text' => 'Categorised link'},
          content: "Article content"
        )
        @article2 = create_article(
          path: "second-article", heading: "Second article")
      end

      it "should display links to articles" do
        do_get
        href = @article.abspath
        link_text = @article.link_text
        assert_selector "h1 a[@href$='#{href}']", content: link_text
        assert_not_selector "h3", content: @article2.link_text
      end

      it "should display the article heading" do
        do_get
        assert_selector 'h1', content: @articles_heading
      end
    end
  end

  describe "with associated categories" do
    it "should link to the first assigned category in breadcrumb" do
      category1 = create_category(path: 'category1', heading: 'Category 1')
      create_category(path: 'category2', heading: 'Category 2')
      @category = create_page(
        path: "a-page",
        heading: "A Page",
        metadata: { 'categories' => 'category1, category2' }
      )
      do_get
      href = category1.abspath
      link_text = category1.link_text
      assert_selector "nav.breadcrumb a[href='#{href}']", content: link_text
    end
  end
end

describe "A Haml page" do
  include ModelFactory
  include RequestSpecHelper

  before(:each) do
    stub_configuration
  end

  after(:each) do
    remove_temp_directory
    Nesta::FileModel.purge_cache
  end

  it "should be able to access helper methods" do
    create_page(
      path: "a-page",
      ext: :haml,
      content: "%div= format_date(Date.new(2010, 11, 23))",
      heading: "A Page"
    )
    get "/a-page"
    assert_selector "div", content: "23 November 2010"
  end

  it "should access helpers when rendering articles on a category page" do
    category = create_page(
      path: "a-page",
      heading: "First heading",
      content: "Blah blah"
    )
    create_article(
      path: "an-article",
      ext: :haml,
      heading: "First heading",
      metadata: { categories: category.path },
      content: "%h1 Second heading\n\n%div= format_date(Date.new(2010, 11, 23))"
    )
    get "/a-page"
    assert_selector "div", content: "23 November 2010"
  end
end

describe "attachments" do
  include ModelFactory
  include RequestSpecHelper

  before(:each) do
    stub_configuration
    create_content_directories
  end

  after(:each) do
    remove_temp_directory
    Nesta::FileModel.purge_cache
  end

  describe "in the attachments folder" do
    before(:each) do
      path = File.join(Nesta::Config.attachment_path, 'test.txt')
      File.open(path, 'w') { |file| file.write("I'm a test attachment") }
    end

    it "should be served successfully" do
      get "/attachments/test.txt"
      last_response.should be_ok
    end

    it "should be sent to the client" do
      get "/attachments/test.txt"
      body.should include("I'm a test attachment")
    end

    it "should set the appropriate MIME type" do
      get "/attachments/test.txt"
      last_response.headers["Content-Type"].should =~ Regexp.new("^text/plain")
    end
  end

  describe "outside the attachments folder" do
    before(:each) do
      path = File.join(Nesta::Config.page_path, 'index.haml')
      File.open(path, 'w') { |file| file.write('%h1 Test page') }
    end

    it "should be directory traversal free" do
      get '/attachments/../pages/index.haml'
      last_response.should_not be_ok
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
from molecule.command import lint

def test_execute(mocker, patched_logger_info, patched_yamllint, patched_flake8,
                 patched_ansible_lint, config_instance):
    l = lint.Lint(config_instance)
    l.execute()

    x = [
        mocker.call("Scenario: 'default'"),
        mocker.call("Action: 'lint'"),
    ]

    assert x == patched_logger_info.mock_calls

    patched_yamllint.assert_called_once_with()
    patched_flake8.assert_called_once_with()
    patched_ansible_lint.assert_called_once_with()


text:
'use strict';

var _ = require('lodash');
var operations = require('./../Operations');
var utils = require('../../utils');

/**
 * Implementation of $not
 * @see http://docs.mongodb.org/manual/reference/operator/query/not/
 */
module.exports = function operation(model, update, options) {
    var valid = false;
    var value = update.$not;
    if(utils.isRegExp(value)){
        value = {
            '$regex' : value
        };
    }
    _.forIn(value, function (item, key) {
        if (operations.isOperation(key)) {
            var opt = {};
            opt[key] = item;
            valid = !operations.getOperation(key)(model, opt, options);
        } else if (utils.isNestedKey(key)) {
            valid = !_.isEqual(utils.findNestedValue(model, key), item);
        }
        else {
            valid = !_.isEqual(model[key], item);
        }
    });
    return valid;
};


text:
#include "tensorflow/compiler/xla/service/cpu/cpu_executable.h"

#include <stdint.h>

#include <algorithm>
#include <set>
#include <utility>
#include <vector>

#include "absl/cleanup/cleanup.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
#include "tensorflow/compiler/xla/service/buffer_assignment.h"
#include "tensorflow/compiler/xla/service/computation_layout.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/logical_buffer.h"
#include "tensorflow/compiler/xla/service/maybe_owning_device_memory.h"
#include "tensorflow/compiler/xla/service/shaped_buffer.h"
#include "tensorflow/compiler/xla/service/xla_debug_info_manager.h"
#include "tensorflow/compiler/xla/shape_tree.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mem.h"
#include "tensorflow/stream_executor/device_memory_allocator.h"
#include "tensorflow/stream_executor/host/host_stream.h"

namespace xla {
namespace cpu {

static std::string ModuleUniqueName(absl::string_view module_name,
                                    const HloModule* module) {
  std::string unique_id;
  if (module != nullptr) {
    unique_id = absl::StrCat("module.", module->unique_id(), ".");
  }
  return absl::StrCat(unique_id, module_name);
}

CpuExecutable::CpuExecutable(
    std::unique_ptr<SimpleOrcJIT> jit,
    std::unique_ptr<const BufferAssignment> assignment,
    std::unique_ptr<HloModule> hlo_module,
    const std::string& entry_function_name,
    std::unique_ptr<HloProfilePrinterData> hlo_profile_printer_data,
    std::unique_ptr<HloProfileIndexMap> hlo_profile_index_map)
    : Executable(std::move(hlo_module), std::move(hlo_profile_printer_data),
                 std::move(hlo_profile_index_map)),
      jit_(std::move(jit)),
      assignment_(std::move(assignment)),
      module_name_(entry_function_name) {
  if (assignment_) {
    buffer_assignment_.reset(new BufferAssignmentProto(assignment_->ToProto()));
  }
  XlaDebugInfoManager::Get()->RegisterModule(
      ModuleUniqueName(module_name_, shared_module().get()), shared_module(),
      buffer_assignment_);

  // Resolve symbols in the constructor rather than at execution time to avoid
  // races because FindSymbol is not thread safe.
  llvm::Expected<llvm::JITEvaluatedSymbol> sym =
      jit_->FindCompiledSymbol(entry_function_name);
  // We expect to find the symbol provided with entry_function_name; otherwise
  // this is an internal error.
  CHECK(*sym) << "Symbol " << entry_function_name << " not found.";
  // getAddress can do work under the hood in the jit, so it needs to be
  // guarded by the mutex.
  compute_function_ = reinterpret_cast<ComputeFunctionType>(sym->getAddress());
  VLOG(1) << "compute_function_ at address "
          << reinterpret_cast<void*>(compute_function_);
  jit_->DoneCompiling();
}

CpuExecutable::~CpuExecutable() {
  XlaDebugInfoManager::Get()->UnregisterModule(
      ModuleUniqueName(module_name_, shared_module().get()), shared_module(),
      buffer_assignment_);
}

static StatusOr<MaybeOwningDeviceMemory> MemoryForAllocation(
    const BufferAllocation& allocation,
    absl::Span<ExecutionInput const> arguments,
    se::DeviceMemoryAllocator* memory_allocator, int device_ordinal) {
  VLOG(3) << allocation.ToString();
  if (allocation.is_entry_computation_parameter()) {
    se::DeviceMemoryBase out = arguments[allocation.parameter_number()]
                                   .Buffer(allocation.param_shape_index())
                                   .AsDeviceMemoryBase();
    CHECK_LE(allocation.size(), out.size())
        << "Size mismatch on param " << allocation.parameter_number()
        << " at shape index " << allocation.param_shape_index().ToString();
    VLOG(3) << "allocation is a parameter";
    return MaybeOwningDeviceMemory{out};
  } else if (allocation.is_constant()) {
    VLOG(3) << "allocation is a constant";
    return MaybeOwningDeviceMemory{se::DeviceMemoryBase{}};
  } else if (allocation.is_thread_local()) {
    VLOG(3) << "buffer is thread-local";
    return MaybeOwningDeviceMemory{se::DeviceMemoryBase{}};
  }

  int64_t buffer_size = allocation.size();
  TF_ASSIGN_OR_RETURN(se::OwningDeviceMemory out,
                      memory_allocator->Allocate(device_ordinal, buffer_size));
  VLOG(3) << "buffer allocated " << buffer_size << " bytes [" << out->opaque()
          << "]";

  // Since the output buffer and all the temporary buffers were written into
  // by the JITed code, msan has no way of knowing their memory was
  // initialized. Mark them initialized so that msan doesn't flag loads from
  // these buffers.
  ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(out->opaque(), buffer_size);
  return MaybeOwningDeviceMemory{std::move(out)};
}

StatusOr<std::vector<MaybeOwningDeviceMemory>> CpuExecutable::CreateBufferTable(
    se::DeviceMemoryAllocator* memory_allocator, int device_ordinal,
    absl::Span<ExecutionInput const> arguments) {
  std::vector<MaybeOwningDeviceMemory> buffers(
      assignment_->Allocations().size());
  VLOG(3) << "Allocating " << assignment_->Allocations().size()
          << " allocations for module " << module().name();
  for (BufferAllocation::Index i = 0; i < assignment_->Allocations().size();
       ++i) {
    const BufferAllocation& allocation = assignment_->GetAllocation(i);
    TF_ASSIGN_OR_RETURN(
        buffers[i], MemoryForAllocation(allocation, arguments, memory_allocator,
                                        device_ordinal));
  }

  if (VLOG_IS_ON(3)) {
    TF_ASSIGN_OR_RETURN(const BufferAllocation::Slice result_slice,
                        assignment_->GetUniqueTopLevelOutputSlice());
    VLOG(3) << "result index: " << result_slice.index();
  }
  return std::move(buffers);
}

Status CpuExecutable::ExecuteComputeFunction(
    const ExecutableRunOptions* run_options,
    absl::Span<MaybeOwningDeviceMemory const> buffers,
    HloExecutionProfile* hlo_execution_profile) {
  uint64_t start_micros = tensorflow::Env::Default()->NowMicros();

  XlaDebugInfoManager::Get()->OnModuleStart(module_name_);
  auto cleanup = absl::MakeCleanup(
      [&]() { XlaDebugInfoManager::Get()->OnModuleStop(module_name_); });

  size_t profile_counters_size =
      hlo_execution_profile ? hlo_execution_profile->profile_counters().size()
                            : 0;
  int64_t* profile_counters =
      hlo_execution_profile
          ? hlo_execution_profile->mutable_profile_counters()->data()
          : nullptr;

  // Call the computation function following the calling convention. See the
  // definition of 'ComputeFunctionType' for the details of the calling
  // convention of JITed functions.
  std::vector<void*> buffer_pointers;
  for (auto& buffer : buffers) {
    buffer_pointers.push_back(
        const_cast<void*>(buffer.AsDeviceMemoryBase().opaque()));
  }

  VLOG(3) << "Executing compute function:";
  VLOG(3) << absl::StrFormat("  Number of buffer table entries: %u",
                             buffer_pointers.size());
  auto ptr_printer = [](std::string* out, const void* p) {
    absl::StrAppend(out, absl::StrFormat("%p", p));
  };
  VLOG(3) << absl::StrFormat("  Buffer table: [%s]",
                             absl::StrJoin(buffer_pointers, ", ", ptr_printer));
  VLOG(3) << absl::StrFormat("  Number of profile counters: %u",
                             profile_counters_size);
  VLOG(3) << absl::StrFormat("  Profile counters: %p", profile_counters);

  XlaCustomCallStatus status;
  // For the entry computation (like all global computations), all inputs and
  // outputs are in the buffer table, and both the result pointer and args array
  // pointers are unused (so we set them to 'nullptr').
  compute_function_(nullptr, run_options, nullptr, buffer_pointers.data(),
                    &status, profile_counters);

  uint64_t end_micros = tensorflow::Env::Default()->NowMicros();

  if (run_options->execution_profile()) {
    const double nanoseconds = (end_micros - start_micros) * 1000.0;
    run_options->execution_profile()->set_compute_time_ns(
        std::max(nanoseconds, 1.0));
    // If hlo profiling was disabled then the cycle count is left empty.
    if (hlo_execution_profile) {
      run_options->execution_profile()->set_compute_cycle_count(
          hlo_execution_profile->total_cycles_executed(
              *module().entry_computation()));
    }
  }

  absl::optional<absl::string_view> error_message =
      CustomCallStatusGetMessage(&status);
  if (error_message) {
    return InternalError("CustomCall failed: %s", *error_message);
  }

  return Status::OK();
}

StatusOr<ExecutionOutput> CpuExecutable::CreateResultShapedBuffer(
    const ServiceExecutableRunOptions* run_options,
    absl::Span<MaybeOwningDeviceMemory> buffers,
    absl::Span<ExecutionInput> arguments) {
  se::Stream* stream = run_options->stream();
  ExecutionOutput result(/*on_device_shape=*/result_shape(),
                         run_options->allocator(),
                         stream->parent()->device_ordinal());
  const HloInputOutputAliasConfig& input_output_alias =
      module().input_output_alias_config();
  HloInstruction* root = hlo_module_->entry_computation()->root_instruction();
  const Shape& root_shape = root->shape();

  // Move se::OwningDeviceMemory values which contain the array(s) of the result
  // into the respective location in ScopedShapedBuffer which is returned to the
  // caller.
  for (auto& p : result.MutableResult()->buffers()) {
    const ShapeIndex& index = p.first;
    se::DeviceMemoryBase& result_buffer = p.second;
    const HloValueSet& sources = this->GetRootValueSet().element(index);
    // The points to set is unambiguous so the set should be a
    // singleton.
    CHECK_EQ(1, sources.values().size());
    const HloValue* value_source = sources.values()[0];
    HloInstruction* src = value_source->instruction();

    // The source for this result buffer can be a nested buffer such as
    // a tuple element.
    TF_ASSIGN_OR_RETURN(
        const BufferAllocation::Slice slice,
        this->assignment_->GetUniqueSlice(src, value_source->index()));
    const BufferAllocation::Index buffer_index = slice.index();

    // TODO(cheshire): duplication with other backends.
    absl::optional<HloInputOutputAliasConfig::Alias> alias =
        input_output_alias.GetAliasedParameter(index);
    if (alias) {
      CHECK_LT(alias->parameter_number, arguments.size());
      ExecutionInput& input = arguments[alias->parameter_number];
      MaybeOwningDeviceMemory* maybe_owning_memory =
          input.MutableBuffer(alias->parameter_index);
      if (alias->must_alias() && !maybe_owning_memory->HasOwnership()) {
        return InvalidArgument(
            "An input was configured to be must-alias at "
            "compile time but not donated at runtime: %s",
            alias->ToString());
      }
      if (absl::optional<se::OwningDeviceMemory> owning =
              maybe_owning_memory->Release()) {
        // If the caller passes the ownership of the device memory, reuse it
        // as the output buffer. It is up to the caller whether or not to
        // donate a buffer; the aliasing information describes which buffers
        // may alias, not buffers that must alias.
        se::DeviceMemoryBase argument_buffer = owning->Release();
        *maybe_owning_memory = argument_buffer;
        result_buffer = argument_buffer;
        // The caller is giving us the
        // input buffer, but in case of error of the execute call, we should
        // not be releasing it as it contains valid data (for example, it is a
        // parameter which the user wants us to alias, in a gradient update
        // computation). So we store the index into the result in the aliased
        // vactor, which will be fed to the ExecutionOutput, which will be
        // using the indices to drop the addresses from its own
        // ScopedShapedBuffer result, if the ExecutionOutput is not committed.
        result.AddAliasedIndex(index);
      } else {
        VLOG(3) << "Using copy-protection: aliasing is specified, but the "
                   "buffer is not donated; allocating a fresh buffer";
        int64_t allocation_size =
            ShapeUtil::ByteSizeOf(ShapeUtil::GetSubshape(root_shape, index));
        TF_ASSIGN_OR_RETURN(
            se::OwningDeviceMemory allocated_buffer,
            run_options->allocator()->Allocate(
                stream->parent()->device_ordinal(), allocation_size));
        result_buffer = allocated_buffer.Release();
        MaybeOwningDeviceMemory& registered_buffer = buffers[buffer_index];
        CHECK_EQ(result_buffer.size(),
                 registered_buffer.AsDeviceMemoryBase().size());
        std::memcpy(/*dest=*/result_buffer.opaque(),
                    /*src=*/registered_buffer.AsDeviceMemoryBase().opaque(),
                    /*n=*/result_buffer.size());
        registered_buffer = result_buffer;
      }
    }

    if (result_buffer.is_null()) {
      MaybeOwningDeviceMemory& buffer = buffers[buffer_index];
      if (absl::optional<se::OwningDeviceMemory> owned_buffer =
              buffer.Release()) {
        result_buffer = owned_buffer->Release();
        buffer = result_buffer;
      } else {
        result_buffer = buffer.AsDeviceMemoryBase();
        result.AddAliasedIndex(index);
      }
    }
  }
  return std::move(result);
}

StatusOr<ExecutionOutput> CpuExecutable::ExecuteAsyncOnStream(
    const ServiceExecutableRunOptions* run_options,
    std::vector<ExecutionInput> arguments,
    HloExecutionProfile* hlo_execution_profile) {
  if (GetRootValueSet().IsAmbiguous()) {
    return Unimplemented("Points-to set of root instruction is ambiguous");
  }

  if (hlo_module_) {
    const HloComputation* entry_comp = hlo_module_->entry_computation();
    CHECK_EQ(entry_comp->num_parameters(), arguments.size())
        << "Wrong number of arguments passed when running executable";
    for (int64_t i = 0; i < entry_comp->num_parameters(); ++i) {
      const Shape& expected_shape =
          entry_comp->parameter_instruction(i)->shape();
      const Shape& actual_shape = arguments[i].Buffers().shape();
      TF_RET_CHECK(
          ShapeUtil::DynamicShapeIsCompatible(actual_shape, expected_shape))
          << "Shape mismatch on argument " << i << ", "
          << expected_shape.ToString(/*print_layout=*/true) << " vs. "
          << actual_shape.ToString(/*print_layout=*/true);
    }
  }

  auto* host_stream = dynamic_cast<se::host::HostStream*>(
      run_options->stream()->implementation());
  se::Stream* stream = run_options->stream();
  se::DeviceMemoryAllocator* memory_allocator = run_options->allocator();
  TF_ASSIGN_OR_RETURN(
      std::vector<MaybeOwningDeviceMemory> buffers,
      CreateBufferTable(memory_allocator, stream->parent()->device_ordinal(),
                        arguments));

  TF_ASSIGN_OR_RETURN(
      ExecutionOutput result,
      CreateResultShapedBuffer(run_options, absl::MakeSpan(buffers),
                               absl::MakeSpan(arguments)));

  // Logically we want this lambda to capture `buffers` by move, ultimately our
  // functor needs to be wrapped in an std::function, and that requires its
  // functor to be copyable.  Thus we perpetrate the hack of capturing buffers
  // "by shared pointer".
  //
  // We also need to change the types of some of the variables we capture:
  // run_options needs to change from a pointer to a value type, and arguments
  // needs to change from a Span into a vector.  We use a struct instead
  // of a lambda to make this explicit.
  struct AsyncRunTask {
    CpuExecutable* executable;
    ServiceExecutableRunOptions run_options;
    std::shared_ptr<std::vector<MaybeOwningDeviceMemory>> task_buffers;
    HloExecutionProfile* hlo_execution_profile;

    Status operator()() {
      return executable->ExecuteComputeFunction(
          &run_options.run_options(), *task_buffers, hlo_execution_profile);
    }
  };
  host_stream->EnqueueTaskWithStatus(
      AsyncRunTask{this, *run_options,
                   std::make_shared<std::vector<MaybeOwningDeviceMemory>>(
                       std::move(buffers)),
                   hlo_execution_profile});

  MarkToBeReleasedArguments(absl::MakeSpan(arguments), result);
  return std::move(result);
}

/*static*/ int64_t CpuExecutable::ShapeSizeBytes(const Shape& shape) {
  // On the cpu, opaques are pointers.
  if (shape.IsOpaque()) {
    return sizeof(void*);
  }
  if (shape.is_static() || shape.IsTuple()) {
    return ShapeUtil::ByteSizeOf(shape, sizeof(void*));
  }
  // Each dynamic dimension size is represented as a S32.
  int64_t metadata_size = sizeof(int32_t) * shape.dimensions_size();
  return ShapeUtil::ByteSizeOf(shape, sizeof(void*)) + metadata_size;
}

const InstructionValueSet& CpuExecutable::GetRootValueSet() const {
  return assignment_->dataflow_analysis().GetInstructionValueSet(
      module().entry_computation()->root_instruction());
}

int64_t CpuExecutable::SizeOfGeneratedCodeInBytes() const {
  return jit_->SizeOfGeneratedCodeInBytes();
}

}  // namespace cpu
}  // namespace xla


text:
import json
import logging
import urllib

from django.db.models import Q
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.utils.functional import wraps
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_http_methods

from desktop.context_processors import get_app_name
from desktop.lib.django_util import JsonResponse, render
from desktop.lib.exceptions_renderable import PopupException
from desktop.models import Document, Document2

from beeswax.design import hql_query
from beeswax.models import SavedQuery, MetaInstall
from beeswax.server import dbms
from beeswax.server.dbms import get_query_server_config
from filebrowser.views import location_to_url
from metastore.forms import LoadDataForm, DbForm
from metastore.settings import DJANGO_APPS
from notebook.connectors.base import Notebook

LOG = logging.getLogger(__name__)

SAVE_RESULTS_CTAS_TIMEOUT = 300         # seconds

def check_has_write_access_permission(view_func):
  """
  Decorator ensuring that the user is not a read only user.
  """
  def decorate(request, *args, **kwargs):
    if not has_write_access(request.user):
      raise PopupException(_('You are not allowed to modify the metastore.'), detail=_('You have must have metastore:write permissions'), error_code=301)

    return view_func(request, *args, **kwargs)
  return wraps(view_func)(decorate)

def index(request):
  return redirect(reverse('metastore:show_tables', kwargs={'database': ''}))

"""
Database Views
"""

def databases(request):
  search_filter = request.GET.get('filter', '')

  db = dbms.get(request.user)
  databases = db.get_databases(search_filter)

  return render("metastore.mako", request, {
    'breadcrumbs': [],
    'database': None,
    'databases': databases,
    'partitions': [],
    'has_write_access': has_write_access(request.user),
  })

@check_has_write_access_permission
def drop_database(request):
  db = dbms.get(request.user)

  if request.method == 'POST':
    databases = request.POST.getlist('database_selection')

    try:
      # Can't be simpler without an important refactoring
      design = SavedQuery.create_empty(app_name='beeswax', owner=request.user, data=hql_query('').dumps())
      query_history = db.drop_databases(databases, design)
      url = reverse('beeswax:watch_query_history', kwargs={'query_history_id': query_history.id}) + '?on_success_url=' + reverse('metastore:databases')
      return redirect(url)
    except Exception, ex:
      error_message, log = dbms.expand_exception(ex, db)
      error = _("Failed to remove %(databases)s.  Error: %(error)s") % {'databases': ','.join(databases), 'error': error_message}
      raise PopupException(error, title=_("Hive Error"), detail=log)
  else:
    title = _("Do you really want to delete the database(s)?")
    return render('confirm.mako', request, {'url': request.path, 'title': title})

def get_database_metadata(request, database):
  db = dbms.get(request.user)
  response = {'status': -1, 'data': ''}
  try:
    db_metadata = db.get_database(database)
    response['status'] = 0
    db_metadata['hdfs_link'] = location_to_url(db_metadata['location'])
    response['data'] = db_metadata
  except Exception, ex:
    response['status'] = 1
    response['data'] = _("Cannot get metadata for database: %s") % (database,)

  return JsonResponse(response)

def table_queries(request, database, table):
  qfilter = Q(data__icontains=table) | Q(data__icontains='%s.%s' % (database, table))

  response = {'status': -1, 'queries': []}
  try:
    queries = [{'doc': d.to_dict(), 'data': Notebook(document=d).get_data()}
              for d in Document2.objects.filter(qfilter, owner=request.user, type='query', is_history=False)[:50]]
    response['status'] = 0
    response['queries'] = queries
  except Exception, ex:
    response['status'] = 1
    response['data'] = _("Cannot get queries related to table %s.%s: %s") % (database, table, ex)

  return JsonResponse(response)

"""
Table Views
"""
def show_tables(request, database=None):
  if database is None:
    database = 'default' # Assume always 'default'

  if request.REQUEST.get("format", "html") == "json":
    db = dbms.get(request.user)

    try:
      databases = db.get_databases()

      if database not in databases:
        database = 'default'

      if request.method == 'POST':
        db_form = DbForm(request.POST, databases=databases)
        if db_form.is_valid():
          database = db_form.cleaned_data['database']
      else:
        db_form = DbForm(initial={'database': database}, databases=databases)

      search_filter = request.GET.get('filter', '')

      tables = db.get_tables_meta(database=database, table_names=search_filter) # SparkSql returns []
      table_names = [table['name'] for table in tables]
    except Exception, e:
      raise PopupException(_('Failed to retrieve tables for database: %s' % database), detail=e)

    resp = JsonResponse({
        'status': 0,
        'database_meta': db.get_database(database),
        'tables': tables,
        'table_names': table_names,
        'search_filter': search_filter
    })
  else:
    resp = render("metastore.mako", request, {
    'breadcrumbs': [],
    'database': None,
    'partitions': [],
    'has_write_access': has_write_access(request.user),
    })

  return resp

def get_table_metadata(request, database, table):
  db = dbms.get(request.user)
  response = {'status': -1, 'data': ''}
  try:
    table_metadata = db.get_table(database, table)
    response['status'] = 0
    response['data'] = {
      'comment': table_metadata.comment,
      'hdfs_link': table_metadata.hdfs_link,
      'is_view': table_metadata.is_view
    }
  except Exception, ex:
    response['status'] = 1
    response['data'] = _("Cannot get metadata for table: `%s`.`%s`") % (database, table)

  return JsonResponse(response)

def describe_table(request, database, table):
  app_name = get_app_name(request)
  query_server = get_query_server_config(app_name)
  db = dbms.get(request.user, query_server)

  try:
    table = db.get_table(database, table)
  except Exception, e:
    LOG.exception("Describe table error")
    if hasattr(e, 'message') and e.message:
      raise PopupException(_("Hive Error"), detail=e.message)
    else:
      raise PopupException(_("Hive Error"), detail=e)

  if request.REQUEST.get("format", "html") == "json":
    return JsonResponse({
        'status': 0,
        'name': table.name,
        'partition_keys': [{'name': part.name, 'type': part.type} for part in table.partition_keys],
        'cols': [{'name': col.name, 'type': col.type, 'comment': col.comment} for col in table.cols],
        'path_location': table.path_location,
        'hdfs_link': table.hdfs_link,
        'comment': table.comment,
        'is_view': table.is_view,
        'properties': table.properties,
        'details': table.details,
        'stats': table.stats
    })
  else:  # Render HTML
    renderable = "metastore.mako"

    partitions = None
    if app_name != 'impala' and table.partition_keys:
      partitions = [_massage_partition(database, table, partition) for partition in db.get_partitions(database, table)]

    return render(renderable, request, {
      'breadcrumbs': [{
          'name': database,
          'url': reverse('metastore:show_tables', kwargs={'database': database})
        }, {
          'name': str(table.name),
          'url': reverse('metastore:describe_table', kwargs={'database': database, 'table': table.name})
        },
      ],
      'table': table,
      'partitions': partitions,
      'database': database,
      'has_write_access': has_write_access(request.user),
    })

@check_has_write_access_permission
@require_http_methods(["POST"])
def alter_table(request, database, table):
  db = dbms.get(request.user)
  response = {'status': -1, 'data': ''}
  try:
    new_table_name = request.POST.get('new_table_name', None)
    comment = request.POST.get('comment', None)

    # Cannot modify both name and comment at same time, name will get precedence
    if new_table_name and comment:
      LOG.warn('Cannot alter both table name and comment at the same time, will perform rename.')

    table_obj = db.alter_table(database, table, new_table_name=new_table_name, comment=comment)

    response['status'] = 0
    response['data'] = {
      'name': table_obj.name,
      'comment': table_obj.comment,
      'is_view': table_obj.is_view,
      'location': table_obj.path_location,
      'properties': table_obj.properties
    }
  except Exception, ex:
    response['status'] = 1
    response['data'] = _("Failed to alter table `%s`.`%s`: %s") % (database, table, str(ex))

  return JsonResponse(response)

@check_has_write_access_permission
@require_http_methods(["POST"])
def alter_column(request, database, table):
  db = dbms.get(request.user)
  response = {'status': -1, 'message': ''}
  try:
    column = request.POST.get('column', None)

    if column is None:
      raise PopupException(_('alter_column requires a column parameter'))

    column_obj = db.get_column(database, table, column)
    if column_obj:
      new_column_name = request.POST.get('new_column_name', column_obj.name)
      new_column_type = request.POST.get('new_column_type', column_obj.type)
      comment = request.POST.get('comment', None)
      partition_spec = request.POST.get('partition_spec', None)

      column_obj = db.alter_column(database, table, column, new_column_name, new_column_type, comment=comment, partition_spec=partition_spec)

      response['status'] = 0
      response['data'] = {
        'name': column_obj.name,
        'type': column_obj.type,
        'comment': column_obj.comment
      }
    else:
      raise PopupException(_('Column `%s`.`%s` `%s` not found') % (database, table, column))
  except Exception, ex:
    response['status'] = 1
    response['message'] = _("Failed to alter column `%s`.`%s` `%s`: %s") % (database, table, column, str(ex))

  return JsonResponse(response)

@check_has_write_access_permission
def drop_table(request, database):
  db = dbms.get(request.user)

  if request.method == 'POST':
    tables = request.POST.getlist('table_selection')
    tables_objects = [db.get_table(database, table) for table in tables]
    try:
      # Can't be simpler without an important refactoring
      design = SavedQuery.create_empty(app_name='beeswax', owner=request.user, data=hql_query('').dumps())
      query_history = db.drop_tables(database, tables_objects, design)
      url = reverse('beeswax:watch_query_history', kwargs={'query_history_id': query_history.id}) + '?on_success_url=' + reverse('metastore:show_tables', kwargs={'database': database})
      return redirect(url)
    except Exception, ex:
      error_message, log = dbms.expand_exception(ex, db)
      error = _("Failed to remove %(tables)s.  Error: %(error)s") % {'tables': ','.join(tables), 'error': error_message}
      raise PopupException(error, title=_("Hive Error"), detail=log)
  else:
    title = _("Do you really want to delete the table(s)?")
    return render('confirm.mako', request, {'url': request.path, 'title': title})

def read_table(request, database, table):
  db = dbms.get(request.user)

  table = db.get_table(database, table)

  try:
    query_history = db.select_star_from(database, table)
    url = reverse('beeswax:watch_query_history', kwargs={'query_history_id': query_history.id}) + '?on_success_url=&context=table:%s:%s' % (table.name, database)
    return redirect(url)
  except Exception, e:
    raise PopupException(_('Cannot read table'), detail=e)

@check_has_write_access_permission
def load_table(request, database, table):
  db = dbms.get(request.user)
  table = db.get_table(database, table)
  response = {'status': -1, 'data': 'None'}

  if request.method == "POST":
    load_form = LoadDataForm(table, request.POST)

    if load_form.is_valid():
      on_success_url = reverse('metastore:describe_table', kwargs={'database': database, 'table': table.name})
      try:
        design = SavedQuery.create_empty(app_name='beeswax', owner=request.user, data=hql_query('').dumps())
        query_history = db.load_data(database, table, load_form, design)
        url = reverse('beeswax:watch_query_history', kwargs={'query_history_id': query_history.id}) + '?on_success_url=' + on_success_url
        response['status'] = 0
        response['data'] = url
      except Exception, e:
        response['status'] = 1
        response['data'] = _("Can't load the data: ") + str(e)
  else:
    load_form = LoadDataForm(table)

  if response['status'] == -1:
    popup = render('popups/load_data.mako', request, {
           'table': table,
           'load_form': load_form,
           'database': database,
           'app_name': 'beeswax'
       }, force_template=True).content
    response['data'] = popup

  return JsonResponse(response)

def describe_partitions(request, database, table):
  db = dbms.get(request.user)

  table_obj = db.get_table(database, table)

  if not table_obj.partition_keys:
    raise PopupException(_("Table '%(table)s' is not partitioned.") % {'table': table})

  reverse_sort = request.REQUEST.get("sort", "desc").lower() == "desc"

  if request.method == "POST":
    partition_filters = {}
    for part in table_obj.partition_keys:
      if request.REQUEST.get(part.name):
        partition_filters[part.name] = request.REQUEST.get(part.name)
    partition_spec = ','.join(["%s='%s'" % (k, v) for k, v in partition_filters.items()])
  else:
    partition_spec = ''

  partitions = db.get_partitions(database, table_obj, partition_spec, reverse_sort=reverse_sort)
  massaged_partitions = [_massage_partition(database, table_obj, partition) for partition in partitions]

  if request.method == "POST" or request.GET.get('format', 'html') == 'json':
    return JsonResponse({
      'partition_keys_json': [partition.name for partition in table_obj.partition_keys],
      'partition_values_json': massaged_partitions,
    })
  else:
    return render("describe_partitions.mako", request, {
      'breadcrumbs': [{
            'name': database,
            'url': reverse('metastore:show_tables', kwargs={'database': database})
          }, {
            'name': table,
            'url': reverse('metastore:describe_table', kwargs={'database': database, 'table': table})
          },{
            'name': 'partitions',
            'url': reverse('metastore:describe_partitions', kwargs={'database': database, 'table': table})
          },
        ],
        'database': database,
        'table': table_obj,
        'partitions': partitions,
        'partition_keys_json': json.dumps([partition.name for partition in table_obj.partition_keys]),
        'partition_values_json': json.dumps(massaged_partitions),
        'request': request,
        'has_write_access': has_write_access(request.user)
    })

def _massage_partition(database, table, partition):
  return {
    'columns': partition.values,
    'partitionSpec': partition.partition_spec,
    'readUrl': reverse('metastore:read_partition', kwargs={
        'database': database,
        'table': table.name,
        'partition_spec': urllib.quote(partition.partition_spec)
    }),
    'browseUrl': reverse('metastore:browse_partition', kwargs={
        'database': database,
        'table': table.name,
        'partition_spec': urllib.quote(partition.partition_spec)
    })
  }

def browse_partition(request, database, table, partition_spec):
  db = dbms.get(request.user)
  try:
    decoded_spec = urllib.unquote(partition_spec)
    partition_table = db.describe_partition(database, table, decoded_spec)
    uri_path = location_to_url(partition_table.path_location)
    return redirect(uri_path)
  except Exception, e:
    raise PopupException(_('Cannot browse partition'), detail=e.message)

def read_partition(request, database, table, partition_spec):
  db = dbms.get(request.user)
  try:
    decoded_spec = urllib.unquote(partition_spec)
    query = db.get_partition(database, table, decoded_spec)
    url = reverse('beeswax:watch_query_history', kwargs={'query_history_id': query.id}) + '?on_success_url=&context=table:%s:%s' % (table, database)
    return redirect(url)
  except Exception, e:
    raise PopupException(_('Cannot read partition'), detail=e.message)

@require_http_methods(["GET", "POST"])
@check_has_write_access_permission
def drop_partition(request, database, table):
  db = dbms.get(request.user)

  if request.method == 'POST':
    partition_specs = request.POST.getlist('partition_selection')
    partition_specs = [spec for spec in partition_specs]
    try:
      design = SavedQuery.create_empty(app_name='beeswax', owner=request.user, data=hql_query('').dumps())
      query_history = db.drop_partitions(database, table, partition_specs, design)
      url = reverse('beeswax:watch_query_history', kwargs={'query_history_id': query_history.id}) + '?on_success_url=' + \
            reverse('metastore:describe_partitions', kwargs={'database': database, 'table': table})
      return redirect(url)
    except Exception, ex:
      error_message, log = dbms.expand_exception(ex, db)
      error = _("Failed to remove %(partition)s.  Error: %(error)s") % {'partition': '\n'.join(partition_specs), 'error': error_message}
      raise PopupException(error, title=_("Hive Error"), detail=log)
  else:
    title = _("Do you really want to delete the partition(s)?")
    return render('confirm.mako', request, {'url': request.path, 'title': title})

def has_write_access(user):
  return user.is_superuser or user.has_hue_permission(action="write", app=DJANGO_APPS[0])


text:
package org.scaladebugger.api.profiles.java.requests.threads

import com.sun.jdi.event.ThreadStartEvent
import org.scaladebugger.api.lowlevel.events.EventType.ThreadStartEventType
import org.scaladebugger.api.lowlevel.events.data.JDIEventDataResult
import org.scaladebugger.api.lowlevel.events.{EventManager, JDIEventArgument}
import org.scaladebugger.api.lowlevel.requests.JDIRequestArgument
import org.scaladebugger.api.lowlevel.threads.{PendingThreadStartSupportLike, ThreadStartManager, ThreadStartRequestInfo}
import org.scaladebugger.api.pipelines.Pipeline
import org.scaladebugger.api.pipelines.Pipeline.IdentityPipeline
import org.scaladebugger.api.profiles.traits.info.InfoProducer
import org.scaladebugger.api.profiles.traits.info.events.{EventInfoProducer, ThreadStartEventInfo}
import org.scaladebugger.api.virtualmachines.ScalaVirtualMachine
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.{JDIMockHelpers, TestRequestHelper}

import scala.util.Success

class JavaThreadStartRequestSpec extends ParallelMockFunSpec with JDIMockHelpers {
  private val TestRequestId = java.util.UUID.randomUUID().toString
  private val mockThreadStartManager = mock[ThreadStartManager]
  private val mockEventManager = mock[EventManager]
  private val mockInfoProducer = mock[InfoProducer]
  private val mockScalaVirtualMachine = mock[ScalaVirtualMachine]

  private type E = ThreadStartEvent
  private type EI = ThreadStartEventInfo
  private type EIData = (EI, Seq[JDIEventDataResult])
  private type RequestArgs = Seq[JDIRequestArgument]
  private type CounterKey = Seq[JDIRequestArgument]
  private class CustomTestRequestHelper extends TestRequestHelper[E, EI, RequestArgs, CounterKey](
    scalaVirtualMachine = mockScalaVirtualMachine,
    eventManager = mockEventManager,
    etInstance = ThreadStartEventType
  )

  private class TestJavaThreadStartRequest(
    private val customTestRequestHelper: Option[CustomTestRequestHelper] = None
  ) extends JavaThreadStartRequest {
    override def newThreadStartRequestHelper() = {
      val originalRequestHelper = super.newThreadStartRequestHelper()
      customTestRequestHelper.getOrElse(originalRequestHelper)
    }
    override protected val threadStartManager = mockThreadStartManager
    override protected val eventManager: EventManager = mockEventManager
    override protected val infoProducer: InfoProducer = mockInfoProducer
    override protected val scalaVirtualMachine: ScalaVirtualMachine = mockScalaVirtualMachine
  }

  private val mockRequestHelper = mock[CustomTestRequestHelper]
  private val javaThreadStartProfile =
    new TestJavaThreadStartRequest(Some(mockRequestHelper))

  describe("JavaThreadStartRequest") {
    describe("for custom request helper") {
      describe("#_newRequestId") {
        it("should return a new id each time") {
          val javaThreadStartProfile = new TestJavaThreadStartRequest()
          val requestHelper = javaThreadStartProfile.newThreadStartRequestHelper()

          val requestId1 = requestHelper._newRequestId()
          val requestId2 = requestHelper._newRequestId()

          requestId1 shouldBe a [String]
          requestId2 shouldBe a [String]
          requestId1 should not be (requestId2)
        }
      }

      describe("#_newRequest") {
        it("should create a new request with the provided args and id") {
          val expected = Success("some id")

          val javaThreadStartProfile = new TestJavaThreadStartRequest()
          val requestHelper = javaThreadStartProfile.newThreadStartRequestHelper()

          val requestId = expected.get
          val requestArgs = Seq(mock[JDIRequestArgument])
          val jdiRequestArgs = Seq(mock[JDIRequestArgument])

          (mockThreadStartManager.createThreadStartRequestWithId _)
            .expects(requestId, jdiRequestArgs)
            .returning(expected)
            .once()

          val actual = requestHelper._newRequest(requestId, requestArgs, jdiRequestArgs)

          actual should be (expected)
        }
      }

      describe("#_hasRequest") {
        it("should return true if a request exists with matching request arguments") {
          val expected = true

          val javaThreadStartProfile = new TestJavaThreadStartRequest()
          val requestHelper = javaThreadStartProfile.newThreadStartRequestHelper()

          val requestId = "some id"
          val requestArgs = Seq(mock[JDIRequestArgument])
          val requestInfo = ThreadStartRequestInfo(
            requestId = requestId,
            isPending = false,
            extraArguments = requestArgs
          )

          // Get a list of request ids
          (mockThreadStartManager.threadStartRequestList _).expects()
            .returning(Seq(requestId)).once()

          // Look up a request that has arguments
          (mockThreadStartManager.getThreadStartRequestInfo _).expects(requestId)
            .returning(Some(requestInfo)).once()

          val actual = requestHelper._hasRequest(requestArgs)

          actual should be (expected)
        }

        it("should return false if no request exists with matching request arguments") {
          val expected = false

          val javaThreadStartProfile = new TestJavaThreadStartRequest()
          val requestHelper = javaThreadStartProfile.newThreadStartRequestHelper()

          val requestId = "some id"
          val requestArgs = Seq(mock[JDIRequestArgument])
          val requestInfo = ThreadStartRequestInfo(
            requestId = requestId,
            isPending = false,
            extraArguments = Seq(mock[JDIRequestArgument])
          )

          // Get a list of request ids
          (mockThreadStartManager.threadStartRequestList _).expects()
            .returning(Seq(requestId)).once()

          // Look up a request that does not have same arguments
          (mockThreadStartManager.getThreadStartRequestInfo _).expects(requestId)
            .returning(Some(requestInfo)).once()

          val actual = requestHelper._hasRequest(requestArgs)

          actual should be (expected)
        }
      }

      describe("#_removeByRequestId") {
        it("should remove the request with the specified id") {
          val javaThreadStartProfile = new TestJavaThreadStartRequest()
          val requestHelper = javaThreadStartProfile.newThreadStartRequestHelper()

          val requestId = "some id"

          (mockThreadStartManager.removeThreadStartRequest _)
            .expects(requestId)
            .returning(true)
            .once()

          requestHelper._removeRequestById(requestId)
        }
      }

      describe("#_retrieveRequestInfo") {
        it("should get the info for the request with the specified id") {
          val expected = Some(ThreadStartRequestInfo(
            requestId = "some id",
            isPending = true,
            extraArguments = Seq(mock[JDIRequestArgument])
          ))

          val javaThreadStartProfile = new TestJavaThreadStartRequest()
          val requestHelper = javaThreadStartProfile.newThreadStartRequestHelper()

          val requestId = "some id"

          (mockThreadStartManager.getThreadStartRequestInfo _)
            .expects(requestId)
            .returning(expected)
            .once()

          val actual = requestHelper._retrieveRequestInfo(requestId)

          actual should be (expected)
        }
      }

      describe("#_newEventInfo") {
        it("should create new event info for the specified args") {
          val expected = mock[ThreadStartEventInfo]

          val javaThreadStartProfile = new TestJavaThreadStartRequest()
          val requestHelper = javaThreadStartProfile.newThreadStartRequestHelper()

          val mockEventProducer = mock[EventInfoProducer]
          (mockInfoProducer.eventProducer _).expects()
            .returning(mockEventProducer).once()

          val mockScalaVirtualMachine = mock[ScalaVirtualMachine]
          val mockEvent = mock[ThreadStartEvent]
          val mockJdiArgs = Seq(mock[JDIRequestArgument], mock[JDIEventArgument])
          (mockEventProducer.newDefaultThreadStartEventInfo _)
            .expects(mockScalaVirtualMachine, mockEvent, mockJdiArgs)
            .returning(expected).once()

          val actual = requestHelper._newEventInfo(
            mockScalaVirtualMachine,
            mockEvent,
            mockJdiArgs
          )

          actual should be (expected)
        }
      }
    }

    describe("#tryGetOrCreateThreadStartRequestWithData") {
      it("should use the request helper's request and event pipeline methods") {
        val requestId = java.util.UUID.randomUUID().toString
        val mockJdiRequestArgs = Seq(mock[JDIRequestArgument])
        val mockJdiEventArgs = Seq(mock[JDIEventArgument])
        val requestArgs = mockJdiRequestArgs

        (mockRequestHelper.newRequest _)
          .expects(requestArgs, mockJdiRequestArgs)
          .returning(Success(requestId)).once()
        (mockRequestHelper.newEventPipeline _)
          .expects(requestId, mockJdiEventArgs, requestArgs)
          .returning(Success(Pipeline.newPipeline(classOf[EIData]))).once()

        val actual = javaThreadStartProfile.tryGetOrCreateThreadStartRequest(
          mockJdiRequestArgs ++ mockJdiEventArgs: _*
        ).get

        actual shouldBe an [IdentityPipeline[EIData]]
      }
    }

    describe("#threadStartRequests") {
      it("should include all active requests") {
        val expected = Seq(
          ThreadStartRequestInfo(TestRequestId, false)
        )

        val mockThreadStartManager = mock[PendingThreadStartSupportLike]
        val javaThreadStartProfile = new Object with JavaThreadStartRequest {
          override protected val threadStartManager = mockThreadStartManager
          override protected val eventManager: EventManager = mockEventManager
          override protected val infoProducer: InfoProducer = mockInfoProducer
          override protected val scalaVirtualMachine: ScalaVirtualMachine = mockScalaVirtualMachine
        }

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(expected.map(_.requestId)).once()
        (mockThreadStartManager.getThreadStartRequestInfo _)
          .expects(TestRequestId).returning(expected.headOption).once()

        (mockThreadStartManager.pendingThreadStartRequests _).expects()
          .returning(Nil).once()

        val actual = javaThreadStartProfile.threadStartRequests

        actual should be (expected)
      }

      it("should include pending requests if supported") {
        val expected = Seq(
          ThreadStartRequestInfo(TestRequestId, true)
        )

        val mockThreadStartManager = mock[PendingThreadStartSupportLike]
        val javaThreadStartProfile = new Object with JavaThreadStartRequest {
          override protected val threadStartManager = mockThreadStartManager
          override protected val eventManager: EventManager = mockEventManager
          override protected val infoProducer: InfoProducer = mockInfoProducer
          override protected val scalaVirtualMachine: ScalaVirtualMachine = mockScalaVirtualMachine
        }

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(Nil).once()

        (mockThreadStartManager.pendingThreadStartRequests _).expects()
          .returning(expected).once()

        val actual = javaThreadStartProfile.threadStartRequests

        actual should be (expected)
      }

      it("should only include active requests if pending unsupported") {
        val expected = Seq(
          ThreadStartRequestInfo(TestRequestId, false)
        )

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(expected.map(_.requestId)).once()
        (mockThreadStartManager.getThreadStartRequestInfo _)
          .expects(TestRequestId).returning(expected.headOption).once()

        val actual = javaThreadStartProfile.threadStartRequests

        actual should be (expected)
      }
    }

    describe("#removeThreadStartRequestWithArgs") {
      it("should return None if no requests exists") {
        val expected = None

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(Nil).once()

        val actual = javaThreadStartProfile.removeThreadStartRequestWithArgs()

        actual should be (expected)
      }

      it("should return None if no request with matching extra arguments exists") {
        val expected = None
        val extraArguments = Seq(mock[JDIRequestArgument])

        val requests = Seq(
          ThreadStartRequestInfo(
            requestId = TestRequestId,
            isPending = true,
            extraArguments = extraArguments
          )
        )

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(requests.map(_.requestId)).once()
        requests.foreach(r =>
          (mockThreadStartManager.getThreadStartRequestInfo _)
            .expects(r.requestId)
            .returning(Some(r))
            .once()
        )

        val actual = javaThreadStartProfile.removeThreadStartRequestWithArgs()

        actual should be (expected)
      }

      it("should return remove and return matching pending requests") {
        val extraArguments = Seq(mock[JDIRequestArgument])

        val expected = Some(
          ThreadStartRequestInfo(
            requestId = TestRequestId,
            isPending = true,

            extraArguments = extraArguments
          )
        )

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(Seq(expected.get).map(_.requestId)).once()
        expected.foreach(r => {
          (mockThreadStartManager.getThreadStartRequestInfo _)
            .expects(r.requestId)
            .returning(Some(r))
            .once()
          (mockThreadStartManager.removeThreadStartRequest _)
            .expects(r.requestId)
            .returning(true)
            .once()
        })

        val actual = javaThreadStartProfile.removeThreadStartRequestWithArgs(
          extraArguments: _*
        )

        actual should be (expected)
      }

      it("should remove and return matching non-pending requests") {
        val extraArguments = Seq(mock[JDIRequestArgument])

        val expected = Some(
          ThreadStartRequestInfo(
            requestId = TestRequestId,
            isPending = false,

            extraArguments = extraArguments
          )
        )

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(Seq(expected.get).map(_.requestId)).once()
        expected.foreach(r => {
          (mockThreadStartManager.getThreadStartRequestInfo _)
            .expects(r.requestId)
            .returning(Some(r))
            .once()
          (mockThreadStartManager.removeThreadStartRequest _)
            .expects(r.requestId)
            .returning(true)
            .once()
        })

        val actual = javaThreadStartProfile.removeThreadStartRequestWithArgs(
          extraArguments: _*
        )

        actual should be (expected)
      }
    }

    describe("#removeAllThreadStartRequests") {
      it("should return empty if no requests exists") {
        val expected = Nil

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(Nil).once()

        val actual = javaThreadStartProfile.removeAllThreadStartRequests()

        actual should be (expected)
      }

      it("should remove and return all pending requests") {
        val extraArguments = Seq(mock[JDIRequestArgument])

        val expected = Seq(
          ThreadStartRequestInfo(
            requestId = TestRequestId,
            isPending = true,
            extraArguments = extraArguments
          )
        )

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(expected.map(_.requestId)).once()
        expected.foreach(r => {
          (mockThreadStartManager.getThreadStartRequestInfo _)
            .expects(r.requestId)
            .returning(Some(r))
            .once()
          (mockThreadStartManager.removeThreadStartRequest _)
            .expects(r.requestId)
            .returning(true)
            .once()
        })

        val actual = javaThreadStartProfile.removeAllThreadStartRequests()

        actual should be (expected)
      }

      it("should remove and return all non-pending requests") {
        val extraArguments = Seq(mock[JDIRequestArgument])

        val expected = Seq(
          ThreadStartRequestInfo(
            requestId = TestRequestId,
            isPending = false,
            extraArguments = extraArguments
          )
        )

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(expected.map(_.requestId)).once()
        expected.foreach(r => {
          (mockThreadStartManager.getThreadStartRequestInfo _)
            .expects(r.requestId)
            .returning(Some(r))
            .once()
          (mockThreadStartManager.removeThreadStartRequest _)
            .expects(r.requestId)
            .returning(true)
            .once()
        })

        val actual = javaThreadStartProfile.removeAllThreadStartRequests()

        actual should be (expected)
      }
    }

    describe("#isThreadStartRequestWithArgsPending") {
      it("should return false if no requests exist") {
        val expected = false

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(Nil).once()

        val actual = javaThreadStartProfile.isThreadStartRequestWithArgsPending()

        actual should be (expected)
      }

      it("should return false if no request with matching extra arguments exists") {
        val expected = false
        val extraArguments = Seq(mock[JDIRequestArgument])

        val requests = Seq(
          ThreadStartRequestInfo(
            requestId = TestRequestId,
            isPending = true,
            extraArguments = extraArguments
          )
        )

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(requests.map(_.requestId)).once()
        requests.foreach(r =>
          (mockThreadStartManager.getThreadStartRequestInfo _)
            .expects(r.requestId)
            .returning(Some(r))
            .once()
        )

        val actual = javaThreadStartProfile.isThreadStartRequestWithArgsPending()

        actual should be (expected)
      }

      it("should return false if no matching request is pending") {
        val expected = false
        val extraArguments = Seq(mock[JDIRequestArgument])

        val requests = Seq(
          ThreadStartRequestInfo(
            requestId = TestRequestId,
            isPending = false,
            extraArguments = extraArguments
          )
        )

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(requests.map(_.requestId)).once()
        requests.foreach(r =>
          (mockThreadStartManager.getThreadStartRequestInfo _)
            .expects(r.requestId)
            .returning(Some(r))
            .once()
        )

        val actual = javaThreadStartProfile.isThreadStartRequestWithArgsPending(
          extraArguments: _*
        )

        actual should be (expected)
      }

      it("should return true if at least one matching request is pending") {
        val expected = true
        val extraArguments = Seq(mock[JDIRequestArgument])

        val requests = Seq(
          ThreadStartRequestInfo(
            requestId = TestRequestId,
            isPending = true,
            extraArguments = extraArguments
          )
        )

        (mockThreadStartManager.threadStartRequestList _).expects()
          .returning(requests.map(_.requestId)).once()
        requests.foreach(r =>
          (mockThreadStartManager.getThreadStartRequestInfo _)
            .expects(r.requestId)
            .returning(Some(r))
            .once()
        )

        val actual = javaThreadStartProfile.isThreadStartRequestWithArgsPending(
          extraArguments: _*
        )

        actual should be (expected)
      }
    }
  }
}


text:
// Copyright 2014 Google Inc.

#import <GoogleCast/GCKDefines.h>

#import <CoreGraphics/CoreGraphics.h>
#import <Foundation/Foundation.h>

@class GCKColor;

GCK_ASSUME_NONNULL_BEGIN

/**
 * @enum GCKMediaTextTrackStyleEdgeType
 * Closed caption text edge types (font effects).
 */
typedef NS_ENUM(NSInteger, GCKMediaTextTrackStyleEdgeType) {
  /** Unknown edge type. */
  GCKMediaTextTrackStyleEdgeTypeUnknown = -1,
  /** None. */
  GCKMediaTextTrackStyleEdgeTypeNone = 0,
  /** Outline. */
  GCKMediaTextTrackStyleEdgeTypeOutline = 1,
  /** Drop shadow. */
  GCKMediaTextTrackStyleEdgeTypeDropShadow = 2,
  /** Raised. */
  GCKMediaTextTrackStyleEdgeTypeRaised = 3,
  /** Depressed. */
  GCKMediaTextTrackStyleEdgeTypeDepressed = 4,
};

/**
 * @enum GCKMediaTextTrackStyleWindowType
 * Closed caption window types.
 */
typedef NS_ENUM(NSInteger, GCKMediaTextTrackStyleWindowType) {
  /** Unknown window type. */
  GCKMediaTextTrackStyleWindowTypeUnknown = -1,
  /** None. */
  GCKMediaTextTrackStyleWindowTypeNone = 0,
  /** Normal. */
  GCKMediaTextTrackStyleWindowTypeNormal = 1,
  /** Rounded corners. */
  GCKMediaTextTrackStyleWindowTypeRoundedCorners = 2,
};

/**
 * @enum GCKMediaTextTrackStyleFontGenericFamily
 * Closed caption text generic font families.
 */
typedef NS_ENUM(NSInteger, GCKMediaTextTrackStyleFontGenericFamily) {
  /** Unknown font family. */
  GCKMediaTextTrackStyleFontGenericFamilyUnknown = -1,
  /** None. */
  GCKMediaTextTrackStyleFontGenericFamilyNone = 0,
  /** Sans serif. */
  GCKMediaTextTrackStyleFontGenericFamilySansSerif = 1,
  /** Monospaced sans serif. */
  GCKMediaTextTrackStyleFontGenericFamilyMonospacedSansSerif = 2,
  /** Serif. */
  GCKMediaTextTrackStyleFontGenericFamilySerif = 3,
  /** Monospaced serif. */
  GCKMediaTextTrackStyleFontGenericFamilyMonospacedSerif = 4,
  /** Casual. */
  GCKMediaTextTrackStyleFontGenericFamilyCasual = 5,
  /** Cursive. */
  GCKMediaTextTrackStyleFontGenericFamilyCursive = 6,
  /** Small Capitals. */
  GCKMediaTextTrackStyleFontGenericFamilySmallCapitals = 7,
};

/**
 * @enum GCKMediaTextTrackStyleFontStyle
 * Closed caption text font styles.
 */
typedef NS_ENUM(NSInteger, GCKMediaTextTrackStyleFontStyle) {
  /** Unknown font style. */
  GCKMediaTextTrackStyleFontStyleUnknown = -1,
  /** Normal. */
  GCKMediaTextTrackStyleFontStyleNormal = 0,
  /** Bold. */
  GCKMediaTextTrackStyleFontStyleBold = 1,
  /** Italic. */
  GCKMediaTextTrackStyleFontStyleItalic = 2,
  /** Bold italic. */
  GCKMediaTextTrackStyleFontStyleBoldItalic = 3,
};

/**
 * A class representing a style for a text media track.
 */
GCK_EXPORT
@interface GCKMediaTextTrackStyle : NSObject <NSCopying, NSSecureCoding>

/**
 * Designated initializer. All properties are mutable and so can be supplied after construction.
 */
- (instancetype)init;

/**
 * Creates an instance with default values based on the system's closed captioning settings. This
 * method will return nil on systems older than iOS 7.
 */
+ (instancetype)createDefault;

/** The font scaling factor for the text. */
@property(nonatomic, assign, readwrite) CGFloat fontScale;

/** The foreground color. */
@property(nonatomic, copy, readwrite, GCK_NULLABLE) GCKColor *foregroundColor;

/** The background color. */
@property(nonatomic, copy, readwrite, GCK_NULLABLE) GCKColor *backgroundColor;

/** The edge type. */
@property(nonatomic, assign, readwrite) GCKMediaTextTrackStyleEdgeType edgeType;

/** The edge color. */
@property(nonatomic, copy, readwrite, GCK_NULLABLE) GCKColor *edgeColor;

/** The window type. Some receiver devices may not support this attribute. */
@property(nonatomic, assign, readwrite) GCKMediaTextTrackStyleWindowType windowType;

/** The window color. Some receiver devices may not support this attribute. */
@property(nonatomic, copy, readwrite, GCK_NULLABLE) GCKColor *windowColor;

/**
 * Rounded corner radius absolute value in pixels.
 * Some receiver devices may not support this attribute.
 */
@property(nonatomic, assign, readwrite) CGFloat windowRoundedCornerRadius;

/** The font family; if the font is not available, the generic font family will be used. **/
@property(nonatomic, copy, readwrite, GCK_NULLABLE) NSString *fontFamily;

/** The generic font family. */
@property(nonatomic, assign, readwrite) GCKMediaTextTrackStyleFontGenericFamily fontGenericFamily;

/** The font style. */
@property(nonatomic, assign, readwrite) GCKMediaTextTrackStyleFontStyle fontStyle;

/** The custom data, if any. */
@property(nonatomic, strong, readwrite, GCK_NULLABLE) id customData;

@end

GCK_ASSUME_NONNULL_END


text:
/**
 * Currently in beta stage. Changes can and will be made to the core mechanic
 * making this not backwards compatible.
 *
 * Github: https://github.com/Need4Speed402/tessellator
 */

Tessellator.Model.prototype.blendFunc = function (){
    return this.add(Tessellator.new.apply(Tessellator.BlendFunc, arguments));
};

Tessellator.BlendFunc = function (){
    this.type = Tessellator.BLEND_FUNC;

    if (arguments.length === 1){
        this.func = arguments[0];
    }else{
        this.func = Tessellator.vec2(arguments);
    };
};

Tessellator.BlendFunc.prototype.init = function (init){
    init.flush();
};

Tessellator.BlendFunc.prototype.postInit = Tessellator.EMPTY_FUNC;

Tessellator.BlendFunc.prototype.apply = function (render){
    render.blendFunc(this.func);
};


text:
'use strict';

var should = require('should');
var nock = require('nock');
var app = require('../../app');
var request = require('supertest');
var assert = require('assert');
var uuid = require('node-uuid');
var db = require('../../components/database');
var bcrypt = require('bcrypt');
var settings = require('../../config/environment');
db.initialize('couchdb');
var users = db.getUsersTable();
var cookie;

describe('POST /api/user/uploadAvatar', function() {

  beforeEach(function (done) {
    var user = {
      username: 'mockUser',
      password: bcrypt.hashSync('mockPassword', 10),
      firstName: 'Foo',
      lastName: 'Bar',
      avatar: 'assets/images/default.png',
      lastfm: {
        username: '',
        currentSong: {
          artist: '',
          song: '',
          url: '',
          lastUpdated: Date.now()
        }
      },
      linesPerMinute: 0.0,
      linesLastUpdated: Date.now(),
      admin: false
     };
    db.insert(users, uuid.v4(), user, function (error) {
      if (error) {
        console.log('Error inserting new user.'.red);
        return done(error);
      }
      request(app).post('/api/user/login')
      .send({username: 'mockUser', password: 'mockPassword'})
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function(error, res) {
        if (error) {
          return done(error);
        }
        cookie = res.headers['set-cookie'];
        assert.equal(res.body.message, 'Logged in.');
        done();
      });
    });
    // Mock the Imgur call for file uploading.
    nock('https://api.imgur.com', {reqheaders: {
    'Authorization': 'Client-ID mockClientId'
    }}).post('/3/upload')
    .reply(200, {"data":{"id":"rrwkbGo","title":null,"description":null,"datetime":1405057112,"type":"image\/jpeg","animated":false,"width":640,"height":972,"size":53957,"views":0,"bandwidth":0,"favorite":false,"nsfw":null,"section":null,"deletehash":"u6w57wEeV7YfDUh","link":"http:\/\/i.imgur.com\/rrwkbGo.jpg"},"success":true,"status":200});
  });

  afterEach(function (done) {
    db.searchUserByAll(function (error, reply) {
      if (error) {
        console.log('Error retrieving users.'.red);
        return done(error);
      }
      var docs = [];
      for (var i = 0; i < reply.rows.length; i++) {
        var user = reply.rows[i].value;
        user._deleted = true;
        docs.push(user);
      }
      db.deleteAllUsers(docs, function(error, reply) {
        if (error) {
          console.log('Error deleting users.'.red);
          return done(error);
        }
        db.compactUserDB(function (error, reply) {
          if (error) {
            console.log('Error compacting user database.'.red);
            return done(error);
          }
          done();
        });
      });
    });
  });

  it('should update an avatar to Imgur', function (done) {
    request(app)
    .post('/api/user/uploadAvatar')
    .set('cookie', cookie)
    .send({'url': 'http://i.imgur.com/BS2iaX2.jpg'})
    .expect(200)
    .expect('Content-Type', /json/)
    .end(function (error, res) {
      if (error) {
        return done(error);
      }
      res.should.have.status(200);
      assert.equal(res.body.message, 'Avatar updated.');
      done();
    });
  });
});


text:
An iOS app to benchmark TFLite models.

The app reads benchmark parameters from a JSON file named
`benchmark_params.json` in its `benchmark_data` directory. Any downloaded models
for benchmarking should also be placed in `benchmark_data` directory.

The JSON file specifies the name of the model file and other benchmarking
parameters like inputs to the model, type of inputs, number of iterations,
number of threads. The default values in the JSON file are for the
Mobilenet_1.0_224 model ([paper][mobilenet-paper],
[tflite&pb][mobilenet-model]).

## Building / running the app

*   Follow the [iOS build instructions][build-ios] to configure the Bazel
    workspace and `.bazelrc` file correctly.

*   Run `build_benchmark_framework.sh` script to build the benchmark framework.
    This script will build the benchmark framework for iOS and put it under
    `TFLiteBenchmark/TFLiteBenchmark/Frameworks` directory.

*   If you want more detailed profiling, run the build script with `-p` option:
    `build_benchmark_framework.sh -p`.

*   Modify `benchmark_params.json` change the `input_layer`, `input_layer_shape`
    and other benchmark parameters.

*   Change `Build Phases -> Copy Bundle Resources` and add the model file to the
    resources that need to be copied.

*   Ensure that `Build Phases -> Link Binary With Library` contains the
    `Accelerate framework` and `TensorFlowLiteBenchmarkC.framework`.

*   Now try running the app. The app has a single button that runs the benchmark
    on the model and displays results in a text view below. You can also see the
    console output section in your Xcode to see more detailed benchmark
    information.

[build-ios]: https://tensorflow.org/lite/guide/build_ios
[mobilenet-model]: https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_2018_02_22/mobilenet_v1_1.0_224.tgz
[mobilenet-paper]: https://arxiv.org/pdf/1704.04861.pdf


text:
<resources>
    <string name="app_name">udpsockets</string>
</resources>


text:
<?php

namespace ZfTable\Decorator\Cell;

use ZfTable\Decorator\Exception;

class AttrDecorator extends AbstractCellDecorator
{

    protected $attr;

    /**
     * Constructor
     *
     * @param array $attributes
     * @throws Exception\InvalidArgumentException
     */
    public function __construct($attributes)
    {
        $this->setAttr($attributes);
    }

    /**
     * Rendering decorator
     * @param string $context
     * @return string
     */
    public function render($context)
    {
        if (count($this->attr) > 0) {
            foreach ($this->attr as $name => $value) {
                $this->getCell()->addAttr($name, $value);
            }
        }
        return $context;
    }

    public function getAttr()
    {
        return $this->attr;
    }

    public function setAttr($attr)
    {
        $this->attr = $attr;
    }
}


text:
//////////////////////////////////////////////////////////////////////////////////////////////
//
// Implement the classes for the various types of hash keys we support.
//
#ifndef __FACTORY_H__
#define __FACTORY_H__ 1

#include <string>

#include "operator.h"
#include "condition.h"

Operator *operator_factory(const std::string &op);
Condition *condition_factory(const std::string &cond);

#endif


text:
/**
 *类名称:树形信息
 *公司: 吉贝克信息技术(北京)有限公司
 *文件名:SysTreeInfoService.java
 *作者: 张明金
 *创建时间: 2013-10-22 09:36
 *最后更新: 2013-10-22 09:36
 *
 *1.作者: 张明金 2013-10-22 09:36
 *初始版本
 *本类提供以下方法:
 *
 **(如要修改,请注释 修改人、修改时间、修改说明)
 *
 */

package  com.gbicc.bll.sys.service;

import java.util.List;
import java.util.Map;

import com.gbicc.bll.sys.bean.SysTreeInfo;
import com.gbicc.bll.sys.bean.SysTreeType;
import com.gbicc.bll.sys.bean.Tree;

public interface SysTreeInfoService {

		public SysTreeType getSysTreeTypeById(String typeCode);
		public String getSysTreeTypeNameById(String typeCode,String typeId);
		/**
		 * 通过类型查询
		 */
		public List getSysTreeByType(String typeId);
		/**
		 * 查询
		 */
		public List getSysTreeInfoList(SysTreeInfo sysTreeInfo);

		/**
		 * 添加和修改是判断名称是否重名
		 */
        public List getSysTreeInfoBypIdName(SysTreeInfo sysTreeInfo);
        /**
         * 添加和修改是判断编码是否重名
         */
        public List getSysTreeInfoBypIdCode(SysTreeInfo sysTreeInfo);

		/**
		 * 通过编号查询
		 */
		public SysTreeInfo getSysTreeInfoById(String id);
		/**
		 * 通过nodeCode查询
		 */
		public SysTreeInfo getSysTreeInfoByNodeCode(String nodeCode);
		/**
		 * 通过编号查询高度
		 */
		public String getSysTreeInfoHightById(String id);
		/**
		 *  插入
		 * @param systreeinfo
		 * @return
		 */
		public String insertSysTreeInfo(SysTreeInfo systreeinfo);

		/**
		 * 修改
		 * @param systreeinfo
		 */
		public int updateSysTreeInfo(SysTreeInfo systreeinfo) ;

		/**
		 * 删除
		 * @param id:编号
		 */
		public int deleteSysTreeInfo(SysTreeInfo systreeinfo);
		/**
		 * 修改树下子节点nodel_level
		 *
		 */
		public void updateSysTreeChildNodeLevel(String idstr,String nodelevel,List systreelist,String type);
		/**
		 * 根据父级节点ID查询其子级节点个数
		 * ltc
		 */
		public int getTreeInfoHightByParentId1(String type_id,String parent_id);
		/**
		 * 根据父节点ID、树类型获取新节点的NODE_CODE
		 * ltc
		 */
		public String getTreeInfoHightByParentId2(String type_id,String parent_id,String parentCode);
	//end auto create.
		/**
		 * 方法名称:selectRepOrgTree
		 * 方法作用:报表分析-机构查看 (查询养老金机构树)
		 * 编写人:LuoTianChang
		 * 编写日期:2015-01-27
		 * 最后更新日期:2015-01-27
		 */
		public List selectRepOrgTree();
		/**
		 * 方法名称:selectRepOrgTree2
		 * 方法作用:报表分析-机构查看 (查询人寿机构树)
		 * 编写人:LuoTianChang
		 * 编写日期:2015-01-27
		 * 最后更新日期:2015-01-27
		 */
		public List selectRepOrgTree2();

		/**
		 * 清单模型*/
		/**
		 * 通过nodeCode查询
		 */
		public SysTreeInfo getSysBillTreeInfoByNodeCode(String nodeCode);

		public SysTreeInfo getSysTreeInfoNodeById(String idstr);
		public int getMaxOrderNo(String idstr);

		public String getSysDeptTreeTypeNameById(String typeCode);

		public int queryDeptChildCount(String parentId);

		public String queryDeptChildOrgCode();

		public String queryDeptMaxChildOrgCode(String parentId);

		public void insertDeptTree(Tree deptTree);

		public List getSysDeptTreeInfoById(String id);

		/**
		 * 删除
		 * @param id:编号
		 */
		public int deleteSysDeptTreeInfo(String idStr);

		public void updateSysDeptTreeInfo(Tree deptTree);

		/**
		 * 获取对应的树的信息
		 * @param map
		 * @return
		 */
		public List<SysTreeInfo> getQuDaoInfo(Map<String,Object> map);

		/**
		 * 获取渠道对应的详情信息
		 * @param map
		 * @return
		 */
		public SysTreeInfo getQuDaoDetailsInfo(Map<String,Object> map);

}


text:
To run this project:

1) Install Go. Homebrew is your friend :)
2) Clone this repo or run `go get github.com/andrewcopp/coup` to download
3) Create a virtualenv
4) Install TensorFlow in that virtualenv
5) Activate the virtualenv
3) Navigate to the top level directory of this project
4) Run `go cmd/trainer/trainer.go`

This will run the script that simulates games and trains and fits against the TensorFlow model.

The script is super slow unless you modify TensorFlow to run on a GPU and put it on an AWS EC2 instance. This is mostly to prove it works.

All Python code can be found in `cmd/trainer/model`

This project was originally written in Go to help with concurrency. Concurrency was not
added in order to finish by the project deadline but will be added in my next iteration.


text:
package org.hawkular.metrics.core.api;

import java.util.Map;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * @author John Sanda
 */
public class AvailabilityMetric extends Metric<Availability> {

    @JsonCreator
    public AvailabilityMetric(@JsonProperty("id") MetricId id) {
        super("", id);
    }

    public AvailabilityMetric(String tenantId, MetricId id) {
        super(tenantId, id);
    }

    public AvailabilityMetric(String tenantId, MetricId id, Map<String, String> tags) {
        super(tenantId, id, tags);
    }

    public AvailabilityMetric(String tenantId, MetricId id, Map<String, String> tags, Integer dataRetention) {
        super(tenantId, id, tags, dataRetention);
    }

    @Override
    public MetricType getType() {
        return MetricType.AVAILABILITY;
    }
}


text: External URL, no hash


text:
from quark_runtime import *

def go():
    _println(u"GO!");


text:
title: ASPNET
---
## ASP.NET

# Overview

ASP.Net is a web development platform provided by Microsoft. It is used for creating web-based applications and websites using HTML, CSS, and JavaScript as front end.
Server-side programming languages like C# and VB .NET may be used to code the back end.

ASP.NET offers different frameworks for creating web applications: For e.g Web Forms and ASP.NET MVC.

#### More Information:
- [ASP .NET Tutorials](https://www.tutorialspoint.com/asp.net/)
- [ASP .NET Site](https://www.asp.net/)
- [ASP .NET Microsoft Documentation](https://docs.microsoft.com/en-us/aspnet/#pivot=aspnet/)
- [ASP .NET Forum](https://forums.asp.net/)


text:
namespace elena_lang
{
   const char* token_dfa[12] =
   {
        ".????????bb??b??????????????????bdfldd??dddddddheeeeeeeeeedd?d???ccccccccccccccccccccccccccd?ddc?cccccccccccccccccccccccccc?ddd?",
        "*********bb*********************b***********************************************************************************************",
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaccccccccccaaaaaaaccccccccccccccccccccccccccaaaacaccccccccccccccccccccccccccaaaaa",
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaadaadaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaeeeeeeeeeeaaaaaaakkkkkkaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaajaaaaaaaaaaaaaaaaaaaaaaa",
        "?fffffffffffffffffffffffffffffffffgfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaiaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "*iiiiiiiii*ii*iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii",
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "????????????????????????????????????????????????kkkkkkkkkk???????kkkkkk?????????????????????????????????j???????????????????????",
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaccccccccccccccccccccccccccaaaacaccccccccccccccccccccccccccaaaaa",
   };

}
#endif