text:
#pragma once

#include <set>
#include <string>
#include <vector>

#include "SeedSetter.hpp"
#include "tcframe/exception.hpp"
#include "tcframe/spec/config.hpp"
#include "tcframe/spec/core.hpp"
#include "tcframe/spec/random.hpp"
#include "tcframe/spec/testcase.hpp"
#include "tcframe/util.hpp"

using std::set;
using std::string;
using std::vector;

namespace tcframe {

template<typename TProblemSpec /* extends BaseProblemSpec */>
class BaseTestSpec : public TProblemSpec, protected TestSuiteBuilder {
private:
    vector<void(BaseTestSpec::*)()> sampleTestCases_ = {
            &BaseTestSpec::SampleTestCase1,
            &BaseTestSpec::SampleTestCase2,
            &BaseTestSpec::SampleTestCase3,
            &BaseTestSpec::SampleTestCase4,
            &BaseTestSpec::SampleTestCase5,
            &BaseTestSpec::SampleTestCase6,
            &BaseTestSpec::SampleTestCase7,
            &BaseTestSpec::SampleTestCase8,
            &BaseTestSpec::SampleTestCase9,
            &BaseTestSpec::SampleTestCase10,
            &BaseTestSpec::SampleTestCase11,
            &BaseTestSpec::SampleTestCase12,
            &BaseTestSpec::SampleTestCase13,
            &BaseTestSpec::SampleTestCase14,
            &BaseTestSpec::SampleTestCase15,
            &BaseTestSpec::SampleTestCase16,
            &BaseTestSpec::SampleTestCase17,
            &BaseTestSpec::SampleTestCase18,
            &BaseTestSpec::SampleTestCase19,
            &BaseTestSpec::SampleTestCase20,
            &BaseTestSpec::SampleTestCase21,
            &BaseTestSpec::SampleTestCase22,
            &BaseTestSpec::SampleTestCase23,
            &BaseTestSpec::SampleTestCase24,
            &BaseTestSpec::SampleTestCase25};

    vector<void(BaseTestSpec::*)()> testGroups_ = {
            &BaseTestSpec::TestGroup1,
            &BaseTestSpec::TestGroup2,
            &BaseTestSpec::TestGroup3,
            &BaseTestSpec::TestGroup4,
            &BaseTestSpec::TestGroup5,
            &BaseTestSpec::TestGroup6,
            &BaseTestSpec::TestGroup7,
            &BaseTestSpec::TestGroup8,
            &BaseTestSpec::TestGroup9,
            &BaseTestSpec::TestGroup10,
            &BaseTestSpec::TestGroup11,
            &BaseTestSpec::TestGroup12,
            &BaseTestSpec::TestGroup13,
            &BaseTestSpec::TestGroup14,
            &BaseTestSpec::TestGroup15,
            &BaseTestSpec::TestGroup16,
            &BaseTestSpec::TestGroup17,
            &BaseTestSpec::TestGroup18,
            &BaseTestSpec::TestGroup19,
            &BaseTestSpec::TestGroup20,
            &BaseTestSpec::TestGroup21,
            &BaseTestSpec::TestGroup22,
            &BaseTestSpec::TestGroup23,
            &BaseTestSpec::TestGroup24,
            &BaseTestSpec::TestGroup25};

public:
    virtual ~BaseTestSpec() = default;

    TestSuite buildTestSuite(const string& slug, const set<int>& definedSubtaskIds) {
        TestSuiteBuilder::setSlug(slug);
        TestSuiteBuilder::setDefinedSubtaskIds(definedSubtaskIds);
        TestSuiteBuilder::setBeforeClosure([this] {
            BeforeTestCase();
        });
        TestSuiteBuilder::setAfterClosure([this] {
            AfterTestCase();
        });

        for (auto sampleTestCase : sampleTestCases_) {
            try {
                TestSuiteBuilder::newSampleTestCase();
                (this->*sampleTestCase)();
            } catch (NotImplementedException&) {
                break;
            }
        }

        try {
            TestCases();
        } catch (NotImplementedException&) {
            for (auto testGroup : testGroups_) {
                try {
                    TestSuiteBuilder::newTestGroup();
                    (this->*testGroup)();
                } catch (NotImplementedException&) {
                    break;
                }
            }
        }
        return TestSuiteBuilder::build();
    }

    SeedSetter* buildSeedSetter() {
        return new SeedSetter([=] (unsigned seed) {rnd.setSeed(seed);});
    }

protected:
    Random rnd;

    virtual void BeforeTestCase() {}
    virtual void AfterTestCase() {}
    virtual void SampleTestCase1() {throw NotImplementedException();}
    virtual void SampleTestCase2() {throw NotImplementedException();}
    virtual void SampleTestCase3() {throw NotImplementedException();}
    virtual void SampleTestCase4() {throw NotImplementedException();}
    virtual void SampleTestCase5() {throw NotImplementedException();}
    virtual void SampleTestCase6() {throw NotImplementedException();}
    virtual void SampleTestCase7() {throw NotImplementedException();}
    virtual void SampleTestCase8() {throw NotImplementedException();}
    virtual void SampleTestCase9() {throw NotImplementedException();}
    virtual void SampleTestCase10() {throw NotImplementedException();}
    virtual void SampleTestCase11() {throw NotImplementedException();}
    virtual void SampleTestCase12() {throw NotImplementedException();}
    virtual void SampleTestCase13() {throw NotImplementedException();}
    virtual void SampleTestCase14() {throw NotImplementedException();}
    virtual void SampleTestCase15() {throw NotImplementedException();}
    virtual void SampleTestCase16() {throw NotImplementedException();}
    virtual void SampleTestCase17() {throw NotImplementedException();}
    virtual void SampleTestCase18() {throw NotImplementedException();}
    virtual void SampleTestCase19() {throw NotImplementedException();}
    virtual void SampleTestCase20() {throw NotImplementedException();}
    virtual void SampleTestCase21() {throw NotImplementedException();}
    virtual void SampleTestCase22() {throw NotImplementedException();}
    virtual void SampleTestCase23() {throw NotImplementedException();}
    virtual void SampleTestCase24() {throw NotImplementedException();}
    virtual void SampleTestCase25() {throw NotImplementedException();}
    virtual void TestCases() {throw NotImplementedException();}
    virtual void TestGroup1() {throw NotImplementedException();}
    virtual void TestGroup2() {throw NotImplementedException();}
    virtual void TestGroup3() {throw NotImplementedException();}
    virtual void TestGroup4() {throw NotImplementedException();}
    virtual void TestGroup5() {throw NotImplementedException();}
    virtual void TestGroup6() {throw NotImplementedException();}
    virtual void TestGroup7() {throw NotImplementedException();}
    virtual void TestGroup8() {throw NotImplementedException();}
    virtual void TestGroup9() {throw NotImplementedException();}
    virtual void TestGroup10() {throw NotImplementedException();}
    virtual void TestGroup11() {throw NotImplementedException();}
    virtual void TestGroup12() {throw NotImplementedException();}
    virtual void TestGroup13() {throw NotImplementedException();}
    virtual void TestGroup14() {throw NotImplementedException();}
    virtual void TestGroup15() {throw NotImplementedException();}
    virtual void TestGroup16() {throw NotImplementedException();}
    virtual void TestGroup17() {throw NotImplementedException();}
    virtual void TestGroup18() {throw NotImplementedException();}
    virtual void TestGroup19() {throw NotImplementedException();}
    virtual void TestGroup20() {throw NotImplementedException();}
    virtual void TestGroup21() {throw NotImplementedException();}
    virtual void TestGroup22() {throw NotImplementedException();}
    virtual void TestGroup23() {throw NotImplementedException();}
    virtual void TestGroup24() {throw NotImplementedException();}
    virtual void TestGroup25() {throw NotImplementedException();}
};

}


text:
require_relative "helper"

module Ruby
  class TestSendNoArgSol < MiniTest::Test
    include RubyTests
    def setup
      @lst = compile( "foo").to_sol
    end
    def test_simple_class
      assert_equal Sol::SendStatement , @lst.class
    end
    def test_simple_name
      assert_equal :foo , @lst.name
    end
    def test_simple_receiver
      assert_equal Sol::SelfExpression , @lst.receiver.class
    end
    def test_simple_args
      assert_equal [] , @lst.arguments
    end
  end
  class TestSendSimpleArgSol < MiniTest::Test
    include RubyTests
    def setup
      @lst = compile( "bar(1)").to_sol
    end
    def test_class
      assert_equal Sol::SendStatement , @lst.class
    end
    def test_name
      assert_equal :bar , @lst.name
    end
    def test_receiver
      assert_equal Sol::SelfExpression , @lst.receiver.class
    end
    def test_args
      assert_equal Sol::IntegerConstant ,  @lst.arguments.first.class
    end
  end
  class TestSendSuperSol < MiniTest::Test
    include RubyTests
    def test_super0
      lst = compile( "super").to_sol
      assert_equal Sol::SuperStatement , lst.class
    end
    def test_super0_receiver
      lst = compile( "super").to_sol
      assert_equal Sol::SelfExpression , lst.receiver.class
    end
  end
  class TestSendSuperArgsSol < MiniTest::Test
    include RubyTests
    def setup
      @lst = compile( "super(1)").to_sol
    end
    def test_super_class
      assert_equal Sol::SuperStatement , @lst.class
    end
    def test_super_receiver
      assert_equal Sol::SelfExpression , @lst.receiver.class
    end
    def test_super_name
      assert_equal :super,  @lst.name
    end
  end
  class TestSendReceiverTypeSol < MiniTest::Test
    include RubyTests

    def setup
      Parfait.boot!(Parfait.default_test_options)
    end

    def test_int_receiver
      sent = compile( "5.div4").to_sol
      assert_equal Parfait::Type , sent.receiver.ct_type.class
      assert_equal "Integer_Type" , sent.receiver.ct_type.name
    end
    def test_string_receiver
      sent = compile( "'5'.putstring").to_sol
      assert_equal Parfait::Type , sent.receiver.ct_type.class
      assert_equal "Word_Type" , sent.receiver.ct_type.name
    end
  end
  class TestSendReceiver < MiniTest::Test
    include RubyTests
    def setup
      @lst = compile( "call.once.more").to_sol
    end
    def test_class
      assert_equal Sol::Statements , @lst.class
    end
    def test_one
      assert_equal Sol::LocalAssignment , @lst.first.class
    end
    def test_one_name
      assert @lst[0].name.to_s.start_with?("tmp_")
    end
    def test_one_value
      assert_equal :call , @lst[0].value.name
    end
    def test_two_name
      assert @lst[1].name.to_s.start_with?("tmp_")
    end
    def test_two_value
      assert_equal :once , @lst[1].value.name
    end
    def test_three_class
      assert_equal Sol::SendStatement, @lst[2].class
    end
    def test_three_name
      assert_equal :more , @lst[2].name
    end
    def test_three_self
      assert @lst[2].receiver.name.to_s.start_with?("tmp_")
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
DECLARE
	CURSOR c_from IS
SELECT
	Old.ORIG_ID as oldOrigId, Old.cons_id as oldId, New.orig_Id as newOrigId, New.cons_id as newId
FROM consumer Old
	JOIN consumer New ON (old.SUB_UNID = new.ORIG_ID AND old.CONS_ID != new.CONS_ID)
WHERE ROWNUM <= 10000
;

BEGIN

	FOR ind IN c_from LOOP -- Cycle with long operations

	DBMS_OUTPUT.PUT_LINE(ind.oldOrigId || ':' || ind.oldId || ':' || ind.newOrigId || ':' || ind.newId); -- That output will be available only AFTER all execution
	tmp_log(ind.oldOrigId || ':' || ind.oldId || ':' || ind.newOrigId || ':' || ind.newId); -- That log you may see in table directly as it arrived. Look at select.sql and select.watch.sql examples.

	UPDATE ADD_ARC_EXPS_H SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE ARC_EXPS_D SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE ARC_EXPS_H SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE CC_SCHEMA SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE CC_STRUCT SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE CHANNEL_STRUCT SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE CONTRACT SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE CUR_EQUIP_STATUS SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE POINT_CONNECT SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE DISP_LIMIT SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE META_CONSUMER SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE ACT_CONSUMPTION SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE ACT_CONSUMP_OBJ SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE GAS_CONS_OBJECT SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;

	UPDATE CL_ACCOUNT SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE CONSUMP_RESTRICT SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE CONS_OUT SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE CONS_TO_LTG SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE CONS_TYPE_PARAM SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE EXCEL_MAPPING_SDU SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE HEAD_CONNECTION SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE INDEPEND_SUPPLY SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE PRC_OVER_LESS SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE PRG2MRG_CONSUMER SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE PRIORITY SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE REQ_YEAR_LIMIT SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE SDU_GAS_CC SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE SDU_GAS_CONS SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE SUPPLY_LICENCE SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;
	UPDATE TECHNICAL_CONDITIONS_JOIN SET CONS_ID = ind.oldId WHERE CONS_ID = ind.newId;

	DELETE consumer WHERE cons_id = ind.newId;
	UPDATE consumer SET ORIG_ID = SUB_UNID WHERE CONS_ID = ind.oldId;

	COMMIT;

	END LOOP;

COMMIT;

END;
/


text:
#import <iTunesStoreUI/SUScriptInterface.h>

@interface SUScriptInterface (SUScriptGiftViewController)
- (id)makeGiftViewController;
@end


text:
import copy
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.optimizers import Optimizer
from keras.callbacks import LearningRateScheduler
from model.setting import Setting

class LangModelSGD(Optimizer):

    def __init__(self, setting, verbose=True):
        super(LangModelSGD, self).__init__(clipnorm=setting.norm_clipping)

        self.iterations = K.variable(0., name="iterations")
        self.lr = K.variable(1.0, name="lr")
        self.epoch_interval = K.variable(setting.epoch_interval)
        self.decay = K.variable(setting.decay)
        self.verbose = verbose

    def get_updates(self, params, constraints, loss):
        grads = self.get_gradients(loss, params)
        self.updates = []
        self.updates.append(K.update_add(self.iterations, 1))
        for p, g in zip(params, grads):
            self.updates.append((p, p - self.lr * g))
        return self.updates

    def get_config(self):
        config = {"iterations": float(K.get_value(self.iterations)),
                  "lr": float(K.get_value(self.lr))
                  }
        base_config = super(LangModelSGD, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

    def get_lr_scheduler(self):
        def scheduler(epoch):
            epoch_interval = K.get_value(self.epoch_interval)
            if epoch != 0 and (epoch + 1) % epoch_interval == 0:
                lr = K.get_value(self.lr)
                decay = K.get_value(self.decay)
                K.set_value(self.lr, lr * decay)
                if self.verbose:
                    print(self.get_config())
            return K.get_value(self.lr)

        return LearningRateScheduler(scheduler)


text:
package initializer

import (
	"k8s.io/apiserver/pkg/admission"
	"k8s.io/apiserver/pkg/authorization/authorizer"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
)

type pluginInitializer struct {
	externalClient    kubernetes.Interface
	externalInformers informers.SharedInformerFactory
	authorizer        authorizer.Authorizer
}

// New creates an instance of admission plugins initializer.
// TODO(p0lyn0mial): make the parameters public, this construction seems to be redundant.
func New(
	extClientset kubernetes.Interface,
	extInformers informers.SharedInformerFactory,
	authz authorizer.Authorizer,
) pluginInitializer {
	return pluginInitializer{
		externalClient:    extClientset,
		externalInformers: extInformers,
		authorizer:        authz,
	}
}

// Initialize checks the initialization interfaces implemented by a plugin
// and provide the appropriate initialization data
func (i pluginInitializer) Initialize(plugin admission.Interface) {
	if wants, ok := plugin.(WantsExternalKubeClientSet); ok {
		wants.SetExternalKubeClientSet(i.externalClient)
	}

	if wants, ok := plugin.(WantsExternalKubeInformerFactory); ok {
		wants.SetExternalKubeInformerFactory(i.externalInformers)
	}

	if wants, ok := plugin.(WantsAuthorizer); ok {
		wants.SetAuthorizer(i.authorizer)
	}
}

var _ admission.PluginInitializer = pluginInitializer{}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<title>SnapPoint Demo</title>

SnapPoint.js Demo

Easy-to-use jQuery plugin that "SnapPoints." A SnapPoint is the beginning of a block of content that you want the browser's window to scroll down to to. Metaphorically stated, SnapPoint attaches a little vacuum to any block level element (e.g. <div>). It sucks the visitors screen down to the top of that content, or if paging is horizontally it sucks the content to the left of the screen.

#1 This is a block of content

#2 This is a second block of content

#3 This is a third block of content
Scroll to the Right


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/extensions/file_manager/private_api_drive.h"

#include "base/prefs/pref_service.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/chromeos/drive/drive_app_registry.h"
#include "chrome/browser/chromeos/drive/drive_integration_service.h"
#include "chrome/browser/chromeos/drive/logging.h"
#include "chrome/browser/chromeos/extensions/file_manager/file_manager_util.h"
#include "chrome/browser/chromeos/extensions/file_manager/file_tasks.h"
#include "chrome/browser/chromeos/extensions/file_manager/private_api_util.h"
#include "chrome/browser/chromeos/fileapi/file_system_backend.h"
#include "chrome/browser/extensions/api/file_handlers/app_file_handler_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host.h"
#include "webkit/common/fileapi/file_system_util.h"

using content::BrowserThread;

namespace file_manager {
namespace {

// List of connection types of drive.
// Keep this in sync with the DriveConnectionType in volume_manager.js.
const char kDriveConnectionTypeOffline[] = "offline";
const char kDriveConnectionTypeMetered[] = "metered";
const char kDriveConnectionTypeOnline[] = "online";

// List of reasons of kDriveConnectionType*.
// Keep this in sync with the DriveConnectionReason in volume_manager.js.
const char kDriveConnectionReasonNotReady[] = "not_ready";
const char kDriveConnectionReasonNoNetwork[] = "no_network";
const char kDriveConnectionReasonNoService[] = "no_service";

// Does nothing with a bool parameter. Used as a placeholder for calling
// ClearCacheAndRemountFileSystem(). TODO(yoshiki): Handle an error from
// ClearCacheAndRemountFileSystem() properly: http://crbug.com/140511.
void DoNothingWithBool(bool /* success */) {
}

// Copies properties from |entry_proto| to |property_dict|.
void FillDriveEntryPropertiesValue(
    const drive::ResourceEntry& entry_proto,
    DictionaryValue* property_dict) {
  property_dict->SetBoolean("sharedWithMe", entry_proto.shared_with_me());

  if (!entry_proto.has_file_specific_info())
    return;

  const drive::FileSpecificInfo& file_specific_info =
      entry_proto.file_specific_info();

  property_dict->SetString("thumbnailUrl", file_specific_info.thumbnail_url());
  property_dict->SetBoolean("isHosted",
                            file_specific_info.is_hosted_document());
  property_dict->SetString("contentMimeType",
                           file_specific_info.content_mime_type());
}

}  // namespace

GetDriveEntryPropertiesFunction::GetDriveEntryPropertiesFunction() {
}

GetDriveEntryPropertiesFunction::~GetDriveEntryPropertiesFunction() {
}

bool GetDriveEntryPropertiesFunction::RunImpl() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  std::string file_url_str;
  if (args_->GetSize() != 1 || !args_->GetString(0, &file_url_str))
    return false;

  GURL file_url = GURL(file_url_str);
  file_path_ = drive::util::ExtractDrivePath(
      util::GetLocalPathFromURL(render_view_host(), profile(), file_url));

  properties_.reset(new base::DictionaryValue);
  properties_->SetString("fileUrl", file_url.spec());

  // Start getting the file info.
  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(profile_);
  // |integration_service| is NULL if Drive is disabled.
  if (!integration_service) {
    CompleteGetFileProperties(drive::FILE_ERROR_FAILED);
    return true;
  }

  integration_service->file_system()->GetResourceEntryByPath(
      file_path_,
      base::Bind(&GetDriveEntryPropertiesFunction::OnGetFileInfo, this));
  return true;
}

void GetDriveEntryPropertiesFunction::OnGetFileInfo(
    drive::FileError error,
    scoped_ptr<drive::ResourceEntry> entry) {
  DCHECK(properties_);

  if (error != drive::FILE_ERROR_OK) {
    CompleteGetFileProperties(error);
    return;
  }
  DCHECK(entry);

  FillDriveEntryPropertiesValue(*entry, properties_.get());

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(profile_);
  // |integration_service| is NULL if Drive is disabled.
  if (!integration_service) {
    CompleteGetFileProperties(drive::FILE_ERROR_FAILED);
    return;
  }

  // The properties meaningful for directories are already filled in
  // FillDriveEntryPropertiesValue().
  if (entry.get() && !entry->has_file_specific_info()) {
    CompleteGetFileProperties(error);
    return;
  }

  const drive::FileSpecificInfo& file_specific_info =
      entry->file_specific_info();

  // Get drive WebApps that can accept this file.
  ScopedVector<drive::DriveAppInfo> drive_apps;
  integration_service->drive_app_registry()->GetAppsForFile(
      file_path_, file_specific_info.content_mime_type(), &drive_apps);
  if (!drive_apps.empty()) {
    std::string default_task_id = file_tasks::GetDefaultTaskIdFromPrefs(
        profile_,
        file_specific_info.content_mime_type(),
        file_path_.Extension());
    file_tasks::TaskDescriptor default_task;
    file_tasks::ParseTaskID(default_task_id, &default_task);
    DCHECK(default_task_id.empty() || !default_task.app_id.empty());

    ListValue* apps = new ListValue();
    properties_->Set("driveApps", apps);
    for (ScopedVector<drive::DriveAppInfo>::const_iterator it =
             drive_apps.begin();
         it != drive_apps.end(); ++it) {
      const drive::DriveAppInfo* app_info = *it;
      DictionaryValue* app = new DictionaryValue();
      app->SetString("appId", app_info->app_id);
      app->SetString("appName", app_info->app_name);
      GURL app_icon = util::FindPreferredIcon(app_info->app_icons,
                                              util::kPreferredIconSize);
      if (!app_icon.is_empty())
        app->SetString("appIcon", app_icon.spec());
      GURL doc_icon = util::FindPreferredIcon(app_info->document_icons,
                                              util::kPreferredIconSize);
      if (!doc_icon.is_empty())
        app->SetString("docIcon", doc_icon.spec());
      app->SetString("objectType", app_info->object_type);
      app->SetBoolean("isPrimary",
                      default_task.app_id == app_info->app_id);
      apps->Append(app);
    }
  }

  integration_service->file_system()->GetCacheEntryByResourceId(
      entry->resource_id(),
      base::Bind(&GetDriveEntryPropertiesFunction::CacheStateReceived, this));
}

void GetDriveEntryPropertiesFunction::CacheStateReceived(
    bool /* success */,
    const drive::FileCacheEntry& cache_entry) {
  // In case of an error (i.e. success is false), cache_entry.is_*() all
  // returns false.
  properties_->SetBoolean("isPinned", cache_entry.is_pinned());
  properties_->SetBoolean("isPresent", cache_entry.is_present());
  properties_->SetBoolean("isDirty", cache_entry.is_dirty());

  CompleteGetFileProperties(drive::FILE_ERROR_OK);
}

void GetDriveEntryPropertiesFunction::CompleteGetFileProperties(
    drive::FileError error) {
  if (error != drive::FILE_ERROR_OK)
    properties_->SetInteger("errorCode", error);
  SetResult(properties_.release());
  SendResponse(true);
}

PinDriveFileFunction::PinDriveFileFunction() {
}

PinDriveFileFunction::~PinDriveFileFunction() {
}

bool PinDriveFileFunction::RunImpl() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  std::string url;
  bool set_pin = false;
  if (args_->GetSize() != 2 ||
      !args_->GetString(0, &url) ||
      !args_->GetBoolean(1, &set_pin))
    return false;

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(profile_);
  drive::FileSystemInterface* file_system =
      integration_service ? integration_service->file_system() : NULL;
  if (!file_system)  // |file_system| is NULL if Drive is disabled.
    return false;

  base::FilePath drive_path =
      drive::util::ExtractDrivePath(
          util::GetLocalPathFromURL(render_view_host(), profile(), GURL(url)));
  if (set_pin) {
    file_system->Pin(drive_path,
                     base::Bind(&PinDriveFileFunction::OnPinStateSet, this));
  } else {
    file_system->Unpin(drive_path,
                       base::Bind(&PinDriveFileFunction::OnPinStateSet, this));
  }
  return true;
}

void PinDriveFileFunction::OnPinStateSet(drive::FileError error) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (error == drive::FILE_ERROR_OK) {
    SendResponse(true);
  } else {
    error_ = drive::FileErrorToString(error);
    SendResponse(false);
  }
}

GetDriveFilesFunction::GetDriveFilesFunction()
    : local_paths_(NULL) {
}

GetDriveFilesFunction::~GetDriveFilesFunction() {
}

bool GetDriveFilesFunction::RunImpl() {
  ListValue* file_urls_as_strings = NULL;
  if (!args_->GetList(0, &file_urls_as_strings))
    return false;

  // Convert the list of strings to a list of GURLs.
  for (size_t i = 0; i < file_urls_as_strings->GetSize(); ++i) {
    std::string file_url_as_string;
    if (!file_urls_as_strings->GetString(i, &file_url_as_string))
      return false;
    const base::FilePath path = util::GetLocalPathFromURL(
        render_view_host(), profile(), GURL(file_url_as_string));
    DCHECK(drive::util::IsUnderDriveMountPoint(path));
    base::FilePath drive_path = drive::util::ExtractDrivePath(path);
    remaining_drive_paths_.push(drive_path);
  }

  local_paths_ = new ListValue;
  GetFileOrSendResponse();
  return true;
}

void GetDriveFilesFunction::GetFileOrSendResponse() {
  // Send the response if all files are obtained.
  if (remaining_drive_paths_.empty()) {
    SetResult(local_paths_);
    SendResponse(true);
    return;
  }

  // Get the file on the top of the queue.
  base::FilePath drive_path = remaining_drive_paths_.front();

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(profile_);
  // |integration_service| is NULL if Drive is disabled.
  if (!integration_service) {
    OnFileReady(drive::FILE_ERROR_FAILED, drive_path,
                scoped_ptr<drive::ResourceEntry>());
    return;
  }

  integration_service->file_system()->GetFileByPath(
      drive_path,
      base::Bind(&GetDriveFilesFunction::OnFileReady, this));
}

void GetDriveFilesFunction::OnFileReady(
    drive::FileError error,
    const base::FilePath& local_path,
    scoped_ptr<drive::ResourceEntry> entry) {
  base::FilePath drive_path = remaining_drive_paths_.front();

  if (error == drive::FILE_ERROR_OK) {
    local_paths_->Append(new base::StringValue(local_path.value()));
    DVLOG(1) << "Got " << drive_path.value() << " as " << local_path.value();

    // TODO(benchan): If the file is a hosted document, a temporary JSON file
    // is created to represent the document. The JSON file is not cached and
    // should be deleted after use. We need to somehow communicate with
    // file_manager.js to manage the lifetime of the temporary file.
    // See crosbug.com/28058.
  } else {
    local_paths_->Append(new base::StringValue(""));
    DVLOG(1) << "Failed to get " << drive_path.value()
             << " with error code: " << error;
  }

  remaining_drive_paths_.pop();

  // Start getting the next file.
  GetFileOrSendResponse();
}

CancelFileTransfersFunction::CancelFileTransfersFunction() {
}

CancelFileTransfersFunction::~CancelFileTransfersFunction() {
}

bool CancelFileTransfersFunction::RunImpl() {
  ListValue* url_list = NULL;
  if (!args_->GetList(0, &url_list))
    return false;

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(profile_);
  // |integration_service| is NULL if Drive is disabled.
  if (!integration_service)
    return false;

  // Create the mapping from file path to job ID.
  drive::JobListInterface* job_list = integration_service->job_list();
  DCHECK(job_list);
  std::vector<drive::JobInfo> jobs = job_list->GetJobInfoList();

  typedef std::map<base::FilePath, std::vector<drive::JobID> > PathToIdMap;
  PathToIdMap path_to_id_map;
  for (size_t i = 0; i < jobs.size(); ++i) {
    if (drive::IsActiveFileTransferJobInfo(jobs[i]))
      path_to_id_map[jobs[i].file_path].push_back(jobs[i].job_id);
  }

  // Cancel by Job ID.
  scoped_ptr<ListValue> responses(new ListValue());
  for (size_t i = 0; i < url_list->GetSize(); ++i) {
    std::string url_as_string;
    url_list->GetString(i, &url_as_string);

    base::FilePath file_path = util::GetLocalPathFromURL(
        render_view_host(), profile(), GURL(url_as_string));
    if (file_path.empty())
      continue;

    DCHECK(drive::util::IsUnderDriveMountPoint(file_path));
    file_path = drive::util::ExtractDrivePath(file_path);
    scoped_ptr<DictionaryValue> result(new DictionaryValue());

    // Cancel all the jobs for the file.
    PathToIdMap::iterator it = path_to_id_map.find(file_path);
    if (it != path_to_id_map.end()) {
      for (size_t i = 0; i < it->second.size(); ++i)
        job_list->CancelJob(it->second[i]);
    }
    result->SetBoolean("canceled", it != path_to_id_map.end());
    // TODO(kinaba): simplify cancelFileTransfer() to take single URL each time,
    // and eliminate this field; it is just returning a copy of the argument.
    result->SetString("fileUrl", url_as_string);
    responses->Append(result.release());
  }
  SetResult(responses.release());
  SendResponse(true);
  return true;
}

SearchDriveFunction::SearchDriveFunction() {
}

SearchDriveFunction::~SearchDriveFunction() {
}

bool SearchDriveFunction::RunImpl() {
  DictionaryValue* search_params;
  if (!args_->GetDictionary(0, &search_params))
    return false;

  std::string query;
  if (!search_params->GetString("query", &query))
    return false;

  std::string next_feed;
  if (!search_params->GetString("nextFeed", &next_feed))
    return false;

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(profile_);
  // |integration_service| is NULL if Drive is disabled.
  if (!integration_service || !integration_service->file_system())
    return false;

  integration_service->file_system()->Search(
      query, GURL(next_feed),
      base::Bind(&SearchDriveFunction::OnSearch, this));
  return true;
}

void SearchDriveFunction::OnSearch(
    drive::FileError error,
    const GURL& next_feed,
    scoped_ptr<std::vector<drive::SearchResultInfo> > results) {
  if (error != drive::FILE_ERROR_OK) {
    SendResponse(false);
    return;
  }

  DCHECK(results.get());

  base::ListValue* entries = new ListValue();

  // Convert Drive files to something File API stack can understand.
  GURL origin_url = source_url_.GetOrigin();
  fileapi::FileSystemType file_system_type = fileapi::kFileSystemTypeExternal;
  GURL file_system_root_url =
      fileapi::GetFileSystemRootURI(origin_url, file_system_type);
  std::string file_system_name =
      fileapi::GetFileSystemName(origin_url, file_system_type);
  for (size_t i = 0; i < results->size(); ++i) {
    DictionaryValue* entry = new DictionaryValue();
    entry->SetString("fileSystemName", file_system_name);
    entry->SetString("fileSystemRoot", file_system_root_url.spec());
    entry->SetString("fileFullPath", "/" + results->at(i).path.value());
    entry->SetBoolean("fileIsDirectory",
                      results->at(i).entry.file_info().is_directory());
    entries->Append(entry);
  }

  base::DictionaryValue* result = new DictionaryValue();
  result->Set("entries", entries);
  result->SetString("nextFeed", next_feed.spec());

  SetResult(result);
  SendResponse(true);
}

SearchDriveMetadataFunction::SearchDriveMetadataFunction() {
}

SearchDriveMetadataFunction::~SearchDriveMetadataFunction() {
}

bool SearchDriveMetadataFunction::RunImpl() {
  DictionaryValue* search_params;
  if (!args_->GetDictionary(0, &search_params))
    return false;

  std::string query;
  if (!search_params->GetString("query", &query))
    return false;

  std::string types;
  if (!search_params->GetString("types", &types))
    return false;

  int max_results = 0;
  if (!search_params->GetInteger("maxResults", &max_results))
    return false;

  drive::util::Log(logging::LOG_INFO,
                   "%s[%d] called. (types: '%s', maxResults: '%d')",
                   name().c_str(),
                   request_id(),
                   types.c_str(),
                   max_results);
  set_log_on_completion(true);

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(profile_);
  // |integration_service| is NULL if Drive is disabled.
  if (!integration_service || !integration_service->file_system())
    return false;

  int options = drive::SEARCH_METADATA_ALL;
  // TODO(hirono): Switch to the JSON scheme compiler. http://crbug.com/241693
  if (types == "EXCLUDE_DIRECTORIES")
    options = drive::SEARCH_METADATA_EXCLUDE_DIRECTORIES;
  else if (types == "SHARED_WITH_ME")
    options = drive::SEARCH_METADATA_SHARED_WITH_ME;
  else if (types == "OFFLINE")
    options = drive::SEARCH_METADATA_OFFLINE;
  else
    DCHECK_EQ("ALL", types);

  integration_service->file_system()->SearchMetadata(
      query,
      options,
      max_results,
      base::Bind(&SearchDriveMetadataFunction::OnSearchMetadata, this));
  return true;
}

void SearchDriveMetadataFunction::OnSearchMetadata(
    drive::FileError error,
    scoped_ptr<drive::MetadataSearchResultVector> results) {
  if (error != drive::FILE_ERROR_OK) {
    SendResponse(false);
    return;
  }

  DCHECK(results.get());

  base::ListValue* results_list = new ListValue();

  // Convert Drive files to something File API stack can understand.  See
  // file_browser_handler_custom_bindings.cc and
  // file_browser_private_custom_bindings.js for how this is magically
  // converted to a FileEntry.
  GURL origin_url = source_url_.GetOrigin();
  fileapi::FileSystemType file_system_type = fileapi::kFileSystemTypeExternal;
  GURL file_system_root_url =
      fileapi::GetFileSystemRootURI(origin_url, file_system_type);
  std::string file_system_name =
      fileapi::GetFileSystemName(origin_url, file_system_type);
  for (size_t i = 0; i < results->size(); ++i) {
    DictionaryValue* result_dict = new DictionaryValue();

    // FileEntry fields.
    DictionaryValue* entry = new DictionaryValue();
    entry->SetString("fileSystemName", file_system_name);
    entry->SetString("fileSystemRoot", file_system_root_url.spec());
    entry->SetString("fileFullPath", "/" + results->at(i).path.value());
    entry->SetBoolean("fileIsDirectory",
                      results->at(i).entry.file_info().is_directory());

    result_dict->Set("entry", entry);
    result_dict->SetString("highlightedBaseName",
                           results->at(i).highlighted_base_name);
    results_list->Append(result_dict);
  }

  SetResult(results_list);
  SendResponse(true);
}

ClearDriveCacheFunction::ClearDriveCacheFunction() {
}

ClearDriveCacheFunction::~ClearDriveCacheFunction() {
}

bool ClearDriveCacheFunction::RunImpl() {
  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(profile_);
  // |integration_service| is NULL if Drive is disabled.
  if (!integration_service || !integration_service->file_system())
    return false;

  // TODO(yoshiki): Receive a callback from JS-side and pass it to
  // ClearCacheAndRemountFileSystem(). http://crbug.com/140511
  integration_service->ClearCacheAndRemountFileSystem(
      base::Bind(&DoNothingWithBool));

  SendResponse(true);
  return true;
}

GetDriveConnectionStateFunction::GetDriveConnectionStateFunction() {
}

GetDriveConnectionStateFunction::~GetDriveConnectionStateFunction() {
}

bool GetDriveConnectionStateFunction::RunImpl() {
  scoped_ptr<DictionaryValue> value(new DictionaryValue());
  scoped_ptr<ListValue> reasons(new ListValue());

  std::string type_string;
  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(profile_);

  bool ready = integration_service &&
      integration_service->drive_service()->CanSendRequest();
  bool is_connection_cellular =
      net::NetworkChangeNotifier::IsConnectionCellular(
          net::NetworkChangeNotifier::GetConnectionType());

  if (net::NetworkChangeNotifier::IsOffline() || !ready) {
    type_string = kDriveConnectionTypeOffline;
    if (net::NetworkChangeNotifier::IsOffline())
      reasons->AppendString(kDriveConnectionReasonNoNetwork);
    if (!ready)
      reasons->AppendString(kDriveConnectionReasonNotReady);
    if (!integration_service)
      reasons->AppendString(kDriveConnectionReasonNoService);
  } else if (
      is_connection_cellular &&
      profile_->GetPrefs()->GetBoolean(prefs::kDisableDriveOverCellular)) {
    type_string = kDriveConnectionTypeMetered;
  } else {
    type_string = kDriveConnectionTypeOnline;
  }

  value->SetString("type", type_string);
  value->Set("reasons", reasons.release());
  SetResult(value.release());

  drive::util::Log(logging::LOG_INFO, "%s succeeded.", name().c_str());
  return true;
}

RequestAccessTokenFunction::RequestAccessTokenFunction() {
}

RequestAccessTokenFunction::~RequestAccessTokenFunction() {
}

bool RequestAccessTokenFunction::RunImpl() {
  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(profile_);
  bool refresh;
  args_->GetBoolean(0, &refresh);

  if (!integration_service) {
    SetResult(new base::StringValue(""));
    SendResponse(true);
    return true;
  }

  // If refreshing is requested, then clear the token to refetch it.
  if (refresh)
    integration_service->drive_service()->ClearAccessToken();

  // Retrieve the cached auth token (if available), otherwise the AuthService
  // instance will try to refetch it.
  integration_service->drive_service()->RequestAccessToken(
      base::Bind(&RequestAccessTokenFunction::OnAccessTokenFetched, this));
  return true;
}

void RequestAccessTokenFunction::OnAccessTokenFetched(
    google_apis::GDataErrorCode code, const std::string& access_token) {
  SetResult(new base::StringValue(access_token));
  SendResponse(true);
}

GetShareUrlFunction::GetShareUrlFunction() {
}

GetShareUrlFunction::~GetShareUrlFunction() {
}

bool GetShareUrlFunction::RunImpl() {
  std::string file_url;
  if (!args_->GetString(0, &file_url))
    return false;

  const base::FilePath path = util::GetLocalPathFromURL(
      render_view_host(), profile(), GURL(file_url));
  DCHECK(drive::util::IsUnderDriveMountPoint(path));

  base::FilePath drive_path = drive::util::ExtractDrivePath(path);

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::GetForProfile(profile_);
  // |integration_service| is NULL if Drive is disabled.
  if (!integration_service)
    return false;

  integration_service->file_system()->GetShareUrl(
      drive_path,
      util::GetFileBrowserExtensionUrl(),  // embed origin
      base::Bind(&GetShareUrlFunction::OnGetShareUrl, this));
  return true;
}

void GetShareUrlFunction::OnGetShareUrl(drive::FileError error,
                                        const GURL& share_url) {
  if (error != drive::FILE_ERROR_OK) {
    error_ = "Share Url for this item is not available.";
    SendResponse(false);
    return;
  }

  SetResult(new base::StringValue(share_url.spec()));
  SendResponse(true);
}

}  // namespace file_manager


text:
package com.example.android.tvleanback.player;

import android.content.Context;
import androidx.leanback.media.PlaybackTransportControlGlue;
import androidx.leanback.widget.Action;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.PlaybackControlsRow;

import com.google.android.exoplayer2.ext.leanback.LeanbackPlayerAdapter;

import java.util.concurrent.TimeUnit;

/**
 * Manages customizing the actions in the {@link PlaybackControlsRow}. Adds and manages the
 * following actions to the primary and secondary controls:
 *
 * <ul>
 *   <li>{@link androidx.leanback.widget.PlaybackControlsRow.RepeatAction}
 *   <li>{@link androidx.leanback.widget.PlaybackControlsRow.ThumbsDownAction}
 *   <li>{@link androidx.leanback.widget.PlaybackControlsRow.ThumbsUpAction}
 *   <li>{@link androidx.leanback.widget.PlaybackControlsRow.SkipPreviousAction}
 *   <li>{@link androidx.leanback.widget.PlaybackControlsRow.SkipNextAction}
 *   <li>{@link androidx.leanback.widget.PlaybackControlsRow.FastForwardAction}
 *   <li>{@link androidx.leanback.widget.PlaybackControlsRow.RewindAction}
 * </ul>
 *
 * Note that the superclass, {@link PlaybackTransportControlGlue}, manages the playback controls
 * row.
 */
public class VideoPlayerGlue extends PlaybackTransportControlGlue<LeanbackPlayerAdapter> {

    private static final long TEN_SECONDS = TimeUnit.SECONDS.toMillis(10);

    /** Listens for when skip to next and previous actions have been dispatched. */
    public interface OnActionClickedListener {

        /** Skip to the previous item in the queue. */
        void onPrevious();

        /** Skip to the next item in the queue. */
        void onNext();
    }

    private final OnActionClickedListener mActionListener;

    private PlaybackControlsRow.RepeatAction mRepeatAction;
    private PlaybackControlsRow.ThumbsUpAction mThumbsUpAction;
    private PlaybackControlsRow.ThumbsDownAction mThumbsDownAction;
    private PlaybackControlsRow.SkipPreviousAction mSkipPreviousAction;
    private PlaybackControlsRow.SkipNextAction mSkipNextAction;
    private PlaybackControlsRow.FastForwardAction mFastForwardAction;
    private PlaybackControlsRow.RewindAction mRewindAction;

    public VideoPlayerGlue(
            Context context,
            LeanbackPlayerAdapter playerAdapter,
            OnActionClickedListener actionListener) {
        super(context, playerAdapter);

        mActionListener = actionListener;

        mSkipPreviousAction = new PlaybackControlsRow.SkipPreviousAction(context);
        mSkipNextAction = new PlaybackControlsRow.SkipNextAction(context);
        mFastForwardAction = new PlaybackControlsRow.FastForwardAction(context);
        mRewindAction = new PlaybackControlsRow.RewindAction(context);

        mThumbsUpAction = new PlaybackControlsRow.ThumbsUpAction(context);
        mThumbsUpAction.setIndex(PlaybackControlsRow.ThumbsUpAction.INDEX_OUTLINE);
        mThumbsDownAction = new PlaybackControlsRow.ThumbsDownAction(context);
        mThumbsDownAction.setIndex(PlaybackControlsRow.ThumbsDownAction.INDEX_OUTLINE);
        mRepeatAction = new PlaybackControlsRow.RepeatAction(context);
    }

    @Override
    protected void onCreatePrimaryActions(ArrayObjectAdapter adapter) {
        // Order matters, super.onCreatePrimaryActions() will create the play / pause action.
        // Will display as follows:
        // play/pause, previous, rewind, fast forward, next
        //   > /||      |<        <<        >>         >|
        super.onCreatePrimaryActions(adapter);
        adapter.add(mSkipPreviousAction);
        adapter.add(mRewindAction);
        adapter.add(mFastForwardAction);
        adapter.add(mSkipNextAction);
    }

    @Override
    protected void onCreateSecondaryActions(ArrayObjectAdapter adapter) {
        super.onCreateSecondaryActions(adapter);
        adapter.add(mThumbsDownAction);
        adapter.add(mThumbsUpAction);
        adapter.add(mRepeatAction);
    }

    @Override
    public void onActionClicked(Action action) {
        if (shouldDispatchAction(action)) {
            dispatchAction(action);
            return;
        }
        // Super class handles play/pause and delegates to abstract methods next()/previous().
        super.onActionClicked(action);
    }

    // Should dispatch actions that the super class does not supply callbacks for.
    private boolean shouldDispatchAction(Action action) {
        return action == mRewindAction
                || action == mFastForwardAction
                || action == mThumbsDownAction
                || action == mThumbsUpAction
                || action == mRepeatAction;
    }

    private void dispatchAction(Action action) {
        // Primary actions are handled manually.
        if (action == mRewindAction) {
            rewind();
        } else if (action == mFastForwardAction) {
            fastForward();
        } else if (action instanceof PlaybackControlsRow.MultiAction) {
            PlaybackControlsRow.MultiAction multiAction = (PlaybackControlsRow.MultiAction) action;
            multiAction.nextIndex();
            // Notify adapter of action changes to handle secondary actions, such as, thumbs up/down
            // and repeat.
            notifyActionChanged(
                    multiAction,
                    (ArrayObjectAdapter) getControlsRow().getSecondaryActionsAdapter());
        }
    }

    private void notifyActionChanged(
            PlaybackControlsRow.MultiAction action, ArrayObjectAdapter adapter) {
        if (adapter != null) {
            int index = adapter.indexOf(action);
            if (index >= 0) {
                adapter.notifyArrayItemRangeChanged(index, 1);
            }
        }
    }

    @Override
    public void next() {
        mActionListener.onNext();
    }

    @Override
    public void previous() {
        mActionListener.onPrevious();
    }

    /** Skips backwards 10 seconds. */
    public void rewind() {
        long newPosition = getCurrentPosition() - TEN_SECONDS;
        newPosition = (newPosition < 0) ? 0 : newPosition;
        getPlayerAdapter().seekTo(newPosition);
    }

    /** Skips forward 10 seconds. */
    public void fastForward() {
        if (getDuration() > -1) {
            long newPosition = getCurrentPosition() + TEN_SECONDS;
            newPosition = (newPosition > getDuration()) ? getDuration() : newPosition;
            getPlayerAdapter().seekTo(newPosition);
        }
    }
}


text:
<?php
namespace SmartEmailing\v3\Request\CustomFields\Search;

use SmartEmailing\v3\Api;
use SmartEmailing\v3\Exceptions\InvalidFormatException;
use SmartEmailing\v3\Request\AbstractRequest;
use function \SmartEmailing\v3\Helpers\value;

class Request extends AbstractRequest
{
    //region Properties
    /**
     * @var int
     */
    public $page = 1;
    /**
     * @var int
     */
    public $limit = 100;

    /**
     * Comma separated list of properties to select. eg. "?select=id,name" If not provided, all fields are selected.
     *
     * Allowed values: "id", "name", "type"
     * @var string|null
     */
    public $select = null;

    /**
     * Using this parameter, "customfield_options_url" property will be replaced by "customfield_options" contianing
     * expanded data. See examples below For more information see "/customfield-options" endpoint.
     *
     * Allowed values: "customfield_options"
     * @var string
     */
    public $expand = null;

    /**
     * Comma separated list of sorting keys from left side. Prepend "-" to any key for desc direction, eg.
     * "?sort=type,-name"
     *
     * Allowed values: "id", "name", "type"
     * @var string|null
     */
    public $sort = null;

    /**
     * Filters holder object
     * @var Filters
     */
    protected $filters;

    //endregion

    /**
     * SearchRequest constructor.
     *
     * @param Api      $api
     * @param int|null $page  desired page
     * @param int|null $limit Number of records on page. Maximum (default) allowed value is 500
     */
    public function __construct(Api $api, $page = null, $limit = null)
    {
        parent::__construct($api);

        $this->page = value($page, $this->page);
        $this->limit = value($limit, $this->limit);
        $this->filters = new Filters($this);
    }

    /**
     * Current filters
     * @return Filters
     */
    public function filter()
    {
        return $this->filters;
    }

    //region Setters
    /**
     * Using this parameter, "customfield_options_url" property will be replaced by "customfield_options" contianing
     * expanded data. See examples below For more information see "/customfield-options" endpoint.
     *
     * Allowed values: "customfield_options"
     *
     * @param string $expand
     *
     * @return Request
     *
     * @throws InvalidFormatException
     */
    public function expandBy($expand)
    {
        InvalidFormatException::checkInArray($expand, ['customfield_options']);
        $this->expand = $expand;
        return $this;
    }

    /**
     * Comma separated list of properties to select. eg. "?select=id,name" If not provided, all fields are selected.
     *
     * Allowed values: "id", "name", "type"
     *
     * @param null|string $select
     *
     * @return Request
     */
    public function select($select)
    {
        $this->select = $select;
        return $this;
    }

    /**
     * Comma separated list of sorting keys from left side. Prepend "-" to any key for desc direction, eg.
     * "?sort=type,-name"
     *
     * Allowed values: "id", "name", "type"
     *
     * @param null|string $sort
     *
     * @return Request
     */
    public function sortBy($sort)
    {
        $this->sort = $sort;
        return $this;
    }

    /**
     * @param int $page
     *
     * @return Request
     */
    public function setPage($page)
    {
        $this->page = $page;
        return $this;
    }

    /**
     * @param int $limit
     *
     * @return Request
     */
    public function limit($limit)
    {
        $this->limit = $limit;
        return $this;
    }

    //endregion

    /**
     * Converts the limit and page into sql offset
     *
     * @return int
     */
    public function offset()
    {
        return ($this->page - 1) * $this->limit;
    }

    /**
     * Builds a GET query
     * @return array
     */
    public function query()
    {
        $query = [
            'limit' => $this->limit,
            'offset' => $this->offset()
        ];

        // Append the optional filters/setup
        $this->setIfNotNull($query, 'sort', $this->sort)
            ->setIfNotNull($query, 'select', $this->select)
            ->setIfNotNull($query, 'id', $this->filter()->id)
            ->setIfNotNull($query, 'name', $this->filter()->name)
            ->setIfNotNull($query, 'type', $this->filter()->type)
            ->setIfNotNull($query, 'expand', $this->expand);

        return $query;
    }

    /**
     * @inheritDoc
     */
    protected function endpoint()
    {
        return 'customfields';
    }

    /**
     * @inheritDoc
     */
    protected function options()
    {

        return [
            'query' => $this->query()
        ];
    }

    /**
     * @inheritDoc
     * @return \SmartEmailing\v3\Request\CustomFields\Search\Response
     */
    public function send()
    {
        return parent::send();
    }

    /**
     * @inheritDoc
     * @return \SmartEmailing\v3\Request\CustomFields\Search\Response
     */
    protected function createResponse($response)
    {
        return new Response($response);
    }

    /**
     * Sets the value into array if not valid
     *
     * @param array  $array
     * @param string $key
     * @param string $value
     *
     * @return $this
     */
    protected function setIfNotNull(array &$array, $key, $value)
    {
        if (is_null($value)) {
            return $this;
        }

        $array[$key] = $value;
        return $this;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>de.ztube.yuno.gui</title>
<meta name="date" content="2017-08-02">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package de.ztube.yuno.gui

Class Summary

Class
Description

Controls

The Class handling the touchpad's input

GUI

The whole GUI handling the touchpad and the HeartContainer

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
<?php

namespace Seo\Bundle\UserBundle\Twig;

use Twig_Extension;

class SeoExtension extends Twig_Extension
{
    public function getFunctions()
    {
        return array(
            'alertkey' => new \Twig_Function_Method($this,'alertKey'),
        );
    }

    public function alertKey($key)
    {
        return str_replace('fos_user_','',$key);
    }

    public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
    {
        $price = number_format($number, $decimals, $decPoint, $thousandsSep);
        $price = '$' . $price;

        return $price;
    }

    public function getName()
    {
        return 'seo_extension';
    }
}


text:
"""
Violin 7000 Series All-Flash Array iSCSI Volume Driver

Provides ISCSI specific LUN services for V7000 series flash arrays.

This driver requires Concerto v7.5.4 or newer software on the array.

You will need to install the python VMEM REST client:
sudo pip install vmemclient

Set the following in the cinder.conf file to enable the VMEM V7000
ISCSI Driver along with the required flags:

volume_driver=cinder.volume.drivers.violin.v7000_iscsi.V7000ISCSIDriver
"""

import random
import uuid

from oslo_log import log as logging

from cinder import exception
from cinder.i18n import _
from cinder import interface
from cinder.volume import driver
from cinder.volume.drivers.san import san
from cinder.volume.drivers.violin import v7000_common

LOG = logging.getLogger(__name__)

@interface.volumedriver
class V7000ISCSIDriver(driver.ISCSIDriver):
    """Executes commands relating to iscsi based Violin Memory arrays.

    Version history:
        1.0 - Initial driver
    """

    VERSION = '1.0'

    # ThirdPartySystems wiki page
    CI_WIKI_NAME = "Violin_Memory_CI"

    # TODO(smcginnis) Either remove this if CI requirements are met, or
    # remove this driver in the Queens release per normal deprecation
    SUPPORTED = False

    def __init__(self, *args, **kwargs):
        super(V7000ISCSIDriver, self).__init__(*args, **kwargs)
        self.stats = {}
        self.gateway_iscsi_ip_addresses = []
        self.configuration.append_config_values(v7000_common.violin_opts)
        self.configuration.append_config_values(san.san_opts)
        self.common = v7000_common.V7000Common(self.configuration)

        LOG.info("Initialized driver %(name)s version: %(vers)s",
                 {'name': self.__class__.__name__, 'vers': self.VERSION})

    def do_setup(self, context):
        """Any initialization the driver does while starting."""
        super(V7000ISCSIDriver, self).do_setup(context)

        self.common.do_setup(context)

        # Register the client with the storage array
        iscsi_version = self.VERSION + "-ISCSI"
        self.common.vmem_mg.utility.set_managed_by_openstack_version(
            iscsi_version, protocol="iSCSI")

        # Getting iscsi IPs from the array is incredibly expensive,
        # so only do it once.
        if not self.configuration.violin_iscsi_target_ips:
            LOG.warning("iSCSI target ip addresses not configured.")
            self.gateway_iscsi_ip_addresses = (
                self.common.vmem_mg.utility.get_iscsi_interfaces())
        else:
            self.gateway_iscsi_ip_addresses = (
                self.configuration.violin_iscsi_target_ips)

    def check_for_setup_error(self):
        """Returns an error if prerequisites aren't met."""
        self.common.check_for_setup_error()
        if len(self.gateway_iscsi_ip_addresses) == 0:
            msg = _('No iSCSI IPs configured on SAN gateway')
            raise exception.ViolinInvalidBackendConfig(reason=msg)

    def create_volume(self, volume):
        """Creates a volume."""
        self.common._create_lun(volume)

    def create_volume_from_snapshot(self, volume, snapshot):
        """Creates a volume from a snapshot."""
        self.common._create_volume_from_snapshot(snapshot, volume)

    def create_cloned_volume(self, volume, src_vref):
        """Creates a clone of the specified volume."""
        self.common._create_lun_from_lun(src_vref, volume)

    def delete_volume(self, volume):
        """Deletes a volume."""
        self.common._delete_lun(volume)

    def extend_volume(self, volume, new_size):
        """Extend an existing volume's size."""
        self.common._extend_lun(volume, new_size)

    def create_snapshot(self, snapshot):
        """Creates a snapshot."""
        self.common._create_lun_snapshot(snapshot)

    def delete_snapshot(self, snapshot):
        """Deletes a snapshot."""
        self.common._delete_lun_snapshot(snapshot)

    def ensure_export(self, context, volume):
        """Synchronously checks and re-exports volumes at cinder start time."""
        pass

    def create_export(self, context, volume, connector):
        """Exports the volume."""
        pass

    def remove_export(self, context, volume):
        """Removes an export for a logical volume."""
        pass

    def initialize_connection(self, volume, connector):
        """Allow connection to connector and return connection info."""
        resp = {}

        LOG.debug("Initialize_connection: initiator - %(initiator)s  host - "
                  "%(host)s ip - %(ip)s",
                  {'initiator': connector['initiator'],
                   'host': connector['host'],
                   'ip': connector['ip']})

        iqn = self._get_iqn(connector)

        # pick a random single target to give the connector since
        # there is no multipathing support
        tgt = self.gateway_iscsi_ip_addresses[random.randint(
            0, len(self.gateway_iscsi_ip_addresses) - 1)]

        resp = self.common.vmem_mg.client.create_client(
            name=connector['host'], proto='iSCSI',
            iscsi_iqns=connector['initiator'])

        # raise if we failed for any reason other than a 'client
        # already exists' error code
        if not resp['success'] and 'Error: 0x900100cd' not in resp['msg']:
            msg = _("Failed to create iscsi client")
            raise exception.ViolinBackendErr(message=msg)

        resp = self.common.vmem_mg.client.create_iscsi_target(
            name=iqn, client_name=connector['host'],
            ip=self.gateway_iscsi_ip_addresses, access_mode='ReadWrite')

        # same here, raise for any failure other than a 'target
        # already exists' error code
        if not resp['success'] and 'Error: 0x09024309' not in resp['msg']:
            msg = _("Failed to create iscsi target")
            raise exception.ViolinBackendErr(message=msg)

        lun_id = self._export_lun(volume, iqn, connector)

        properties = {}
        properties['target_discovered'] = False
        properties['target_iqn'] = iqn
        properties['target_portal'] = '%s:%s' % (tgt, '3260')
        properties['target_lun'] = lun_id
        properties['volume_id'] = volume['id']

        LOG.debug("Return ISCSI data: %(properties)s.",
                  {'properties': properties})

        return {'driver_volume_type': 'iscsi', 'data': properties}

    def terminate_connection(self, volume, connector, **kwargs):
        """Terminates the connection (target<-->initiator)."""
        iqn = self._get_iqn(connector)
        self._unexport_lun(volume, iqn, connector)

    def get_volume_stats(self, refresh=False):
        """Get volume stats.

        If 'refresh' is True, update the stats first.
        """
        if refresh or not self.stats:
            self._update_volume_stats()
        return self.stats

    def _update_volume_stats(self):
        """Gathers array stats and converts them to GB values."""
        data = self.common._get_volume_stats(self.configuration.san_ip)

        backend_name = self.configuration.volume_backend_name
        data['volume_backend_name'] = backend_name or self.__class__.__name__
        data['driver_version'] = self.VERSION
        data['storage_protocol'] = 'iSCSI'
        for i in data:
            LOG.debug("stat update: %(name)s=%(data)s",
                      {'name': i, 'data': data[i]})

        self.stats = data

    def _export_lun(self, volume, target, connector):
        """Generates the export configuration for the given volume.

        :param volume:  volume object provided by the Manager
        :param connector:  connector object provided by the Manager
        :returns: the LUN ID assigned by the backend
        """
        lun_id = ''
        v = self.common.vmem_mg

        LOG.debug("Exporting lun %(vol_id)s - initiator iqns %(i_iqns)s "
                  "- target iqns %(t_iqns)s.",
                  {'vol_id': volume['id'], 'i_iqns': connector['initiator'],
                   't_iqns': self.gateway_iscsi_ip_addresses})

        try:
            lun_id = self.common._send_cmd_and_verify(
                v.lun.assign_lun_to_iscsi_target,
                self._is_lun_id_ready,
                "Assign device successfully",
                [volume['id'], target],
                [volume['id'], connector['host']])

        except exception.ViolinBackendErr:
            LOG.exception("Backend returned error for lun export.")
            raise

        except Exception:
            raise exception.ViolinInvalidBackendConfig(
                reason=_('LUN export failed!'))

        lun_id = self._get_lun_id(volume['id'], connector['host'])
        LOG.info("Exported lun %(vol_id)s on lun_id %(lun_id)s.",
                 {'vol_id': volume['id'], 'lun_id': lun_id})

        return lun_id

    def _unexport_lun(self, volume, target, connector):
        """Removes the export configuration for the given volume.

        The equivalent CLI command is "no lun export container
        <container_name> name <lun_name>"

        Arguments:
            volume -- volume object provided by the Manager
        """
        v = self.common.vmem_mg

        LOG.info("Unexporting lun %(vol)s host is %(host)s.",
                 {'vol': volume['id'], 'host': connector['host']})

        try:
            self.common._send_cmd(v.lun.unassign_lun_from_iscsi_target,
                                  "Unassign device successfully",
                                  volume['id'], target, True)

        except exception.ViolinBackendErrNotFound:
            LOG.info("Lun %s already unexported, continuing...",
                     volume['id'])

        except Exception:
            LOG.exception("LUN unexport failed!")
            msg = _("LUN unexport failed")
            raise exception.ViolinBackendErr(message=msg)

    def _is_lun_id_ready(self, volume_name, client_name):
        """Get the lun ID for an exported volume.

        If the lun is successfully assigned (exported) to a client, the
        client info has the lun_id.

        Note: The structure returned for iscsi is different from the
        one returned for FC. Therefore this function is here instead of
        common.

        Arguments:
            volume_name -- name of volume to query for lun ID
            client_name -- name of client associated with the volume

        Returns:
            lun_id -- Returns True or False
        """

        lun_id = -1
        lun_id = self._get_lun_id(volume_name, client_name)

        if lun_id is None:
            return False
        else:
            return True

    def _get_lun_id(self, volume_name, client_name):
        """Get the lun ID for an exported volume.

        If the lun is successfully assigned (exported) to a client, the
        client info has the lun_id.

        Note: The structure returned for iscsi is different from the
        one returned for FC. Therefore this function is here instead of
        common.

        Arguments:
            volume_name -- name of volume to query for lun ID
            client_name -- name of client associated with the volume

        Returns:
            lun_id -- integer value of lun ID
        """
        v = self.common.vmem_mg
        lun_id = None

        client_info = v.client.get_client_info(client_name)

        for x in client_info['ISCSIDevices']:
            if volume_name == x['name']:
                lun_id = x['lun']
                break

        if lun_id:
            lun_id = int(lun_id)

        return lun_id

    def _get_iqn(self, connector):
        # The vmemclient connection properties list hostname field may
        # change depending on failover cluster config.  Use a UUID
        # from the backend's IP address to avoid a potential naming
        # issue.
        host_uuid = uuid.uuid3(uuid.NAMESPACE_DNS, self.configuration.san_ip)
        return "%s%s.%s" % (self.configuration.iscsi_target_prefix,
                            connector['host'], host_uuid)


text:
author: slowe
categories: Explanation
comments: true
date: 2015-11-23T00:00:00Z
tags:
- Ansible
- Linux
- OpenStack
- CLI
- Ubuntu
title: Bootstrapping Cloud Instances into Ansible
url: /2015/11/23/bootstrapping-cloud-instances-ansible/
---

A while ago, I wrote an article about [bootstrapping servers into Ansible][xref-1]---in other words, how to prepare servers to be managed via [Ansible][link-1]. In order for a server to be managed via Ansible, you usually must first create a user account for Ansible, populate the appropriate SSH keys, and grant the new Ansible user sudo permissions. The process I described in my earlier blog post works great for manually-built servers (physical or virtual), but I recently needed to revisit this process for cloud instances. Was it possible to use the process I'd found to bootstrap cloud instances into Ansible?

Cloud instances are a slightly different beast than manually-built servers primarily because password authentication isn't an option---generally speaking, you're required to use SSH keys when working with cloud instances. Ansible is SSH-based, as you probably already know, so this _shouldn't_ be an issue, but it was still something I hadn't tested or verified. After a bit of testing, I found the bootstrap process I described in my earlier post can be easily adapted for cloud instances.

For reference, here's the command I use when bootstrapping manually-built servers into Ansible:

    ansible-playbook bootstrap.yml -k -K --extra-vars \
    "hosts=newhost.domain.com user=admin"

The `bootstrap.yml` playbook simply creates an Ansible user, populates the appropriate SSH keys, and sets `sudo` permissions. The playbook relies upon the variables passed on the command-line, which tell it what hosts should be affected and what user account (and password, via the `-k` and `-K` parameters) to use to modify the remote server.

With a cloud instance, this needed to change. First, you don't know the password; you're required to use an SSH key for authentication. You generally _do_ know the user account, but not the password. After a short bit of trial and error, I found the following command-line worked with a freshly-booted cloud instance:

    ansible-playbook bootstrap.yml --extra-vars \
    "hosts=172.16.6.7 user=ubuntu" --private-key=~/.ssh/cloudkey.pem

The command is largely the same, with two major changes:

* The `-k` and `-K` parameters are gone. The password is unknown, so there's no point in telling Ansible to prompt for any passwords.
* The `--private-key` parameter supplies the path and name of the SSH keypair (obtained from your cloud platform) that allow initial authentication to the new cloud instance.
* You'll note I omitted the `-i` parameter to specify an inventory file; this is because I created an `ansible.cfg` in this directory and specified the inventory file there. (It makes the command-line easier and simpler.)

As before, I use the `--extra-vars` parameter to supply the specific host being bootstrapped into Ansible as well as the name of the initial user account (in this case, I'm bootstrapping an Ubuntu cloud image, so the initial user is "ubuntu"). Once the initial bootstrap process completes successsfully, I can then run subsequent playbooks against this cloud instance with no further configuration or command-line parameters required.

[link-1]: http://www.ansible.com/
[xref-1]: {{< relref "2015-05-26-bootstrap-servers-ansible.md" >}}


text:
function initialize() {
	var classroom = new google.maps.LatLng(35.084280,-106.624073)
	var office = new google.maps.LatLng(35.084506,-106.624899)
	var myOptions = {
		zoom: 18,
		center: classroom,
		mapTypeId: google.maps.MapTypeId.HYBRID
		};
	var map = new google.maps.Map(
		document.getElementById("map_canvas"),
		myOptions);

	var classroomMarker = new google.maps.Marker({
		position: classroom,
		title:"Geography 485L/585L Classroom, Bandelier East, Room 106"
		});
	classroomMarker.setMap(map);

	var officeMarker = new google.maps.Marker({
		position: office,
		title:"Office, Bandelier West, Room 107"
		});
	officeMarker.setMap(map);
}


text:
'use strict';

angular.module('am.parkingSpots').controller('ParkingSpotsController', ['$scope', '$stateParams', '$location', 'Global', 'ParkingSpots', 'Residents',
    function ($scope, $stateParams, $location, Global, ParkingSpots, Residents) {
        $scope.global = Global;

        $scope.populateResidents = function (query) {
            Residents.query(query, function (residents) {
                $scope.residents = residents;
            });
        };

        $scope.create = function () {
            var parkingSpot = new ParkingSpots({
                parkingSpotId: this.parkingSpot.parkingSpotId,
                occupied: this.parkingSpot.occupied,
                occupiedSinceDate: this.parkingSpot.occupiedSinceDate
            });

            parkingSpot.$save(function (response) {
                $location.path('parkingspots/' + response._id);
            });

            this.parkingSpot.parkingSpotId = '';
            this.parkingSpot.occupied = false;
            this.parkingSpot.occupiedSinceDate = '';
        };

        $scope.update = function () {
            var parkingSpot = $scope.parkingSpot;

            parkingSpot.$update(function () {
                $location.path('parkingspots/' + parkingSpot._id);
            });
        };

        $scope.find = function (query) {
            ParkingSpots.query(query, function (parkingSpots) {
                $scope.parkingSpots = parkingSpots;
            });
        };

        $scope.findOne = function () {
            ParkingSpots.get({parkingSpotId: $stateParams.parkingSpotId}, function (parkingSpot) {
                $scope.parkingSpot = parkingSpot;
            });
        };

        $scope.remove = function (parkingSpot) {
            parkingSpot.$remove();
            for (var i in $scope.parkingSpots) {
                if ($scope.parkingSpots[i] === parkingSpot) {
                    $scope.parkingSpots.splice(i, 1);
                }
            }
        };

        $scope.toggleDatePicker = function($event, target) {
            $event.preventDefault();
            $event.stopPropagation();

            $scope[target] = !$scope[target];
        };
    }]);


text:
import sys
import re
import os
import tempfile
import shutil
import subprocess
import urllib
from string import Template
from collections import defaultdict
import boto3
from zfile import zfile

# File categories
categories = ['dynamic', # dynamic libraries
              'static',  # static libraries
              'pc',      # pkg-config
              'include'] # include files / headers

win_ver = 'win7'
# Maps platform and category to expected files, or vice versa.
wanted_files = {
    win_ver: {
        'dynamic': ['librdkafka.dll', 'librdkafkacpp.dll',
                    'librdkafka.lib', 'librdkafkacpp.lib',
                    'msvcr120.dll', 'zlib.dll'],
        'static': ['librdkafka.lib', 'librdkafkacpp.lib'],
        'include': ['rdkafka.h', 'rdkafkacpp.h'],
    },

    'osx': {
        'dynamic': ['librdkafka.dylib', 'librdkafka++.dylib'],
        'static': ['librdkafka.a', 'librdkafka++.a'],
        'include': ['rdkafka.h', 'rdkafkacpp.h'],
        'pc': ['rdkafka.pc', 'rdkafka++.pc'],
    },

    'debian': {
        'dynamic': ['librdkafka.so.1', 'librdkafka++.so.1'],
        'static': ['librdkafka.a', 'librdkafka++.a'],
        'include': ['rdkafka.h', 'rdkafkacpp.h'],
        'pc': ['rdkafka.pc', 'rdkafka++.pc'],
    },

    'rhel':  {
        'dynamic': ['librdkafka.so.1', 'librdkafka++.so.1'],
        'static': ['librdkafka.a', 'librdkafka++.a'],
        'include': ['rdkafka.h', 'rdkafkacpp.h'],
        'pc': ['rdkafka.pc', 'rdkafka++.pc'],
    }
}

# Supported platforms
platforms = wanted_files.keys()

# Default documents to include in all packages
default_doc = ['../../README.md',
               '../../CONFIGURATION.md',
               '../../LICENSES.txt']

# Rename matching files
rename_files = {'librdkafka.so.1': 'librdkafka.so',
                'librdkafka++.so.1': 'librdkafka++.so'}

# Rename token values
rename_vals = {'plat': {'linux': 'debian',
                        'windows': win_ver},
               'arch': {'x86_64': 'x64',
                        'i386': 'x86',
                        'win32': 'x86'}}

# Collects CI artifacts from S3 storage, downloading them
# to a local directory, or collecting already downloaded artifacts from
# local directory.
#
# The artifacts' folder in the S3 bucket must have the following token
# format:
#  <token>-[<value>]__   (repeat)
#
# Recognized tokens (unrecognized tokens are ignored):
#  p       - project (e.g., "confluent-kafka-python")
#  bld     - builder (e.g., "travis")
#  plat    - platform ("osx", "linux", ..)
#  arch    - arch ("x64", ..)
#  tag     - git tag
#  sha     - git sha
#  bid     - builder's build-id
#  bldtype - Release, Debug (appveyor)
#
# Example:
#   librdkafka/p-librdkafka__bld-travis__plat-linux__arch-x64__tag-v0.0.62__sha-d051b2c19eb0c118991cd8bc5cf86d8e5e446cde__bid-1562.1/librdkafka.tar.gz

s3_bucket = 'librdkafka-ci-packages'
dry_run = False

class Artifact (object):
    def __init__(self, arts, path, info=None):
        self.path = path
        # Remove unexpanded AppVeyor $(..) tokens from filename
        self.fname = re.sub(r'\$\([^\)]+\)', '', os.path.basename(path))
        slpath = os.path.join(os.path.dirname(path), self.fname)
        if os.path.isfile(slpath):
            # Already points to local file in correct location
            self.lpath = slpath
        else:
            # Prepare download location in dlpath
            self.lpath = os.path.join(arts.dlpath, slpath)

        if info is None:
            self.info = dict()
        else:
            # Assign the map and convert all keys to lower case
            self.info = {k.lower(): v for k, v in info.items()}
            # Rename values, e.g., 'plat':'linux' to 'plat':'debian'
            for k,v in self.info.items():
                rdict = rename_vals.get(k, None)
                if rdict is not None:
                    self.info[k] = rdict.get(v, v)

        # Score value for sorting
        self.score = 0

        # AppVeyor symbol builds are of less value
        if self.fname.find('.symbols.') != -1:
            self.score -= 10

        self.arts = arts
        arts.artifacts.append(self)

    def __repr__(self):
        return self.path

    def __lt__ (self, other):
        return self.score < other.score

    def download(self):
        """ Download artifact from S3 and store in local directory .lpath.
            If the artifact is already downloaded nothing is done. """
        if os.path.isfile(self.lpath) and os.path.getsize(self.lpath) > 0:
            return
        print('Downloading %s' % self.path)
        if dry_run:
            return
        ldir = os.path.dirname(self.lpath)
        if not os.path.isdir(ldir):
            os.makedirs(ldir, 0o755)
        self.arts.s3_bucket.download_file(self.path, self.lpath)

class Artifacts (object):
    def __init__(self, match, dlpath):
        super(Artifacts, self).__init__()
        self.match = match
        self.artifacts = list()
        # Download directory (make sure it ends with a path separator)
        if not dlpath.endswith(os.path.sep):
            dlpath = os.path.join(dlpath, '')
        self.dlpath = dlpath
        if not os.path.isdir(self.dlpath):
            if not dry_run:
                os.makedirs(self.dlpath, 0o755)

    def collect_single(self, path, req_tag=True):
        """ Collect single artifact, be it in S3 or locally.
        :param: path string: S3 or local (relative) path
        :param: req_tag bool: Require tag to match.
        """

        #print('?  %s' % path)

        # For local files, strip download path.
        # Also ignore any parent directories.
        if path.startswith(self.dlpath):
            folder = os.path.basename(os.path.dirname(path[len(self.dlpath):]))
        else:
            folder = os.path.basename(os.path.dirname(path))

        # The folder contains the tokens needed to perform
        # matching of project, gitref, etc.
        rinfo = re.findall(r'(?P<tag>[^-]+)-(?P<val>.*?)__', folder)
        if rinfo is None or len(rinfo) == 0:
            print('Incorrect folder/file name format for %s' % folder)
            return None

        info = dict(rinfo)

        # Ignore AppVeyor Debug builds
        if info.get('bldtype', '').lower() == 'debug':
            print('Ignoring debug artifact %s' % folder)
            return None

        tag = info.get('tag', None)
        if tag is not None and (len(tag) == 0 or tag.startswith('$(')):
            # AppVeyor doesn't substite $(APPVEYOR_REPO_TAG_NAME)
            # with an empty value when not set, it leaves that token
            # in the string - so translate that to no tag.
            del info['tag']

        # Perform matching
        unmatched = list()
        for m,v in self.match.items():
            if m not in info or info[m] != v:
                unmatched.append(m)

        # Make sure all matches were satisfied, unless this is a
        # common artifact.
        if info.get('p', '') != 'common' and len(unmatched) > 0:
            # print('%s: %s did not match %s' % (info.get('p', None), folder, unmatched))
            return None

        return Artifact(self, path, info)

    def collect_s3(self):
        """ Collect and download build-artifacts from S3 based on git reference """
        print('Collecting artifacts matching %s from S3 bucket %s' % (self.match, s3_bucket))
        self.s3 = boto3.resource('s3')
        self.s3_bucket = self.s3.Bucket(s3_bucket)
        self.s3_client = boto3.client('s3')
        for item in self.s3_client.list_objects(Bucket=s3_bucket, Prefix='librdkafka/').get('Contents'):
            self.collect_single(item.get('Key'))

        for a in self.artifacts:
            a.download()

    def collect_local(self, path, req_tag=True):
        """ Collect artifacts from a local directory possibly previously
        collected from s3 """
        for f in [os.path.join(dp, f) for dp, dn, filenames in os.walk(path) for f in filenames]:
            if not os.path.isfile(f):
                continue
            self.collect_single(f, req_tag)

class Package (object):
    """ Generic Package class
        A Package is a working container for one or more output
        packages for a specific package type (e.g., nuget) """

    def __init__ (self, version, arts, ptype):
        super(Package, self).__init__()
        self.version = version
        self.arts = arts
        self.ptype = ptype
        # These may be overwritten by specific sub-classes:
        self.artifacts = arts.artifacts
        self.platforms = platforms
        # Staging path, filled in later.
        self.stpath = None
        self.kv = {'version': version}
        self.files = dict()

    def add_file (self, file):
        self.files[file] = True

    def categorize (self):
        """ Categorize and arrange a Package's artifacts according to
            its platforms.
            Returns a fout map:
              category: [(artifact,file)]
        """

        fout = defaultdict(list)

        # Flat lists of files to collect keyed by platform,category
        collect_files = dict()
        for platform in wanted_files:
            for category, flist in wanted_files[platform].items():
                for f in flist:
                    collect_files[(platform,category,f)] = list()

        for a in self.artifacts:
            try:
                with zfile.ZFile(a.lpath, 'r') as zf:
                    if os.path.splitext(a.lpath)[-1] == '.rpm':
                        a.info['plat'] = 'rhel'

                    platform = a.info['plat']
                    if platform not in platforms:
                        continue

                    zfiles = zf.getnames()
                    if len(zfiles) == 0:
                        print('No files in %s?' % a)
                    for category, flist in wanted_files[platform].items():
                        for f in flist:
                            matches = [(a,x) for x in zfiles if os.path.basename(x) == f]
                            if len(matches) > 0:
                                collect_files[(platform,category,f)] += matches
                                fout[category] += matches

            except zfile.tarfile.ReadError as e:
                print('ignoring artifact: %s: %s' % (a.lpath, str(e)))

        # Verify that all wanted combinations were matched
        errors = 0
        for missing in [x for x in collect_files if len(collect_files[x]) == 0]:
            errors += 1
            print('ERROR: No matching artifact files for', missing)

        if errors > 0:
            raise Exception('Not all wanted files found in artifacts, see above.')
        return fout

    def layout (self, lydef):
        """
        Layout categorized files according to provided
        layout definition \p lydef.

        Returns a layout dict containing the matched artifacts.
        """

        # Categorize files
        fout = self.categorize()

        ly = defaultdict(list)

        # For each template path, attempt to map all files in that category
        # and add any files that renders completely to the layout.
        for tmplsrc, category in lydef.items():
             tmpl = Template(tmplsrc)
             for a, f in fout[category]:
                 # print('%s: Try %s matched to %s in %s' % (category, tmplsrc, f, a))
                 try:
                     path = os.path.join(tmpl.substitute(a.info),
                                         os.path.basename(f))
                     ly[path].append((a, f))
                 except KeyError as e:
                     print(' -- %s info key %s not found' % (a, e))
                     pass

        # Sort providing sources for each path.
        # E.g., prefer .redist. before .symbols., etc.
        for path in ly:
            ly[path].sort(reverse=True)

        return ly

    def build (self):
        """ Build package output(s), return a list of paths to built packages """
        raise NotImplementedError

    def cleanup (self):
        """ Optional cleanup routine for removing temporary files, etc. """
        pass

    def verify (self, path):
        """ Optional post-build package verifier """
        pass

    def render (self, fname, destpath='.'):
        """ Render template in file fname and save to destpath/fname,
        where destpath is relative to stpath """

        outf = os.path.join(self.stpath, destpath, fname)

        if not os.path.isdir(os.path.dirname(outf)):
            os.makedirs(os.path.dirname(outf), 0o0755)

        with open(os.path.join('templates', fname), 'r') as tf:
            tmpl = Template(tf.read())
        with open(outf, 'w') as of:
            of.write(tmpl.substitute(self.kv))

        self.add_file(outf)

    def copy_template (self, fname, target_fname=None, destpath='.'):
        """ Copy template file to destpath/fname
        where destpath is relative to stpath """

        if target_fname is None:
            target_fname = fname
        outf = os.path.join(self.stpath, destpath, target_fname)

        if not os.path.isdir(os.path.dirname(outf)):
            os.makedirs(os.path.dirname(outf), 0o0755)

        shutil.copy(os.path.join('templates', fname), outf)

        self.add_file(outf)

    def extract_artifacts (self, layout):
        """ Extract members from artifacts into staging path """
        print('Extracting artifacts according to layout:')
        for path, afs in layout.items():
            artifact = afs[0][0]
            member = afs[0][1]
            print('  %s (from %s) -> %s' % (member, artifact, path))
            outf = os.path.join(self.stpath, path)
            zfile.ZFile.extract(artifact.lpath, member, outf)

            self.add_file(outf)

        # Rename files, if needed.
        for root, _, filenames in os.walk(self.stpath):
            for filename in filenames:
                fname = os.path.basename(filename)
                if fname in rename_files:
                    bpath = os.path.join(root, os.path.dirname(filename))
                    oldfile = os.path.join(bpath, fname)
                    newfile = os.path.join(bpath, rename_files[fname])
                    print('Renaming %s -> %s' % (oldfile, newfile))
                    os.rename(oldfile, newfile)

        # And rename them in the files map too
        rename_these = [x for x in self.files.keys() if os.path.basename(x) in rename_files]
        for oldfile in rename_these:
            newfile = os.path.join(os.path.dirname(oldfile),
                                   rename_files[os.path.basename(oldfile)])
            self.files[newfile] = self.files[oldfile]
            del self.files[oldfile]

class NugetPackage (Package):
    """ All platforms, archs, et.al, are bundled into one set of
        NuGet output packages: "main", redist and symbols """
    def __init__ (self, version, arts):
        if version.startswith('v'):
            version = version[1:] # Strip v prefix
        super(NugetPackage, self).__init__(version, arts, "nuget")

    def cleanup(self):
        if os.path.isdir(self.stpath):
            shutil.rmtree(self.stpath)

    def build (self, buildtype):
        """ Build single NuGet package for all its artifacts. """
        layout = self.xlayout()

        # NuGet removes the prefixing v from the version.
        vless_version = self.kv['version']
        if vless_version[0] == 'v':
            vless_version = vless_version[1:]

        self.stpath = tempfile.mkdtemp(prefix="out-", suffix="-%s" % buildtype,
                                       dir=".")

        self.render('librdkafka.redist.nuspec')
        self.copy_template('librdkafka.redist.targets',
                           destpath=os.path.join('build', 'native'))
        self.copy_template('librdkafka.redist.props',
                           destpath=os.path.join('build', 'native'))
        self.copy_template('librdkafka.redist.props',
                           destpath=os.path.join('build', 'net'))
        for f in default_doc:
            shutil.copy(f, self.stpath)

        self.extract_artifacts(layout)

        print('Tree extracted to %s' % self.stpath)

        # After creating a bare-bone nupkg layout containing the artifacts
        # and some spec and props files, call the 'nuget' utility to
        # make a proper nupkg of it (with all the metadata files).
        subprocess.check_call("./nuget.sh pack %s -BasePath '%s' -NonInteractive" %  \
                              (os.path.join(self.stpath, 'librdkafka.redist.nuspec'),
                               self.stpath), shell=True)
        return ['librdkafka.redist.%s.nupkg' % vless_version]

    def xlayout (self):
        """ Copy files from artifact nupkgs to new super-layout

            Buildtype: release, debug

            High-level requirements:
             * provide build artifacts: -> build/
               - static libraries
               - header files
               - layout:
                  build/native/librdkafka.targets
                  build/native/lib/<plat>/<arch>/<variant>/<toolset>/{static}
                  build/native/include/librdkafka/*.h

             * provide runtime artifacts: -> runtimes/
               - dynamic libraries
               - possibly symbol files
               - layout:
                  runtimes/<plat>-<arch>/native/{dynamic}
             * both cases:
               - docs -> ./

            runtimes from https://github.com/dotnet/corefx/blob/master/pkg/Microsoft.NETCore.Platforms/runtime.json
            * win7-x86
            * win7-x64
            * osx
            * osx-x64
            * debian-x64
            * rhel-x64  (rhel.7)

            This gives the following layout:
            build/native/include/librdkafka/rdkafka.h..
            build/native/net/librdkafka.redist.props

        """

        # Generate template tokens for artifacts
        for a in self.arts.artifacts:
            if 'bldtype' not in a.info:
                a.info['bldtype'] = 'release'

            a.info['variant'] = '%s-%s-%s' % (a.info.get('plat'),
                                              a.info.get('arch'),
                                              a.info.get('bldtype'))
            if 'toolset' not in a.info:
                a.info['toolset'] = 'v120'

        nuget_layout = {
            # Build
            'build/native/lib/${plat}/${arch}/${variant}/${toolset}/': 'static',
            'build/native/include/librdkafka/': 'include',

            # Runtime
            'runtimes/${plat}-${arch}/native/': 'dynamic',

            # All
            'content/docs/': 'doc'
        }

        layout = self.layout(nuget_layout)

        errors = 0
        print(' %s layout:' % self)
        for path, afs in layout.items():
            print('  %s provided by:' % path)
            for a, f in afs:
                print('    %s from artifact %s (and %d more)' % (f, a.fname, len(afs)-1))
                break
            if len(afs) == 0:
                print('     ERROR: no artifacts found')
                errors += 1
        print('')

        if errors > 0:
            raise Exception('Layout not satisfied by collected artifacts: %d missing' % errors)

        return layout

    def verify (self, path):
        """ Verify package """
        expect = ["librdkafka.redist.nuspec",
                  "LICENSES.txt",
                  "build/native/librdkafka.redist.props",
                  "build/native/librdkafka.redist.targets",
                  "build/native/include/librdkafka/rdkafka.h",
                  "build/native/include/librdkafka/rdkafkacpp.h",
                  "build/net/librdkafka.redist.props",
                  "runtimes/win7-x86/native/librdkafka.dll",
                  "runtimes/win7-x86/native/librdkafka.lib",
                  "runtimes/win7-x86/native/zlib.dll",
                  "runtimes/win7-x86/native/msvcr120.dll",
                  "runtimes/win7-x64/native/librdkafka.dll",
                  "runtimes/win7-x64/native/librdkafka.lib",
                  "runtimes/win7-x64/native/msvcr120.dll",
                  "runtimes/osx-x64/native/librdkafka++.dylib",
                  "runtimes/osx-x64/native/librdkafka.dylib",
                  "runtimes/debian-x64/native/librdkafka++.so",
                  "runtimes/debian-x64/native/librdkafka.so",
                  "runtimes/rhel-x64/native/librdkafka++.so",
                  "runtimes/rhel-x64/native/librdkafka.so"]
        missing = list()
        with zfile.ZFile(path, 'r') as zf:
            print('Verifying %s:' % path)

            # Zipfiles may url-encode filenames, unquote them before matching.
            pkgd = [urllib.unquote(x) for x in zf.getnames()]
            missing = [x for x in expect if x not in pkgd]

        if len(missing) > 0:
            print('Missing files in package %s:\n%s' % (path, '\n'.join(missing)))
            return False
        else:
            print('OK - %d expected files found' % expect)
            return True


text:
<?php

// $Id$

class XMLHelper {
	/**
	 * Take an XML node and generate a nested array.
	 * @param $xmlNode DOMDocument
	 * @param $keepEmpty boolean whether to keep empty elements, default: false
	 * @return mixed
	 */
	function &xmlToArray(&$xmlNode, $keepEmpty = false) {
		// Loop through all child nodes of the xml node.
		$resultArray = array();
		foreach ($xmlNode->childNodes as $childNode) {
			if ($childNode->nodeType == 1) {
				$childNodes =& $childNode->childNodes;
				if ($childNodes->length > 1) {
					// Recurse
					$resultArray[$childNode->nodeName] = $this->xmlToArray($childNode);
				} elseif ( ($childNode->nodeValue == '' && $keepEmpty) || ($childNode->nodeValue != '') ) {
					if (isset($resultArray[$childNode->nodeName])) {
						if (!is_array($resultArray[$childNode->nodeName])) {
							// We got a second value with the same key,
							// let's convert this element into an array.
							$resultArray[$childNode->nodeName] = array($resultArray[$childNode->nodeName]);
						}

						// Add the child node to the result array
						$resultArray[$childNode->nodeName][] = $childNode->nodeValue;
					} else {
						// This key occurs for the first time so
						// set it as a scalar value.
						$resultArray[$childNode->nodeName] = $childNode->nodeValue;
					}
				}
				unset($childNodes);
			}
		}

		return $resultArray;
	}
}

?>


text:
@interface KeyDocument : NSPersistentDocument
@end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Stud. Mycol. 9: 17 (1975)

#### Original name
Dothidea examinans Mont. & Berk., 1844

### Remarks
null


text:
package com.kancolle.server.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Package: com.kancolle.server.config
 * Author: mac
 * Date: 16/8/8
 */
@Configuration
public class Const {

    @Bean(name = "useItemIds")
    public int[] createUseItemIds() {
        return new int[]{10, 11, 12, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63};
    }

    @Bean(name = "equip_exslot")
    public int[] equip_exslot() {
        return new int[]{23, 43, 44};
    }
}


text:
require 'redmine_sympa/actions'

module RedmineSympa
  module Patches
    module EnabledModulePatch
      def self.included(base)
        base.send(:include, InstanceMethods)
        base.class_eval do
          unloadable # Send unloadable so it will not be unloaded in development

          after_create :sympa_enable_module
          before_destroy :sympa_disable_module
        end
      end

      module InstanceMethods
        def is_a_sympa_module?
          return (self.name == 'sympa_mailing_list' ? true : false)
        end

        def sympa_enable_module
          self.reload
          if(project && self.is_a_sympa_module?)
            RedmineSympa::SympaLogger.info("EnabledModule: Project #{project.identifier} needs a new mailing list. We must registers all its users, too.")
            RedmineSympa::Actions.create_list(project)
          end
        end

        def sympa_disable_module
          if(project && self.is_a_sympa_module?)
            RedmineSympa::SympaLogger.info("EnabledModule: Project #{project.identifier} doesn't need a mailing list any more")
            RedmineSympa::Actions.destroy_list(project)
          end
        end
      end
    end
  end
end


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="ca.ualberta.cs.xpertsapp.views.FriendServiceDetailsActivity">

</menu>


text:
echo "Begin download yml"
echo "tumama"


text: puts args.inspect