text:
using content::HostZoomMap;
using content::UserMetricsAction;
using content::WebContents;

////////////////////////////////////////////////////////////////////////////////
// EncodingMenuModel

EncodingMenuModel::EncodingMenuModel(Browser* browser)
    : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
      browser_(browser) {
  Build();
}

EncodingMenuModel::~EncodingMenuModel() {
}

void EncodingMenuModel::Build() {
  EncodingMenuController::EncodingMenuItemList encoding_menu_items;
  EncodingMenuController encoding_menu_controller;
  encoding_menu_controller.GetEncodingMenuItems(browser_->profile(),
                                                &encoding_menu_items);

  int group_id = 0;
  EncodingMenuController::EncodingMenuItemList::iterator it =
      encoding_menu_items.begin();
  for (; it != encoding_menu_items.end(); ++it) {
    int id = it->first;
    string16& label = it->second;
    if (id == 0) {
      AddSeparator();
    } else {
      if (id == IDC_ENCODING_AUTO_DETECT) {
        AddCheckItem(id, label);
      } else {
        // Use the id of the first radio command as the id of the group.
        if (group_id <= 0)
          group_id = id;
        AddRadioItem(id, label, group_id);
      }
    }
  }
}

bool EncodingMenuModel::IsCommandIdChecked(int command_id) const {
  WebContents* current_tab = browser_->GetSelectedWebContents();
  if (!current_tab)
    return false;
  EncodingMenuController controller;
  return controller.IsItemChecked(browser_->profile(),
                                  current_tab->GetEncoding(), command_id);
}

bool EncodingMenuModel::IsCommandIdEnabled(int command_id) const {
  bool enabled = browser_->command_updater()->IsCommandEnabled(command_id);
  // Special handling for the contents of the Encoding submenu. On Mac OS,
  // instead of enabling/disabling the top-level menu item, the submenu's
  // contents get disabled, per Apple's HIG.
#if defined(OS_MACOSX)
  enabled &= browser_->command_updater()->IsCommandEnabled(IDC_ENCODING_MENU);
#endif
  return enabled;
}

bool EncodingMenuModel::GetAcceleratorForCommandId(
    int command_id,
    ui::Accelerator* accelerator) {
  return false;
}

void EncodingMenuModel::ExecuteCommand(int command_id) {
  browser_->ExecuteCommand(command_id);
}

////////////////////////////////////////////////////////////////////////////////
// ZoomMenuModel

ZoomMenuModel::ZoomMenuModel(ui::SimpleMenuModel::Delegate* delegate)
    : SimpleMenuModel(delegate) {
  Build();
}

ZoomMenuModel::~ZoomMenuModel() {
}

void ZoomMenuModel::Build() {
  AddItemWithStringId(IDC_ZOOM_PLUS, IDS_ZOOM_PLUS);
  AddItemWithStringId(IDC_ZOOM_NORMAL, IDS_ZOOM_NORMAL);
  AddItemWithStringId(IDC_ZOOM_MINUS, IDS_ZOOM_MINUS);
}

////////////////////////////////////////////////////////////////////////////////
// ToolsMenuModel

ToolsMenuModel::ToolsMenuModel(ui::SimpleMenuModel::Delegate* delegate,
                               Browser* browser)
    : SimpleMenuModel(delegate) {
  Build(browser);
}

ToolsMenuModel::~ToolsMenuModel() {}

void ToolsMenuModel::Build(Browser* browser) {
#if !defined(OS_CHROMEOS) && !defined(OS_MACOSX)
  AddItemWithStringId(IDC_CREATE_SHORTCUTS, IDS_CREATE_SHORTCUTS);
  AddSeparator();
#endif

  AddItemWithStringId(IDC_MANAGE_EXTENSIONS, IDS_SHOW_EXTENSIONS);
#if defined(OS_CHROMEOS)
  AddItemWithStringId(IDC_FILE_MANAGER, IDS_FILE_MANAGER);
#endif
  AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER);
  AddItemWithStringId(IDC_CLEAR_BROWSING_DATA, IDS_CLEAR_BROWSING_DATA);

  AddSeparator();

#if !defined(OS_CHROMEOS)
  // Show IDC_FEEDBACK in "Tools" menu for non-ChromeOS platforms.
  AddItemWithStringId(IDC_FEEDBACK, IDS_FEEDBACK);
  AddSeparator();
#endif

  encoding_menu_model_.reset(new EncodingMenuModel(browser));
  AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU,
                         encoding_menu_model_.get());
  AddItemWithStringId(IDC_VIEW_SOURCE, IDS_VIEW_SOURCE);
  AddItemWithStringId(IDC_DEV_TOOLS, IDS_DEV_TOOLS);
  AddItemWithStringId(IDC_DEV_TOOLS_CONSOLE, IDS_DEV_TOOLS_CONSOLE);

#if defined(ENABLE_PROFILING) && !defined(NO_TCMALLOC)
  AddSeparator();
  AddCheckItemWithStringId(IDC_PROFILING_ENABLED, IDS_PROFILING_ENABLED);
#endif
}

////////////////////////////////////////////////////////////////////////////////
// WrenchMenuModel

WrenchMenuModel::WrenchMenuModel(ui::AcceleratorProvider* provider,
                                 Browser* browser)
    : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
      provider_(provider),
      browser_(browser),
      tabstrip_model_(browser_->tabstrip_model()) {
  Build();
  UpdateZoomControls();

  tabstrip_model_->AddObserver(this);

  registrar_.Add(
      this, content::NOTIFICATION_ZOOM_LEVEL_CHANGED,
      content::Source<HostZoomMap>(
          HostZoomMap::GetForBrowserContext(browser_->profile())));
  registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
                 content::NotificationService::AllSources());
}

WrenchMenuModel::~WrenchMenuModel() {
  if (tabstrip_model_)
    tabstrip_model_->RemoveObserver(this);
}

bool WrenchMenuModel::DoesCommandIdDismissMenu(int command_id) const {
  return command_id != IDC_ZOOM_MINUS && command_id != IDC_ZOOM_PLUS;
}

bool WrenchMenuModel::IsItemForCommandIdDynamic(int command_id) const {
  return command_id == IDC_ZOOM_PERCENT_DISPLAY ||
#if defined(OS_MACOSX)
         command_id == IDC_FULLSCREEN ||
#endif
         command_id == IDC_VIEW_BACKGROUND_PAGES ||
         command_id == IDC_UPGRADE_DIALOG ||
         command_id == IDC_SHOW_SYNC_SETUP;
}

string16 WrenchMenuModel::GetLabelForCommandId(int command_id) const {
  switch (command_id) {
    case IDC_ZOOM_PERCENT_DISPLAY:
      return zoom_label_;
#if defined(OS_MACOSX)
    case IDC_FULLSCREEN: {
      int string_id = IDS_ENTER_FULLSCREEN_MAC;  // Default to Enter.
      // Note: On startup, |window()| may be NULL.
      if (browser_->window() && browser_->window()->IsFullscreen())
        string_id = IDS_EXIT_FULLSCREEN_MAC;
      return l10n_util::GetStringUTF16(string_id);
    }
#endif
    case IDC_VIEW_BACKGROUND_PAGES: {
      string16 num_background_pages = base::FormatNumber(
          TaskManager::GetBackgroundPageCount());
      return l10n_util::GetStringFUTF16(IDS_VIEW_BACKGROUND_PAGES,
                                        num_background_pages);
    }
    case IDC_UPGRADE_DIALOG:
      return l10n_util::GetStringUTF16(IDS_UPDATE_NOW);
    case IDC_SHOW_SYNC_SETUP: {
      ProfileSyncService* service =
          ProfileSyncServiceFactory::GetInstance()->GetForProfile(
              browser_->GetProfile()->GetOriginalProfile());
      SyncGlobalError* error = service->sync_global_error();
      if (error && error->HasCustomizedSyncMenuItem())
        return error->MenuItemLabel();
      if (service->HasSyncSetupCompleted()) {
        std::string username = browser_->GetProfile()->GetPrefs()->GetString(
            prefs::kGoogleServicesUsername);
        if (!username.empty()) {
          return l10n_util::GetStringFUTF16(IDS_SYNC_MENU_SYNCED_LABEL,
                                            UTF8ToUTF16(username));
        }
      }
      return l10n_util::GetStringFUTF16(IDS_SYNC_MENU_PRE_SYNCED_LABEL,
          l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));
    }
    default:
      NOTREACHED();
      return string16();
  }
}

bool WrenchMenuModel::GetIconForCommandId(int command_id,
                                          SkBitmap* icon) const {
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  switch (command_id) {
    case IDC_UPGRADE_DIALOG: {
      if (UpgradeDetector::GetInstance()->notify_upgrade()) {
        *icon = *rb.GetNativeImageNamed(
            UpgradeDetector::GetInstance()->GetIconResourceID(
                UpgradeDetector::UPGRADE_ICON_TYPE_MENU_ICON)).ToSkBitmap();
        return true;
      }
      return false;
    }
    case IDC_SHOW_SYNC_SETUP: {
      ProfileSyncService* service =
          ProfileSyncServiceFactory::GetInstance()->GetForProfile(
              browser_->GetProfile()->GetOriginalProfile());
      SyncGlobalError* error = service->sync_global_error();
      if (error && error->HasCustomizedSyncMenuItem()) {
        int icon_id = error->MenuItemIconResourceID();
        if (icon_id) {
          *icon = *rb.GetNativeImageNamed(icon_id).ToSkBitmap();
          return true;
        }
      }
      return false;
    }
    default:
      break;
  }
  return false;
}

void WrenchMenuModel::ExecuteCommand(int command_id) {
  GlobalError* error = GlobalErrorServiceFactory::GetForProfile(
      browser_->profile())->GetGlobalErrorByMenuItemCommandID(command_id);
  if (error) {
    error->ExecuteMenuItem(browser_);
    return;
  }

  if (command_id == IDC_SHOW_SYNC_SETUP) {
    ProfileSyncService* service =
        ProfileSyncServiceFactory::GetInstance()->GetForProfile(
            browser_->GetProfile()->GetOriginalProfile());
    SyncGlobalError* error = service->sync_global_error();
    if (error && error->HasCustomizedSyncMenuItem()) {
      error->ExecuteMenuItem(browser_);
      return;
    }
  }

  if (command_id == IDC_HELP_PAGE)
    content::RecordAction(UserMetricsAction("ShowHelpTabViaWrenchMenu"));

  browser_->ExecuteCommand(command_id);
}

bool WrenchMenuModel::IsCommandIdChecked(int command_id) const {
  if (command_id == IDC_SHOW_BOOKMARK_BAR) {
    return browser_->profile()->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
  } else if (command_id == IDC_PROFILING_ENABLED) {
    return Profiling::BeingProfiled();
  }

  return false;
}

bool WrenchMenuModel::IsCommandIdEnabled(int command_id) const {
  GlobalError* error = GlobalErrorServiceFactory::GetForProfile(
      browser_->profile())->GetGlobalErrorByMenuItemCommandID(command_id);
  if (error)
    return true;

  return browser_->command_updater()->IsCommandEnabled(command_id);
}

bool WrenchMenuModel::IsCommandIdVisible(int command_id) const {
  if (command_id == IDC_UPGRADE_DIALOG) {
    return UpgradeDetector::GetInstance()->notify_upgrade();
  } else if (command_id == IDC_VIEW_INCOMPATIBILITIES) {
#if defined(OS_WIN)
    EnumerateModulesModel* loaded_modules =
        EnumerateModulesModel::GetInstance();
    if (loaded_modules->confirmed_bad_modules_detected() <= 0)
      return false;
    loaded_modules->AcknowledgeConflictNotification();
    return true;
#else
    return false;
#endif
  } else if (command_id == IDC_VIEW_BACKGROUND_PAGES) {
    return TaskManager::GetBackgroundPageCount() > 0;
  }
  return true;
}

bool WrenchMenuModel::GetAcceleratorForCommandId(
      int command_id,
      ui::Accelerator* accelerator) {
  return provider_->GetAcceleratorForCommandId(command_id, accelerator);
}

void WrenchMenuModel::ActiveTabChanged(TabContentsWrapper* old_contents,
                                       TabContentsWrapper* new_contents,
                                       int index,
                                       bool user_gesture) {
  // The user has switched between tabs and the new tab may have a different
  // zoom setting.
  UpdateZoomControls();
}

void WrenchMenuModel::TabReplacedAt(TabStripModel* tab_strip_model,
                                    TabContentsWrapper* old_contents,
                                    TabContentsWrapper* new_contents,
                                    int index) {
  UpdateZoomControls();
}

void WrenchMenuModel::TabStripModelDeleted() {
  // During views shutdown, the tabstrip model/browser is deleted first, while
  // it is the opposite in gtk land.
  tabstrip_model_->RemoveObserver(this);
  tabstrip_model_ = NULL;
}

void WrenchMenuModel::Observe(int type,
                              const content::NotificationSource& source,
                              const content::NotificationDetails& details) {
  switch (type) {
    case content::NOTIFICATION_ZOOM_LEVEL_CHANGED:
    case content::NOTIFICATION_NAV_ENTRY_COMMITTED:
      UpdateZoomControls();
      break;
    default:
      NOTREACHED();
  }
}

// For testing.
WrenchMenuModel::WrenchMenuModel()
    : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
      provider_(NULL),
      browser_(NULL),
      tabstrip_model_(NULL) {
}

#if !defined(OS_CHROMEOS)
void WrenchMenuModel::Build() {
  AddItemWithStringId(IDC_NEW_TAB, IDS_NEW_TAB);
  AddItemWithStringId(IDC_NEW_WINDOW, IDS_NEW_WINDOW);
  AddItemWithStringId(IDC_NEW_INCOGNITO_WINDOW, IDS_NEW_INCOGNITO_WINDOW);

  bookmark_sub_menu_model_.reset(new BookmarkSubMenuModel(this, browser_));
  AddSubMenuWithStringId(IDC_BOOKMARKS_MENU, IDS_BOOKMARKS_MENU,
                         bookmark_sub_menu_model_.get());

  AddSeparator();
#if defined(OS_POSIX) && !defined(TOOLKIT_VIEWS)
  // WARNING: Mac does not use the ButtonMenuItemModel, but instead defines the
  // layout for this menu item in Toolbar.xib. It does, however, use the
  // command_id value from AddButtonItem() to identify this special item.
  edit_menu_item_model_.reset(new ui::ButtonMenuItemModel(IDS_EDIT, this));
  edit_menu_item_model_->AddGroupItemWithStringId(IDC_CUT, IDS_CUT);
  edit_menu_item_model_->AddGroupItemWithStringId(IDC_COPY, IDS_COPY);
  edit_menu_item_model_->AddGroupItemWithStringId(IDC_PASTE, IDS_PASTE);
  AddButtonItem(IDC_EDIT_MENU, edit_menu_item_model_.get());
#else
  // TODO(port): Move to the above.
  CreateCutCopyPaste();
#endif

  AddSeparator();
#if defined(OS_POSIX) && !defined(TOOLKIT_VIEWS)
  // WARNING: See above comment.
  zoom_menu_item_model_.reset(
      new ui::ButtonMenuItemModel(IDS_ZOOM_MENU, this));
  zoom_menu_item_model_->AddGroupItemWithStringId(
      IDC_ZOOM_MINUS, IDS_ZOOM_MINUS2);
  zoom_menu_item_model_->AddButtonLabel(IDC_ZOOM_PERCENT_DISPLAY,
                                        IDS_ZOOM_PLUS2);
  zoom_menu_item_model_->AddGroupItemWithStringId(
      IDC_ZOOM_PLUS, IDS_ZOOM_PLUS2);
  zoom_menu_item_model_->AddSpace();
  zoom_menu_item_model_->AddItemWithImage(
      IDC_FULLSCREEN, IDR_FULLSCREEN_MENU_BUTTON);
  AddButtonItem(IDC_ZOOM_MENU, zoom_menu_item_model_.get());
#else
  // TODO(port): Move to the above.
  CreateZoomFullscreen();
#endif

  AddSeparator();
  AddItemWithStringId(IDC_SAVE_PAGE, IDS_SAVE_PAGE);
  AddItemWithStringId(IDC_FIND, IDS_FIND);
  AddItemWithStringId(IDC_PRINT, IDS_PRINT);

  tools_menu_model_.reset(new ToolsMenuModel(this, browser_));
  AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_TOOLS_MENU,
                         tools_menu_model_.get());

  AddSeparator();

  AddItemWithStringId(IDC_SHOW_HISTORY, IDS_SHOW_HISTORY);
  AddItemWithStringId(IDC_SHOW_DOWNLOADS, IDS_SHOW_DOWNLOADS);
  AddSeparator();

  if (browser_->profile()->GetOriginalProfile()->IsSyncAccessible()) {
    const string16 short_product_name =
        l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME);
    AddItem(IDC_SHOW_SYNC_SETUP, l10n_util::GetStringFUTF16(
        IDS_SYNC_MENU_PRE_SYNCED_LABEL, short_product_name));
    AddSeparator();
  }

  AddItemWithStringId(IDC_OPTIONS, IDS_SETTINGS);
  AddItem(IDC_ABOUT, l10n_util::GetStringUTF16(IDS_ABOUT));
  string16 num_background_pages = base::FormatNumber(
      TaskManager::GetBackgroundPageCount());
  AddItem(IDC_VIEW_BACKGROUND_PAGES, l10n_util::GetStringFUTF16(
      IDS_VIEW_BACKGROUND_PAGES, num_background_pages));
  AddItem(IDC_UPGRADE_DIALOG, l10n_util::GetStringUTF16(IDS_UPDATE_NOW));
  AddItem(IDC_VIEW_INCOMPATIBILITIES, l10n_util::GetStringUTF16(
      IDS_VIEW_INCOMPATIBILITIES));

#if defined(OS_WIN)
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  SetIcon(GetIndexOfCommandId(IDC_VIEW_INCOMPATIBILITIES),
          *rb.GetBitmapNamed(IDR_CONFLICT_MENU));
#endif

  AddItemWithStringId(IDC_HELP_PAGE, IDS_HELP_PAGE);

  AddGlobalErrorMenuItems();

  if (browser_defaults::kShowExitMenuItem) {
    AddSeparator();
    AddItemWithStringId(IDC_EXIT, IDS_EXIT);
  }
}
#endif // !OS_CHROMEOS

void WrenchMenuModel::AddGlobalErrorMenuItems() {
  // TODO(sail): Currently we only build the wrench menu once per browser
  // window. This means that if a new error is added after the menu is built
  // it won't show in the existing wrench menu. To fix this we need to some
  // how update the menu if new errors are added.
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  const GlobalErrorService::GlobalErrorList& errors =
      GlobalErrorServiceFactory::GetForProfile(browser_->profile())->errors();
  for (GlobalErrorService::GlobalErrorList::const_iterator
       it = errors.begin(); it != errors.end(); ++it) {
    GlobalError* error = *it;
    if (error->HasMenuItem()) {
      AddItem(error->MenuItemCommandID(), error->MenuItemLabel());
      int icon_id = error->MenuItemIconResourceID();
      if (icon_id) {
        gfx::Image& image = rb.GetImageNamed(icon_id);
        SetIcon(GetIndexOfCommandId(error->MenuItemCommandID()),
                *image.ToSkBitmap());
      }
    }
  }
}

void WrenchMenuModel::CreateCutCopyPaste() {
  // WARNING: views/wrench_menu assumes these items are added in this order. If
  // you change the order you'll need to update wrench_menu as well.
  AddItemWithStringId(IDC_CUT, IDS_CUT);
  AddItemWithStringId(IDC_COPY, IDS_COPY);
  AddItemWithStringId(IDC_PASTE, IDS_PASTE);
}

void WrenchMenuModel::CreateZoomFullscreen() {
  // WARNING: views/wrench_menu assumes these items are added in this order. If
  // you change the order you'll need to update wrench_menu as well.
  AddItemWithStringId(IDC_ZOOM_MINUS, IDS_ZOOM_MINUS);
  AddItemWithStringId(IDC_ZOOM_PLUS, IDS_ZOOM_PLUS);
  AddItemWithStringId(IDC_FULLSCREEN, IDS_FULLSCREEN);
}

void WrenchMenuModel::UpdateZoomControls() {
  bool enable_increment = false;
  bool enable_decrement = false;
  int zoom_percent = 100;
  if (browser_->GetSelectedWebContents()) {
    zoom_percent = browser_->GetSelectedWebContents()->GetZoomPercent(
        &enable_increment, &enable_decrement);
  }
  zoom_label_ = l10n_util::GetStringFUTF16(
      IDS_ZOOM_PERCENT, base::IntToString16(zoom_percent));
}

string16 WrenchMenuModel::GetSyncMenuLabel() const {
  return sync_ui_util::GetSyncMenuLabel(ProfileSyncServiceFactory::
      GetInstance()->GetForProfile(browser_->profile()->GetOriginalProfile()));
}


text:
package net.x52im.mobileimsdk.android.event;

public interface ChatMessageEvent {
    void onRecieveMessage(String fingerPrintOfProtocal, String userid, String dataContent, int typeu);
    void onErrorResponse(int errorCode, String errorMsg);
}

redpajama_set_name: RedPajamaGithub


text:
package org.jetbrains.plugins.scala.codeInspection.collections

import org.jetbrains.plugins.scala.codeInspection.InspectionBundle

/**
 * @author Nikolay.Tropin
 */
class HeadOptionTest extends OperationsOnCollectionInspectionTest {
  override val inspectionClass: Class[_ <: OperationOnCollectionInspection] = classOf[HeadOrLastOptionInspection]

  override def hint: String = InspectionBundle.message("replace.with.headOption")

  def test1(): Unit = {
    doTest(
      s"val seq = Seq(0); ${START}if (seq.size != 0) Some(seq.head) else None$END",
      "val seq = Seq(0); if (seq.size != 0) Some(seq.head) else None",
      "val seq = Seq(0); seq.headOption"
    )
  }

  def test2(): Unit = {
    doTest(
      s"val seq = Seq(0); ${START}if (seq.nonEmpty) Some(seq.head) else None$END",
      "val seq = Seq(0); if (seq.nonEmpty) Some(seq.head) else None",
      "val seq = Seq(0); seq.headOption"
    )
  }

  def test3(): Unit = {
    doTest(
      s"""val seq = Seq(0)
         |${START}if (seq.isEmpty)
         |  None
         |else
         |  Some(seq.head)$END""".stripMargin,
      """val seq = Seq(0)
        |if (seq.isEmpty)
        |  None
        |else
        |  Some(seq.head)""".stripMargin,
      """val seq = Seq(0)
        |seq.headOption""".stripMargin
    )
  }

  def test4(): Unit = {
    doTest(
      s"val seq = Seq(0); seq.${START}lift(0)$END",
      "val seq = Seq(0); seq.lift(0)",
      "val seq = Seq(0); seq.headOption"
    )
  }
}

class LastOptionTest extends OperationsOnCollectionInspectionTest {
  override val inspectionClass: Class[_ <: OperationOnCollectionInspection] = classOf[HeadOrLastOptionInspection]

  override def hint: String = InspectionBundle.message("replace.with.lastOption")

  def test1(): Unit = {
    doTest(
      s"val seq = Seq(0); ${START}if (seq.size != 0) Some(seq.last) else None$END",
      "val seq = Seq(0); if (seq.size != 0) Some(seq.last) else None",
      "val seq = Seq(0); seq.lastOption"
    )
  }

  def test2(): Unit = {
    doTest(
      s"val seq = Seq(0); ${START}if (seq.nonEmpty) Some(seq.last) else None$END",
      "val seq = Seq(0); if (seq.nonEmpty) Some(seq.last) else None",
      "val seq = Seq(0); seq.lastOption"
    )
  }

  def test3(): Unit = {
    doTest(
      s"""val seq = Seq(0)
         |${START}if (seq.isEmpty)
                    |  None
                    |else
                    |  Some(seq.last)$END""".stripMargin,
      """val seq = Seq(0)
        |if (seq.isEmpty)
        |  None
        |else
        |  Some(seq.last)""".stripMargin,
      """val seq = Seq(0)
        |seq.lastOption""".stripMargin
    )
  }

  def test4(): Unit = {
    doTest(
      s"val seq = Seq(0); seq.${START}lift(seq.size - 1)$END",
      "val seq = Seq(0); seq.lift(seq.size - 1)",
      "val seq = Seq(0); seq.lastOption"
    )
  }
}


text:
package com.github.havarunner.exception

import com.github.havarunner.HavaRunnerSuite

class SuiteMemberDoesNotBelongToSuitePackage(suiteMember: Class[_], suiteClass: Class[_<:HavaRunnerSuite[_]]) extends RuntimeException(
  String.format(
    "Suite member %s must be within the same package as the suite %s. Try moving %s under the package %s.",
    suiteMember.getName,
    suiteClass.getName,
    suiteMember.getSimpleName,
    suiteClass.getPackage.getName
  )
)


text:
#include "make_unsigned_test.hpp"
#include <type_traits>

enum e1 : char {};
enum class e2 : int {}; // TODO : is this valid that enum that underlying type is int -> unsigned long ?
enum class e3 : long {};

using types = ::testing::Types<
    std::tuple<e1, std::make_unsigned<e1>::type>,
    std::tuple<e2, std::make_unsigned<e2>::type>,
    std::tuple<e3, std::make_unsigned<e3>::type>
>;

INSTANTIATE_TYPED_TEST_CASE_P(enum, make_unsigned_test, types);


text:
<?php session_start(); ?>
<!DOCTYPE html>

<?php include('header.php');?>

<?php include('navbar.php');?>

    <?php

     if(isset($_SESSION["error"])){
      echo $_SESSION["error"];

     unset($_SESSION["error"]);

     }?>

Ingrese sus credenciales para iniciar sesion:

                    <form class="form-inline" action="procesalogin.php" method="POST">

                Usuario:
                <input type="text" class="form-control" id="username"
                       name ="username" placeholder="usuario">

                    Clave:
                 <input type="password" class="form-control" id="password"
                       name ="password" placeholder="123456">

              <button type="submit" class="btn btn-primary">Enviar</button>
          </form>


text:
package org.apache.druid.timeline.partition;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.druid.data.input.InputRow;
import org.apache.druid.java.util.common.ISE;

import javax.annotation.Nullable;
import java.util.List;
import java.util.Objects;

/**
 * See {@link BucketNumberedShardSpec} for how this class is used.
 *
 * @see BuildingSingleDimensionShardSpec
 */
public class SingleDimensionRangeBucketShardSpec implements BucketNumberedShardSpec<BuildingSingleDimensionShardSpec>
{
  private final int bucketId;
  private final String dimension;
  @Nullable
  private final String start;
  @Nullable
  private final String end;

  @JsonCreator
  public SingleDimensionRangeBucketShardSpec(
      @JsonProperty("bucketId") int bucketId,
      @JsonProperty("dimension") String dimension,
      @JsonProperty("start") @Nullable String start,
      @JsonProperty("end") @Nullable String end
  )
  {
    this.bucketId = bucketId;
    this.dimension = dimension;
    this.start = start;
    this.end = end;
  }

  @Override
  @JsonProperty
  public int getBucketId()
  {
    return bucketId;
  }

  @JsonProperty
  public String getDimension()
  {
    return dimension;
  }

  @Nullable
  @JsonProperty
  public String getStart()
  {
    return start;
  }

  @Nullable
  @JsonProperty
  public String getEnd()
  {
    return end;
  }

  @Override
  public BuildingSingleDimensionShardSpec convert(int partitionId)
  {
    return new BuildingSingleDimensionShardSpec(bucketId, dimension, start, end, partitionId);
  }

  public boolean isInChunk(InputRow inputRow)
  {
    return SingleDimensionShardSpec.isInChunk(dimension, start, end, inputRow);
  }

  @Override
  public ShardSpecLookup getLookup(List<? extends ShardSpec> shardSpecs)
  {
    return (long timestamp, InputRow row) -> {
      for (ShardSpec spec : shardSpecs) {
        if (((SingleDimensionRangeBucketShardSpec) spec).isInChunk(row)) {
          return spec;
        }
      }
      throw new ISE("row[%s] doesn't fit in any shard[%s]", row, shardSpecs);
    };
  }

  @Override
  public String getType()
  {
    return Type.BUCKET_SINGLE_DIM;
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    SingleDimensionRangeBucketShardSpec bucket = (SingleDimensionRangeBucketShardSpec) o;
    return bucketId == bucket.bucketId &&
           Objects.equals(dimension, bucket.dimension) &&
           Objects.equals(start, bucket.start) &&
           Objects.equals(end, bucket.end);
  }

  @Override
  public int hashCode()
  {
    return Objects.hash(bucketId, dimension, start, end);
  }

  @Override
  public String toString()
  {
    return "SingleDimensionRangeBucketShardSpec{" +
           ", bucketId=" + bucketId +
           ", dimension='" + dimension + '\'' +
           ", start='" + start + '\'' +
           ", end='" + end + '\'' +
           '}';
  }
}


text:
package org.onosproject.bgp.controller;
import java.util.List;
import org.jboss.netty.channel.Channel;
import org.onosproject.bgp.bgpio.exceptions.BgpParseException;
import org.onosproject.bgp.bgpio.protocol.BgpFactory;
import org.onosproject.bgp.bgpio.protocol.BgpMessage;
import org.onosproject.bgp.bgpio.protocol.flowspec.BgpFlowSpecNlri;
import org.onosproject.bgp.bgpio.protocol.flowspec.BgpFlowSpecRouteKey;
import org.onosproject.bgp.bgpio.types.BgpValueType;
import org.onosproject.bgp.bgpio.types.attr.WideCommunity;

/**
 * Represents the peer side of an BGP peer.
 *
 */
public interface BgpPeer {

    enum FlowSpecOperation {

        /**
         * Signifies addition of flow specification rule.
         */
        ADD,

        /**
         *  Signifies updation of flow specification rule.
         */
        UPDATE,

        /**
         * Signifies deletion of flow specification rule.
         */
        DELETE
    }
    /**
     * Sets the associated Netty channel for this bgp peer.
     *
     * @param channel the Netty channel
     */
    void setChannel(Channel channel);

    /**
     * Gets the associated Netty channel handler for this bgp peer.
     *
     * @return Channel channel connected.
     */
    Channel getChannel();

    /**
     * Sets whether the bgp peer is connected.
     *
     * @param connected whether the bgp peer is connected
     */
    void setConnected(boolean connected);

    /**
     * Checks whether the handshake is complete.
     *
     * @return true is finished, false if not.
     */
    boolean isHandshakeComplete();

    /**
     * Writes the message to the peer.
     *
     * @param msg the message to write
     */
    void sendMessage(BgpMessage msg);

    /**
     * Writes the BgpMessage list to the peer.
     *
     * @param msgs the messages to be written
     */
    void sendMessage(List<BgpMessage> msgs);

    /**
     * Provides the factory for BGP version.
     *
     * @return BGP version specific factory.
     */
    BgpFactory factory();

    /**
     * Checks if the bgp peer is still connected.
     *
     * @return whether the bgp peer is still connected
     */
    boolean isConnected();

    /**
     * Disconnects the bgp peer by closing the TCP connection. Results in a call to the channel handler's
     * channelDisconnected method for cleanup
     */
    void disconnectPeer();

    /**
     * Identifies the channel used to communicate with the bgp peer.
     *
     * @return string representation of the connection to the peer
     */
    String channelId();

    /**
     * Maintaining Adj-RIB-In separately for each peer.
     *
     * @param pathAttr list of Bgp path attributes
     * @throws BgpParseException while building Adj-Rib-In
     */
    void buildAdjRibIn(List<BgpValueType> pathAttr) throws BgpParseException;

    /**
     * Return the BGP session info.
     *
     * @return sessionInfo bgp session info
     */
    BgpSessionInfo sessionInfo();

    /**
     * Updates flow specification rule.
     *
     * @param operType operation type add or delete or update
     * @param routeKey flow route key  for the flow rule
     * @param flowSpec BGP flow specification components
     * @param wideCommunity for route policy
     */
    void updateFlowSpec(FlowSpecOperation operType, BgpFlowSpecRouteKey routeKey,
                               BgpFlowSpecNlri flowSpec, WideCommunity wideCommunity);
}


text:
package io.sundr.examples.curator.impl;

import io.sundr.examples.curator.PathableAndBytesableInterface;
import io.sundr.examples.curator.SetDataInterface;
import io.sundr.examples.curator.StatablePathablePathAndBytesableInterface;
import io.sundr.examples.curator.WatchableStatablePathablePathAndBytesableInterface;

public class SetDataInterfaceImpl implements SetDataInterface, WatchableStatablePathablePathAndBytesableInterface<String, Void>,
    PathableAndBytesableInterface<String, Void>,
    StatablePathablePathAndBytesableInterface<String, Void> {

  @Override
  public WatchableStatablePathablePathAndBytesableInterface<String, Void> inBackground(boolean flag) {
    return this;
  }

  @Override
  public WatchableStatablePathablePathAndBytesableInterface<String, Void> inBackground(Object context) {
    return this;
  }

  @Override
  public WatchableStatablePathablePathAndBytesableInterface<String, Void> inBackground() {
    return this;
  }

  @Override
  public Void forPath(String path, byte[] bytes) {
    return null;
  }

  @Override
  public String forPath(String path) {
    return "";
  }

  @Override
  public PathableAndBytesableInterface<String, Void> storingStatIn(String stat) {
    return this;
  }

  @Override
  public StatablePathablePathAndBytesableInterface<String, Void> watched() {
    return this;
  }

  /*
   * static {
   * new SetDataInterfaceImpl().forPath("somePath");
   * new SetDataInterfaceImpl().forPath("somePath", (byte) 0);
   * new SetDataInterfaceImpl().inBackground().forPath("somePath", (byte) 0);
   * new SetDataInterfaceImpl().forPath("somePath");
   * new SetDataInterfaceImpl().watched().forPath("somePath");
   * new SetDataInterfaceImpl().inBackground().forPath("somePath", (byte) 9);
   * String s = new SetDataInterfaceImpl().inBackground().forPath("somePath");
   * }
   */

}


text:
@extends('adminlte::layouts.auth')

@section('htmlheader_title')
    Log in
@endsection

@section('content')

                Panel Nordala

 Zaloguj Się aby rozpocząć przygodę

        <form action="/telegram/login" method="POST">
            {{ csrf_field()}}

              @if(session('error'))

                  {{ session('error') }}

              @endif

                <input type="email" class="form-control" placeholder="example@example.com" name="Email" value="{{ old('Email') }}"/>

                <input type="password" class="form-control" placeholder="Password" name="password"/>

                     <input type="submit" value="{{trans('app.LoginBtn')}}" class="btn btn-success pull-left" />

                    <input type="button" value="{{trans('app.Register')}}" class="btn btn-primary pull-right" onclick="location.href='/telegram/register'"/>

                    <input type="button" value="{{trans('auth.forgotpassword')}}" class="btn btn-primary pull-right" onclick="location.href='/telegram/password/reset'"/>

        </form>

@endsection


text:
class Node(object):
    def __init__(self,val, left = None, right = None):
        self.val = val
        self.left = left
        self.right = right

def root_to_leaf(root,path):
    if root.left is None and root.right is None:
        path.append(root.val)
        print(" ".join(map(str,path)))
        return

    path.append(root.val)
    root_to_leaf(root.left, path)
    path.pop()
    root_to_leaf(root.right, path)
    path.pop()

tree = Node(1,Node(2,Node(4),Node(5)),Node(3,Node(6),Node(7)))

root_to_leaf(tree,[])


text:
**Deprecation Notice:** This project is no longer being maintained.

a lightweight, progressively enhanced table.

[Download Tables](https://github.com/cferdinandi/tables/archive/master.zip) / [View the demo](http://cferdinandi.github.io/tables/)

**In This Documentation**

1. [Getting Started](#getting-started)
2. [Installing with Package Managers](#installing-with-package-managers)
3. [Working with the Source Files](#working-with-the-source-files)
4. [Browser Compatibility](#browser-compatibility)
5. [How to Contribute](#how-to-contribute)
6. [License](#license)
7. [Changelog](#changelog)

## Getting Started

Compiled and production-ready code can be found in the `dist` directory. The `src` directory contains development code.

### 1. Include Tables on your site.

```html
<link rel="stylesheet" href="dist/css/tables.css">
```

Tables is [built with Sass](http://sass-lang.com/) for easy customization. If you don't use Sass, that's ok. The `css` folder contains compiled vanilla CSS.

The `_config.scss` and `_mixins.scss` files are the same ones used in [Kraken](http://cferdinandi.github.io/kraken/), so you can drop the `_tables.css` file right into Kraken without making any updates. Or, adjust the variables to suit your own project.

### 2. Add the markup to your HTML.

```html
<table>
	<thead>
		<tr>
			<th>First Name</th>
			<th>Last Name</th>
			<th>Super Hero</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>Peter</td>
			<td>Parker</td>
			<td>Spiderman</td>
		</tr>
		<tr>
			<td>Bruce</td>
			<td>Wayne</td>
			<td>Batman</td>
		</tr>
		<tr>
			<td>Clark</td>
			<td>Kent</td>
			<td>Superman</td>
		</tr>
	</tbody>
</table>
```

Add the `.table-condensed` class for more compact tables.

```html
<table class="table-condensed">
	...
</table>
```

And that's it, you're done. Nice work!

## Installing with Package Managers

You can install Tables with your favorite package manager.

* **[NPM](https://www.npmjs.org/):** `npm install cferdinandi/tables`
* **[Bower](http://bower.io/):** `bower install https://github.com/cferdinandi/tables.git`
* **[Component](http://component.io/):** `component install cferdinandi/tables`

## Working with the Source Files

If you would prefer, you can work with the development code in the `src` directory using the included [Gulp build system](http://gulpjs.com/). This compiles, lints, and minifies code, and runs unit tests. It's the same build system that's used by [Kraken](http://cferdinandi.github.io/kraken/), so it includes some unnecessary tasks and Sass variables but can be dropped right in to the boilerplate without any configuration.

### Dependencies
Make sure these are installed first.

* [Node.js](http://nodejs.org)
* [Ruby Sass](http://sass-lang.com/install)
* [Gulp](http://gulpjs.com) `sudo npm install -g gulp`

### Quick Start

1. In bash/terminal/command line, `cd` into your project directory.
2. Run `npm install` to install required files.
3. When it's done installing, run one of the task runners to get going:
	* `gulp` manually compiles files.
	* `gulp watch` automatically compiles files when changes are made.
	* `gulp reload` automatically compiles files and applies changes using [LiveReload](http://livereload.com/).

## Browser Compatibility

Tables works with all modern browsers, including IE 6 and above. However, browsers that don't support `:nth-child` pseudo selectors will display a lined table instead of a striped one.

## How to Contribute

In lieu of a formal style guide, take care to maintain the existing coding style. Don't forget to update the version number, the changelog (in the `readme.md` file), and when applicable, the documentation.

## License

The code is available under the [MIT License](LICENSE.md).

## Changelog

Tables uses [semantic versioning](http://semver.org/).

* v2.2.2 - October 19, 2014
	* Updated `gulpfile.js` tasks and namespacing.
* v2.2.1 - October 3, 2014
	* Updated `gulpfile.js`.
	* Updated readme.
	* Updated travis config.
* v2.2.0 - June 23, 2014
	* Converted to gulp.js workflow.
	* Updated naming conventions.
	* Added minified versions of files.
	* Updated to three number versioning system.
* v2.1 - December 2, 2013
	* Updated folder structure for easier use.
* v2.0 - November 29, 2013
	* Converted to Sass.
	* Rebuilt styling from scratch.
	* Switched to MIT license.
	* Removed `.table-bordered` option.
	* Added zebra-striping for better usability.
* v1.1 - June 18, 2013
	* Reduced padding for `.table-condensed`.
* v1.0 - February 13, 2013
	* Renamed `example.html` to `index.html`.
* v1.0 - February 5, 2013
	* Initial release.


text:
package com.marverenic.music.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.marverenic.music.utils.Themes;

/**
 * An {@link android.support.v7.widget.RecyclerView.ItemDecoration} that draws horizontal dividers
 * between entries in a {@link RecyclerView}
 */
public class DividerDecoration extends RecyclerView.ItemDecoration {

    private static final int DIVIDER_HEIGHT_DP = 1;

    private Drawable dividerDrawable;
    private static int measuredDividerHeight;
    private int[] excludedIDs;

    /**
     * Create a new ItemDecorator for use with a RecyclerView
     * @param context A context held temporarily to get colors and display metrics
     */
    public DividerDecoration(Context context) {
        this(context, null);
    }

    /**
     * Create an ItemDecorator for use with a RecyclerView
     * @param context A context held temporarily to get colors and display metrics
     * @param excludedLayoutIDs an array of layoutIDs to exclude adding a divider to
     *                          null to add a divider to each entry in the RecyclerView
     */
    public DividerDecoration(Context context, int[] excludedLayoutIDs){
        dividerDrawable = new ColorDrawable(Themes.isLight(context)? 0x1E000000 : 0x1EFFFFFF);
        measuredDividerHeight = (int) Math.ceil(DIVIDER_HEIGHT_DP * context.getResources().getDisplayMetrics().density);
        excludedIDs = excludedLayoutIDs;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int endIndex = parent.getChildCount();
        for (int i = 0; i < endIndex - 1; i++) { // Exclude the last item in the list
            final View child = parent.getChildAt(i);
            if (excludedIDs == null || includeView(child.getId())) {

                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + measuredDividerHeight;

                dividerDrawable.setBounds(left, top, right, bottom);

                // Don't draw separators under the last item in a section
                if (excludedIDs == null || includeView(parent.getChildAt(i + 1).getId())) dividerDrawable.draw(c);
            }
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        if (excludedIDs == null || includeView(view.getId())){
            outRect.bottom = measuredDividerHeight;
        }
    }

    private boolean includeView(int viewId){
        for (int i : excludedIDs){
            if (viewId == i) return false;
        }
        return true;
    }
}


text:
using IdentityServer3.Core.Models;

namespace IdentityServer3.Core.Validation
{
    /// <summary>
    /// Validation result for client validation
    /// </summary>
    public class ScopeSecretValidationResult : ValidationResult
    {
        /// <summary>
        /// Gets or sets the client.
        /// </summary>
        /// <value>
        /// The client.
        /// </value>
        public Scope Scope { get; set; }
    }
}


text:
layout: post
status: publish
published: true
title: The New Sysinternals Web Site
author: Leask

author_login: leask
author_email: i@leaskh.com
author_url: https://leaskh.com
wordpress_id: 425
wordpress_url: http://leaskh.wordpress.com/2006/11/08/the-new-sysinternals-web-site
date: '2006-11-08 13:18:57 +0800'
date_gmt: '2006-11-08 13:18:57 +0800'
categories:
- Computers and Internet
tags: []
comments: []
---

The Sysinternals web site was created in 1996 by Mark Russinovich and Bryce Cogswell to host their advanced system utilities and technical information and Microsoft acquired Sysinternals in July, 2006. Whether you’re an IT Pro or a developer, you’ll find Sysinternals utilities to help you manage, troubleshoot and diagnose your Windows systems and applications. If you have a question about a tool or how to use it, please visit the Sysinternals Forum for answers and help from other users and our moderators.

Microsoft的TechNet技术网站已经被新的Sysinternals代替了。

TechNet是以前在Windows玩编程的时候常去的,查语法,查函数,等等。

现在用Mac了,也慢慢开始上ADC比较多了。

但是有点怀念在TechNet探索的那段日子。

那个时候什么都不懂吧,像个小猫,什么都好好奇,跌跌撞撞却又学到点东西。

Snowman也是那个时候不知天高地厚写出来的。

说起Snowman,今天在cnBeta看到赢政软件下载关闭了,那也是收录Snowman的网站之一。

互联网每天都在变呀,无法想象明天睡醒又出什么新鲜事情。

但是可以肯定的是,这个圈子养活很多人,这些人改变着这个世界。

More About:

http://www.microsoft.com/technet/sysinternals/default.mspx

http://soft.winzheng.com/


text:
<LINK REL="stylesheet" HREF="../static/styles.css">

<TITLE>ChannelControl::addFadePoint</TITLE>

Firelight Technologies FMOD Studio API

ChannelControl::addFadePoint

Add a volume point to fade from or towards, using a clock offset and 0 to 1 volume level.

C++ Syntax

FMOD_RESULT ChannelControl::addFadePoint(
  unsigned long long dspclock,
  float volume
);

Parameters

dspclock

DSP clock of the parent channel group to set the fade point volume.

volume

Volume level where 0 is silent and 1.0 is normal volume.  Amplification is supported.

Return Values

If the function succeeds then the return value is FMOD_OK.

If the function fails then the return value will be one of the values defined in the FMOD_RESULT enumeration.

Remarks

For every fade point, FMOD will do a per sample volume ramp between them.  It will scale with the current Channel or ChannelGroup's volume.

// Ramp from full volume to half volume over the next 4096 samples
FMOD_RESULT result;
unsigned long long parentclock;
result = target->getDSPClock(NULL, &parentclock);
result = target->addFadePoint(parentclock,        1.0f);
result = target->addFadePoint(parentclock + 4096, 0.5f);

See Also

ChannelControl::removeFadePoints

ChannelControl::setFadePointRamp

ChannelControl::getFadePoints

Version 1.08.02 Built on Apr 14, 2016


text:
require 'spec_helper'

describe Iyzi::Request do
  before { stub_config }
  let(:config) { Iyzi.configuration }

  describe '#initialize' do
    it 'initializes request object' do
      request = described_class.new('post', '/path/to/request', locale: 'en', conversation_id: '123')
      expect(request.method).to eq('post')
      expect(request.path).to eq('/path/to/request')
    end
  end

  describe '#connection' do
    let(:request) { described_class.new('post', '/path') }
    it 'returns connection' do
      connection = request.connection
      expect(connection).to be_kind_of(Faraday::Connection)
      expect(connection.url_prefix.to_s).to eq(config.base_url)
    end
  end

  describe '#headers' do
    let(:digest) { 'BXwJ+miJyQ88NLQJB1/FzWZ6he8=' }
    let(:auth_header_string) { "IYZWS IYZICO_API_KEY:#{digest}" }
    let(:pki) { 'pki' }
    let(:random_string) { 'random_string' }
    let(:request) { described_class.new('post', '/path', { config: config }) }

    before do
      # stub random string
      allow_any_instance_of(described_class).to receive(:secure_random_string)
        .and_return(random_string)
      # stub pki
      allow_any_instance_of(described_class).to receive(:to_pki)
        .and_return(pki)
    end

    it 'returns header hash' do
      expected = {
        'Authorization' => auth_header_string,
        'x-iyzi-rnd'    => random_string
      }
      expect(request.auth_headers).to eq(expected)
    end

    it '#auth_header_string' do
      expect(request.auth_header_string).to eq(auth_header_string)
    end

    it '#request_hash_digest' do
      expect(request.request_hash_digest).to eq(digest)
    end

    it '#params_will_be_hashed' do
      expected = config.api_key + random_string + config.secret + pki
      expect(request.params_will_be_hashed).to eq(expected)
    end
  end

  it 'generates secure_random_string' do
    str = described_class.new('post', '/path').secure_random_string
    expect(str).not_to be_nil
    expect(str.size).to eq(8)
  end
end


text:
'use strict'
/* globals describe beforeEach it */

let nock = require('nock')
let cmd = require('../../commands')

let chai = require('chai')
let expect = chai.expect

let chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised)

let cli = require('heroku-cli-util')

let now = new Date()

describe('spaces', function () {
  beforeEach(() => cli.mockConsole())

  it('shows spaces', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/spaces')
      .reply(200, [
        {name: 'my-space', organization: {name: 'my-org'}, region: {name: 'my-region'}, state: 'enabled', created_at: now}
      ])
    return cmd.run({flags: {}})
      .then(() => expect(cli.stdout).to.equal(
        `Name      Organization  Region     State    Created At
────────  ────────────  ─────────  ───────  ────────────────────────
my-space  my-org        my-region  enabled  ${now.toISOString()}
`))
      .then(() => api.done())
  })

  it('shows spaces with --json', function () {
    let spaces = [{name: 'my-space', organization: {name: 'my-org'}, region: {name: 'my-region'}, state: 'enabled', created_at: now.toISOString()}]
    let api = nock('https://api.heroku.com:443')
      .get('/spaces')
      .reply(200, spaces)
    return cmd.run({flags: {json: true}})
      .then(() => expect(JSON.parse(cli.stdout)).to.eql(spaces))
      .then(() => api.done())
  })

  it('shows spaces scoped by orgs', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/spaces')
      .reply(200, [
        {name: 'my-space', organization: {name: 'my-org'}, region: {name: 'my-region'}, state: 'enabled', created_at: now},
        {name: 'other-space', organization: {name: 'other-org'}, region: {name: 'my-region'}, state: 'enabled', created_at: now}
      ])
    return cmd.run({flags: {}, org: 'my-org'})
      .then(() => expect(cli.stdout).to.equal(
        `Name      Organization  Region     State    Created At
────────  ────────────  ─────────  ───────  ────────────────────────
my-space  my-org        my-region  enabled  ${now.toISOString()}
`))
      .then(() => api.done())
  })

  it('shows spaces org error message', function () {
    nock('https://api.heroku.com:443')
      .get('/spaces')
      .reply(200, [])
    return chai.assert.isRejected(cmd.run({flags: {}, org: 'my-org'}), /^Error: No spaces in my-org.$/)
  })

  it('shows spaces error message', function () {
    nock('https://api.heroku.com:443')
      .get('/spaces')
      .reply(200, [])
    return chai.assert.isRejected(cmd.run({flags: {}}), /^Error: You do not have access to any spaces./)
  })
})


text:
////////////////////////////////////////////////////////////////////////////////
//
//  TYPHOON FRAMEWORK
//  Copyright 2015, Typhoon Framework Contributors
//  All Rights Reserved.
//
//  NOTICE: The authors permit you to use, modify, and distribute this file
//  in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////

#import "PFApplicationAssembly.h"
#import "PFCoreComponents.h"
#import "PFAddCityViewController.h"
#import "PFRootViewController.h"
#import "PFCitiesListViewController.h"
#import "PFThemeAssembly.h"
#import "PFWeatherReportViewController.h"
#import "PFAppDelegate.h"
#import "TyphoonDefinition+Infrastructure.h"

@implementation PFApplicationAssembly

//-------------------------------------------------------------------------------------------
#pragma mark - Bootstrapping
//-------------------------------------------------------------------------------------------

- (PFAppDelegate *)appDelegate
{
    return [TyphoonDefinition withClass:[PFAppDelegate class] configuration:^(TyphoonDefinition *definition)
    {
        [definition injectProperty:@selector(window) with:[self mainWindow]];
        [definition injectProperty:@selector(cityDao) with:[_coreComponents cityDao]];
        [definition injectProperty:@selector(rootViewController) with:[self rootViewController]];
    }];
}

/**
* Set up the main window. We don't really need to use DI for this, but it shows an example of injecting a struct.
*/
- (UIWindow *)mainWindow
{
    return [TyphoonDefinition withClass:[UIWindow class] configuration:^(TyphoonDefinition *definition)
    {
        [definition useInitializer:@selector(initWithFrame:) parameters:^(TyphoonMethod *initializer)
        {
            [initializer injectParameterWith:[NSValue valueWithCGRect:[[UIScreen mainScreen] bounds]]];
        }];
        [definition injectProperty:@selector(rootViewController) with:[self rootViewController]];
    }];
}

- (id)config
{
    return [TyphoonDefinition configDefinitionWithName:@"Configuration.plist"];
}

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

- (PFRootViewController *)rootViewController
{
    return [TyphoonDefinition withClass:[PFRootViewController class] configuration:^(TyphoonDefinition *definition)
    {
        [definition useInitializer:@selector(initWithMainContentViewController:assembly:) parameters:^(TyphoonMethod *initializer)
        {
            [initializer injectParameterWith:[self weatherReportController]];
            [initializer injectParameterWith:self];
        }];
        definition.scope = TyphoonScopeSingleton;
    }];
}

- (PFCitiesListViewController *)citiesListController
{
    return [TyphoonDefinition withClass:[PFCitiesListViewController class] configuration:^(TyphoonDefinition *definition)
    {
        [definition useInitializer:@selector(initWithCityDao:theme:) parameters:^(TyphoonMethod *initializer)
        {
            [initializer injectParameterWith:[_coreComponents cityDao]];
            [initializer injectParameterWith:[_themeProvider currentTheme]];
        }];
        [definition injectProperty:@selector(assembly)];
    }];
}

- (PFWeatherReportViewController *)weatherReportController
{
    return [TyphoonDefinition withClass:[PFWeatherReportViewController class] configuration:^(TyphoonDefinition *definition)
    {
        [definition useInitializer:@selector(initWithView:weatherClient:weatherReportDao:cityDao:assembly:)
            parameters:^(TyphoonMethod *initializer)
            {
                [initializer injectParameterWith:[self weatherReportView]];
                [initializer injectParameterWith:[_coreComponents weatherClient]];
                [initializer injectParameterWith:[_coreComponents weatherReportDao]];
                [initializer injectParameterWith:[_coreComponents cityDao]];
                [initializer injectParameterWith:self];
            }];
    }];
}

- (PFWeatherReportView *)weatherReportView
{
    return [TyphoonDefinition withClass:[PFWeatherReportView class] configuration:^(TyphoonDefinition *definition)
    {
        [definition injectProperty:@selector(theme) with:[_themeProvider currentTheme]];
    }];
}

- (PFAddCityViewController *)addCityViewController
{
    return [TyphoonDefinition withClass:[PFAddCityViewController class] configuration:^(TyphoonDefinition *definition)
    {
        [definition useInitializer:@selector(initWithNibName:bundle:) parameters:^(TyphoonMethod *initializer)
        {
            [initializer injectParameterWith:@"AddCity"];
            [initializer injectParameterWith:[NSBundle mainBundle]];
        }];

        [definition injectProperty:@selector(cityDao) with:[_coreComponents cityDao]];
        [definition injectProperty:@selector(weatherClient) with:[_coreComponents weatherClient]];
        [definition injectProperty:@selector(theme) with:[_themeProvider currentTheme]];
        [definition injectProperty:@selector(rootViewController) with:[self rootViewController]];
    }];
}

@end


text:
#include "config.h"
#include "test.h"

#include "dict.h"
#include "library.h"
#include "mock.h"
#include "modules.h"
#include "p11-kit.h"
#include "virtual.h"

#include <sys/types.h>
#ifdef OS_UNIX
#include <sys/wait.h>
#endif
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static CK_FUNCTION_LIST_PTR
setup_mock_module (CK_SESSION_HANDLE *session)
{
	CK_FUNCTION_LIST_PTR module;
	CK_RV rv;

	p11_lock ();

	rv = p11_module_load_inlock_reentrant (&mock_module, 0, &module);
	assert (rv == CKR_OK);
	assert_ptr_not_null (module);
	assert (p11_virtual_is_wrapper (module));

	p11_unlock ();

	rv = p11_kit_module_initialize (module);
	assert (rv == CKR_OK);

	if (session) {
		rv = (module->C_OpenSession) (MOCK_SLOT_ONE_ID,
		                              CKF_RW_SESSION | CKF_SERIAL_SESSION,
		                              NULL, NULL, session);
		assert (rv == CKR_OK);
	}

	return module;
}

static void
teardown_mock_module (CK_FUNCTION_LIST_PTR module)
{
	CK_RV rv;

	rv = p11_kit_module_finalize (module);
	assert (rv == CKR_OK);

	p11_lock ();

	rv = p11_module_release_inlock_reentrant (module);
	assert (rv == CKR_OK);

	p11_unlock ();
}

static CK_RV
fail_C_Initialize (void *init_reserved)
{
	return CKR_FUNCTION_FAILED;
}

static void
test_initialize_finalize (void)
{
	CK_FUNCTION_LIST_PTR module;
	CK_RV rv;

	p11_lock ();

	rv = p11_module_load_inlock_reentrant (&mock_module, 0, &module);
	assert (rv == CKR_OK);
	assert_ptr_not_null (module);
	assert (p11_virtual_is_wrapper (module));

	p11_unlock ();

	rv = module->C_Initialize (NULL);
	assert (rv == CKR_OK);

	rv = module->C_Initialize (NULL);
	assert (rv == CKR_CRYPTOKI_ALREADY_INITIALIZED);

	rv = module->C_Finalize (NULL);
	assert (rv == CKR_OK);

	rv = module->C_Finalize (NULL);
	assert (rv == CKR_CRYPTOKI_NOT_INITIALIZED);

	p11_lock ();

	rv = p11_module_release_inlock_reentrant (module);
	assert (rv == CKR_OK);

	p11_unlock ();
}

static void
test_initialize_fail (void)
{
	CK_FUNCTION_LIST_PTR module;
	CK_FUNCTION_LIST base;
	CK_RV rv;

	memcpy (&base, &mock_module, sizeof (CK_FUNCTION_LIST));
	base.C_Initialize = fail_C_Initialize;

	p11_lock ();

	rv = p11_module_load_inlock_reentrant (&base, 0, &module);
	assert (rv == CKR_OK);

	p11_unlock ();

	rv = p11_kit_module_initialize (module);
	assert (rv == CKR_FUNCTION_FAILED);
}

static void
test_separate_close_all_sessions (void)
{
	CK_FUNCTION_LIST *first;
	CK_FUNCTION_LIST *second;
	CK_SESSION_HANDLE s1;
	CK_SESSION_HANDLE s2;
	CK_SESSION_INFO info;
	CK_RV rv;

	first = setup_mock_module (&s1);
	second = setup_mock_module (&s2);

	rv = first->C_GetSessionInfo (s1, &info);
	assert (rv == CKR_OK);

	rv = second->C_GetSessionInfo (s2, &info);
	assert (rv == CKR_OK);

	first->C_CloseAllSessions (MOCK_SLOT_ONE_ID);
	assert (rv == CKR_OK);

	rv = first->C_GetSessionInfo (s1, &info);
	assert (rv == CKR_SESSION_HANDLE_INVALID);

	rv = second->C_GetSessionInfo (s2, &info);
	assert (rv == CKR_OK);

	second->C_CloseAllSessions (MOCK_SLOT_ONE_ID);
	assert (rv == CKR_OK);

	rv = first->C_GetSessionInfo (s1, &info);
	assert (rv == CKR_SESSION_HANDLE_INVALID);

	rv = second->C_GetSessionInfo (s2, &info);
	assert (rv == CKR_SESSION_HANDLE_INVALID);

	teardown_mock_module (first);
	teardown_mock_module (second);
}

#ifdef OS_UNIX

static void
test_fork_and_reinitialize (void)
{
	CK_FUNCTION_LIST *module;
	CK_INFO info;
	int status;
	CK_RV rv;
	pid_t pid;
	int i;

	module = setup_mock_module (NULL);
	assert_ptr_not_null (module);

	pid = fork ();
	assert_num_cmp (pid, >=, 0);

	/* The child */
	if (pid == 0) {
		rv = (module->C_Initialize) (NULL);
		assert_num_eq (CKR_OK, rv);

		for (i = 0; i < 32; i++) {
			rv = (module->C_GetInfo) (&info);
			assert_num_eq (CKR_OK, rv);
		}

		rv = (module->C_Finalize) (NULL);
		assert_num_eq (CKR_OK, rv);

		_exit (66);
	}

	for (i = 0; i < 128; i++) {
		rv = (module->C_GetInfo) (&info);
		assert_num_eq (CKR_OK, rv);
	}

	assert_num_eq (waitpid (pid, &status, 0), pid);
	assert_num_eq (WEXITSTATUS (status), 66);

	teardown_mock_module (module);
}

#endif /* OS_UNIX */

/* Bring in all the mock module tests */
#include "test-mock.c"

int
main (int argc,
      char *argv[])
{
	mock_module_init ();
	p11_library_init ();

	p11_test (test_initialize_finalize, "/managed/test_initialize_finalize");
	p11_test (test_initialize_fail, "/managed/test_initialize_fail");
	p11_test (test_separate_close_all_sessions, "/managed/test_separate_close_all_sessions");

#ifdef OS_UNIX
	p11_test (test_fork_and_reinitialize, "/managed/fork-and-reinitialize");
#endif

	test_mock_add_tests ("/managed");

	p11_kit_be_quiet ();

	return p11_test_run (argc, argv);
}


text:
/*****************************************************************************
 * \file
 * \brief This header contains a detailed memory tracker used to watch every
 *        individual allocation
 *****************************************************************************/

/*
  The MIT License (MIT)

  Copyright (c) 2018 Matthew Rodusek

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

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

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

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include "detail/stat_recording_tracker.hpp" // detail::stat_recording_tracker

#include "../../utilities/allocator_info.hpp" // allocator_info
#include "../../utilities/errors.hpp"         // get_leak_handler
#include "../../utilities/macros.hpp"         // BIT_MEMORY_UNUSED

#include "../../concepts/MemoryTracker.hpp" // is_memory_tracker

#include <cstddef> // std::size_t, std::ptrdiff_t
#include <map>     // std::map

namespace bit {
  namespace memory {

    ///////////////////////////////////////////////////////////////////////////
    /// \brief This tracker watches individual allocations to determine which
    ///        allocations may be missing a corresponding deallocation
    ///
    /// \satisfies{MemoryTracker}
    ///////////////////////////////////////////////////////////////////////////
    class detailed_leak_tracker
    {
      //-----------------------------------------------------------------------
      // Tracking
      //-----------------------------------------------------------------------
    public:

      /// \brief Records an allocation of the pointer \p p with size \p bytes
      ///
      /// \param p the pointer
      /// \param bytes the size of the memory, in bytes
      /// \param align the alignment of the allocation
      void on_allocate( void* p, std::size_t bytes, std::size_t align ) noexcept;

      /// \brief Records a deallocation of the pointer \p p with size \p bytes
      ///
      /// \param info the allocator info
      /// \param p the pointer
      /// \param bytes the size of the memory, in bytes
      void on_deallocate( const allocator_info& info, void* p, std::size_t bytes ) noexcept;

      /// \brief Records all allocations being truncated into a single
      ///        deallocation
      ///
      /// This clears all open records of allocations
      void on_deallocate_all() noexcept;

      /// \brief Finalizes the leak tracker, determining any leaks that may
      ///        have occurred
      ///
      /// \param info the allocator_info for the tracker
      void finalize( const allocator_info& info );

      //-----------------------------------------------------------------------
      // Private Members
      //-----------------------------------------------------------------------
    private:

      std::map<void*,std::size_t> m_allocations;
      std::ptrdiff_t m_allocated = 0;
    };

    using stat_recording_detailed_leak_tracker = detail::stat_recording_tracker<detailed_leak_tracker>;

    static_assert( is_memory_tracker_v<detailed_leak_tracker>,
                   "detailed_leak_tracker must satisfy MemoryTracker" );
    static_assert( is_memory_tracker_v<stat_recording_detailed_leak_tracker>,
                   "stat_recording_detailed_tracker must satisfy MemoryTracker" );

  } // namespace memory
} // namespace bit

#include "detail/detailed_leak_tracker.inl"

#endif /* BIT_MEMORY_POLICIES_TRACKERS_DETAILED_LEAK_TRACKER_HPP */


text:
package aurelienribon.tweenengine;

/**
 * Base class for every paths. You can create your own paths and directly use
 * them in the Tween engine by inheriting from this class.
 *
 * @author Aurelien Ribon | http://www.aurelienribon.com/
 */
public interface TweenPath {

	/**
	 * Computes the next value of the interpolation, based on its waypoints and
	 * the current progress.
	 *
	 * @param t The progress of the interpolation, between 0 and 1. May be out
	 * of these bounds if the easing equation involves some kind of rebounds.
	 * @param points The waypoints of the tween, from start to target values.
	 * @param pointsCnt The number of valid points in the array.
	 * @return The next value of the interpolation.
	 */
	public float compute(float t, float[] points, int pointsCnt);
}


text:
<a href="<?php echo base_url();?>auth/dashboard"> Dashboard

 Recycle Bin

Posisi

Panduan

                     <button type="button" data-toggle="tooltip" title="Lihat Panduan" class="btn btn-box-tool" data-widget="collapse">
                     </button>
                     <button type="button" data-toggle="tooltip" title="Hapus Panduan" class="btn btn-box-tool" data-widget="remove"></button>

Halaman ini berisi data Posisi dan ada beberapa tombol pada halaman ini. Tombol <button type="button" class="btn btn-primary btn-xs" data-toggle="tooltip" title="Tambah Posisi">  Tambah</button> digunakan untuk menambah data Posisi, tombol  digunakan untuk merubah data Posisi dan tombol  digunakan untuk menghapus Posisi.

POSISI

                                       No
                                       Kode posisi
                                       Nama posisi
                                       Keterangan
                                       Tanggal Hapus
                                       Action

                                    <?php foreach ($posisi as $a): ?>

                                       <?php echo ++$start ?>
                                       <?php echo $a->kode_posisi?>
                                       <?php echo $a->nama_posisi?>
                                       <?php echo $a->ket_posisi?>
                                       <?php echo date('d M. Y H:i:s', strtotime($a->update_at));?>

                                             <a class="restore" href="<?php echo base_url();?>posisi/delete2/<?php echo $a->id_posisi;?>/<?php echo $a->hapus;?>">

                                    <?php endforeach ?>

                                    No
                                    Kode posisi
                                    Nama posisi
                                    Keterangan
                                    Tanggal Hapus
                                    Action

               <button type="button" class="close" data-dismiss="modal">×</button>

Form Posisi

               <form action="<?php echo base_url(); ?>posisi/create_action" id="" method="post" name="login">

                           Kode Posisi
                           <input type="text" class="form-control" placeholder="Kode Posisi" name="kode_posisi" id="nama_pegawai" value="" required/>

                           Nama Nama
                           <input type="text" class="form-control" placeholder="Nama Posisi" name="nama_posisi" id="nama_pegawai" value="" required/>

                     Keterangan
                     <textarea class="form-control" rows="3" name="ket_posisi" placeholder="Keterangan" value=""></textarea>

                     <button type="button" class="btn btn-default  pull-left" data-dismiss="modal">Tutup</button>

                  <input type="hidden" name="id_posisi" value="" />

                     <button type="submit" class="btn btn-primary" href="">Simpan</button>

            </form>

               <button type="button" class="close" data-dismiss="modal">×</button>

Form Edit Posisi

               <form action="<?php echo base_url(); ?>posisi/update_action" id="" method="post" name="login">

                           Kode
                           <input type="text" class="form-control" placeholder="Kode" name="kode_posisi2" id="nama_pegawai" value="" required/>

                           Nama
                           <input type="text" class="form-control" placeholder="Nama" name="nama_posisi2" id="nama_pegawai" value="" required/>

                     Keterangan
                     <textarea class="form-control" rows="3" name="ket_posisi2" id="ket_posisi2" placeholder="Keterangan" value=""></textarea>

                        <input type="hidden" name="id_posisi2" value="" />

                     <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Tutup</button>

                     <button type="submit" class="btn btn-primary" href="">Simpan</button>

            </form>


text:
<?php

namespace Oauth\Adapter\Oauth2;

use Oauth\Adapter\Oauth2\AbstractAdapter;
use Oauth\Service\Token\Access as AccessToken;

class Foursquare extends AbstractAdapter
{
    protected $websiteName = 'Foursquare';

    protected $authorizeUrl = "https://foursquare.com/oauth2/authorize";
    protected $accessTokenUrl = "https://foursquare.com/oauth2/access_token";

    public function accessTokenToArray(AccessToken $accessToken)
    {
        $token = parent::accessTokenToArray($accessToken);
        $expiredTime = $accessToken->getParam('expires');
        if(!isset($token['remoteUserId']) || !$token['remoteUserId']){
            $token['remoteUserId'] = $this->getRemoteUserId($token['token']);
        }
        return $token;
    }

    public function getRemoteUserId($accessToken)
    {
        $client = $this->getHttpClient();
        $client->setUri('https://api.foursquare.com/v2/users/self');
        //Foursquare use oauth_token instead of oauth_token
        $client->setParameterGet(array(
            'oauth_token' => $accessToken
        ));
        $response = $client->send();
        $data = $this->parseJsonResponse($response);
        return isset($data['response']['user']['id']) ? $data['response']['user']['id'] : null;
    }
}


text:
topic: Jekyll Stub Site
---

This site contains information about getting started with building web applications in

* Python, using Flask
* JavaScript, using Node
* Java, using SparkJava
* Ruby, using Rails

## Topics

{% for topic in site.topics %}

{{ topic.topic }}—{{topic.desc}}

{% endfor %}


text:
        All
        <button (click)="filterByWonderType($event)" id="check-all" class="btn active"></button>

        <template ngFor #wonderType [ngForOf]="wonderTypes">
          {{ wonderType }}
          <button (click)="filterByWonderType($event)" id="check-{{ wonderType | lowercase }}" attr.data-filter=".{{ wonderType | lowercase }}" class="btn" ></button>
        </template>

          <template ngFor #wonder [ngForOf]="wonders">

{{wonder.englishName}}
                  <template ngFor #nativeName [ngForOf]="wonder.nativeNames">
                    {{nativeName}}
                  </template>

{{comment.body}}

              <average-rating [averageRating]="wonder.averageRating"></average-rating>
              Details

      </template>


text:
package org.boon.tests.model;

public class HourlyEmployee extends Employee {
    int weeklyHours = 40;

}


text:
<?php

namespace spec\Prophecy\Call;

use PhpSpec\ObjectBehavior;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Argument\ArgumentsWildcard;

class CallCenterSpec extends ObjectBehavior
{
    /**
     * @param \Prophecy\Prophecy\ObjectProphecy $objectProphecy
     */
    function let($objectProphecy)
    {
    }

    /**
     * @param \Prophecy\Prophecy\ObjectProphecy    $objectProphecy
     * @param \Prophecy\Argument\ArgumentsWildcard $wildcard
     */
    function it_records_calls_made_through_makeCall_method($objectProphecy, $wildcard)
    {
        $wildcard->scoreArguments(array(5, 2, 3))->willReturn(10);
        $objectProphecy->getMethodProphecies()->willReturn(array());

        $this->makeCall($objectProphecy, 'setValues', array(5, 2, 3));

        $calls = $this->findCalls('setValues', $wildcard);
        $calls->shouldHaveCount(1);

        $calls[0]->shouldBeAnInstanceOf('Prophecy\Call\Call');
        $calls[0]->getMethodName()->shouldReturn('setValues');
        $calls[0]->getArguments()->shouldReturn(array(5, 2, 3));
        $calls[0]->getReturnValue()->shouldReturn(null);
    }

    function it_returns_null_for_any_call_through_makeCall_if_no_method_prophecies_added(
        $objectProphecy
    )
    {
        $objectProphecy->getMethodProphecies()->willReturn(array());

        $this->makeCall($objectProphecy, 'setValues', array(5, 2, 3))->shouldReturn(null);
    }

    /**
     * @param \Prophecy\Prophecy\MethodProphecy    $method1
     * @param \Prophecy\Prophecy\MethodProphecy    $method2
     * @param \Prophecy\Prophecy\MethodProphecy    $method3
     * @param \Prophecy\Argument\ArgumentsWildcard $arguments1
     * @param \Prophecy\Argument\ArgumentsWildcard $arguments2
     * @param \Prophecy\Argument\ArgumentsWildcard $arguments3
     * @param \Prophecy\Promise\PromiseInterface   $promise
     */
    function it_executes_promise_of_method_prophecy_that_matches_signature_passed_to_makeCall(
        $objectProphecy, $method1, $method2, $method3, $arguments1, $arguments2, $arguments3,
        $promise
    )
    {
        $method1->getMethodName()->willReturn('getName');
        $method1->getArgumentsWildcard()->willReturn($arguments1);
        $arguments1->scoreArguments(array('world', 'everything'))->willReturn(false);

        $method2->getMethodName()->willReturn('setTitle');
        $method2->getArgumentsWildcard()->willReturn($arguments2);
        $arguments2->scoreArguments(array('world', 'everything'))->willReturn(false);

        $method3->getMethodName()->willReturn('getName');
        $method3->getArgumentsWildcard()->willReturn($arguments3);
        $method3->getPromise()->willReturn($promise);
        $arguments3->scoreArguments(array('world', 'everything'))->willReturn(200);

        $objectProphecy->getMethodProphecies()->willReturn(array(
            'method1' => array($method1),
            'method2' => array($method2, $method3)
        ));
        $objectProphecy->getMethodProphecies('getName')->willReturn(array($method1, $method3));
        $objectProphecy->reveal()->willReturn(new \stdClass());

        $promise->execute(array('world', 'everything'), $objectProphecy->getWrappedObject(), $method3)->willReturn(42);

        $this->makeCall($objectProphecy, 'getName', array('world', 'everything'))->shouldReturn(42);

        $calls = $this->findCalls('getName', $arguments3);
        $calls->shouldHaveCount(1);
        $calls[0]->getReturnValue()->shouldReturn(42);
    }

    /**
     * @param \Prophecy\Prophecy\MethodProphecy    $method1
     * @param \Prophecy\Prophecy\MethodProphecy    $method2
     * @param \Prophecy\Prophecy\MethodProphecy    $method3
     * @param \Prophecy\Argument\ArgumentsWildcard $arguments1
     * @param \Prophecy\Argument\ArgumentsWildcard $arguments2
     * @param \Prophecy\Argument\ArgumentsWildcard $arguments3
     * @param \Prophecy\Promise\PromiseInterface   $promise
     */
    function it_executes_promise_of_method_prophecy_that_matches_with_highest_score_to_makeCall(
        $objectProphecy, $method1, $method2, $method3, $arguments1, $arguments2, $arguments3,
        $promise
    )
    {
        $method1->getMethodName()->willReturn('getName');
        $method1->getArgumentsWildcard()->willReturn($arguments1);
        $arguments1->scoreArguments(array('world', 'everything'))->willReturn(50);

        $method2->getMethodName()->willReturn('getName');
        $method2->getArgumentsWildcard()->willReturn($arguments2);
        $method2->getPromise()->willReturn($promise);
        $arguments2->scoreArguments(array('world', 'everything'))->willReturn(300);

        $method3->getMethodName()->willReturn('getName');
        $method3->getArgumentsWildcard()->willReturn($arguments3);
        $arguments3->scoreArguments(array('world', 'everything'))->willReturn(200);

        $objectProphecy->getMethodProphecies()->willReturn(array(
            'method1' => array($method1),
            'method2' => array($method2, $method3)
        ));
        $objectProphecy->getMethodProphecies('getName')->willReturn(array(
            $method1, $method2, $method3
        ));
        $objectProphecy->reveal()->willReturn(new \stdClass());

        $promise->execute(array('world', 'everything'), $objectProphecy->getWrappedObject(), $method2)
            ->willReturn('second');

        $this->makeCall($objectProphecy, 'getName', array('world', 'everything'))
            ->shouldReturn('second');
    }

    /**
     * @param \Prophecy\Prophecy\MethodProphecy    $method
     * @param \Prophecy\Argument\ArgumentsWildcard $arguments
     */
    function it_throws_exception_if_call_does_not_match_any_of_defined_method_prophecies(
        $objectProphecy, $method, $arguments
    )
    {
        $method->getMethodName()->willReturn('getName');
        $method->getArgumentsWildcard()->willReturn($arguments);
        $arguments->scoreArguments(array('world', 'everything'))->willReturn(false);
        $arguments->__toString()->willReturn('arg1, arg2');

        $objectProphecy->getMethodProphecies()->willReturn(array('method1' => array($method)));
        $objectProphecy->getMethodProphecies('getName')->willReturn(array($method));

        $this->shouldThrow('Prophecy\Exception\Call\UnexpectedCallException')
            ->duringMakeCall($objectProphecy, 'getName', array('world', 'everything'));
    }

    /**
     * @param \Prophecy\Prophecy\MethodProphecy    $method
     * @param \Prophecy\Argument\ArgumentsWildcard $arguments
     */
    function it_returns_null_if_method_prophecy_that_matches_makeCall_arguments_has_no_promise(
        $objectProphecy, $method, $arguments
    )
    {
        $method->getMethodName()->willReturn('getName');
        $method->getArgumentsWildcard()->willReturn($arguments);
        $method->getPromise()->willReturn(null);
        $arguments->scoreArguments(array('world', 'everything'))->willReturn(100);

        $objectProphecy->getMethodProphecies()->willReturn(array($method));
        $objectProphecy->getMethodProphecies('getName')->willReturn(array($method));

        $this->makeCall($objectProphecy, 'getName', array('world', 'everything'))
            ->shouldReturn(null);
    }

    /**
     * @param \Prophecy\Argument\ArgumentsWildcard $wildcard
     */
    function it_finds_recorded_calls_by_a_method_name_and_arguments_wildcard(
        $objectProphecy, $wildcard
    )
    {
        $objectProphecy->getMethodProphecies()->willReturn(array());

        $this->makeCall($objectProphecy, 'getName', array('world'));
        $this->makeCall($objectProphecy, 'getName', array('everything'));
        $this->makeCall($objectProphecy, 'setName', array(42));

        $wildcard->scoreArguments(array('world'))->willReturn(false);
        $wildcard->scoreArguments(array('everything'))->willReturn(10);

        $calls = $this->findCalls('getName', $wildcard);

        $calls->shouldHaveCount(1);
        $calls[0]->getMethodName()->shouldReturn('getName');
        $calls[0]->getArguments()->shouldReturn(array('everything'));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Sample1</string>
    <string name="contentDescription">contentDescription</string>
    <string name="nickname">昵称</string>
    <string name="hint_login_input_name">输入用户名</string>
    <string name="hint_login_password">密码</string>
    <string name="login">登陆</string>
    <string name="agree_xieyi">同意注册协议</string>
    <string name="hint_login_input_password">输入密码</string>
</resources>


text:
var should = require('should');
var toolbelt = require(__dirname+'/../index');

describe('base/has', function(){

    var has;
    var fixture = {foo:{bar:{baz:"snafu"}}};

    it('should be loadable',function(){
         has = toolbelt.pick('base/has');
         has.should.be.a('function');
    });

    it('should return false on a none valid path',function(){

        has(fixture, "foo.bar.bam").should.be.not.ok;
    });

    it('should return true on a valid path',function(){
        has(fixture,"foo.bar.baz").should.be.ok;
    });

    it('should return false if object is null',function(){
        has(null,"foo.bar.baz").should.be.not.ok;
    });
});


text:
Annotator Store
===============

This is a backend store for `Annotator <http://annotatorjs.org>`__.

The functionality can roughly be separated in two parts:

1. An abstraction layer wrapping Elasticsearch, to easily manage annotation
   storage. It features authorization to filter search results according to
   their permission settings.
2. A Flask blueprint for a web server that exposes an HTTP API to the annotation
   storage. To use this functionality, build this package with the ``[flask]``
   option.

Getting going
-------------

You'll need a recent version of `Python <http://python.org>`__ (Python 2 >=2.6
or Python 3 >=3.3) and `ElasticSearch <http://elasticsearch.org>`__ (>=1.0.0)
installed.

The quickest way to get going requires the ``pip`` and ``virtualenv``
tools (``easy_install virtualenv`` will get them both). Run the
following in the repository root::

    virtualenv pyenv
    source pyenv/bin/activate
    pip install -e .[flask]
    cp annotator.cfg.example annotator.cfg
    python run.py

You should see something like::

    * Running on http://127.0.0.1:5000/
    * Restarting with reloader...

If you wish to customize the configuration of the Annotator Store, make
your changes to ``annotator.cfg`` or dive into ``run.py``.

Additionally, the ``HOST`` and ``PORT`` environment variables override
the default socket binding of address ``127.0.0.1`` and port ``5000``.

Store API
---------

The Store API is designed to be compatible with the
`Annotator <http://okfnlabs.org/annotator>`__. The annotation store, a
JSON-speaking REST API, will be mounted at ``/api`` by default. See the
`Annotator
documentation <http://docs.annotatorjs.org/en/v1.2.x/storage.html>`__ for
details.

Running tests
-------------

We use ``nosetests`` to run tests. You can just
``pip install -e .[testing]``, ensure ElasticSearch is running, and
then::

    $ nosetests
    ......................................................................................
    ----------------------------------------------------------------------
    Ran 86 tests in 19.171s

    OK

Alternatively (and preferably), you should install
`Tox <http://tox.testrun.org/>`__, and then run ``tox``. This will run
the tests against multiple versions of Python (if you have them
installed).

Please `open an issue <http://github.com/openannotation/annotator-store/issues>`__
if you find that the tests don't all pass on your machine, making sure to include
the output of ``pip freeze``.


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>
    <style name="MyNavigationDrawerTheme" parent="MaterialNavigationDrawerTheme.Light.DarkActionBar" >
        <!-- Other customization -->
        <!--<item name="drawerColor">#37474F</item>-->
        <item name="singleAccount">true</item>
        <item name="learningPattern">false</item>
        <item name="rippleBackport">true</item>
        <item name="toolbarElevation">true</item>
    </style>

</resources>


text:
res4j (pronounce "rez for jay") allows the application to read structured, read-only files into structured Java objects in memory, a bit like the classical ResourceBundle. But res4j is much more flexible, thanks to its composite, strategy-based XML configuration.

IMPORTANT: This library is still in active development and not yet ready for production.

| Feature | ResourceBundle | res4j  |
| ------- | -------------- | ------ |
| Structure | Flat content | Structured content and even shared sub-content |
| Cache | Coarse control | Fine-grained control; Map implementation; Ehcache implementation |
| Location | Classpath | Classpath; File; URL |
| Matching | Locale; External | A generalization called Context; External (file name) or internal (XML attribute or CSV column);  Can be used to match atomic files like images |
| DAO | Properties; Flat XML | Properties; CSV; Structured XML with JAXB, SAX or hybrid parsing, XInclude |
| Data Type | String | ArrayList; LinkedHashMap; LinkedHashSet; ResourceBundle; BigDecimal; BigInteger; Boolean; Byte; byte[]; Calendar; Character; Class; Date; Double; Duration; Float; Integer; Long; Package; Short; String; URL|


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "DTD/xhtml1-strict.dtd">

    <title>elita.dataservice.JobDataService : API documentation</title>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
    <link href="apidocs.css" type="text/css" rel="stylesheet" />

e.d.JobDataService(GenericChildDataService) : class documentation

      Part of elita.dataservice

      View In Hierarchy

No class docstring

    Method
    GetAllActions
    Get all actions associated with application. Get it from root_tree
because the actions are dynamically populated at the start of each
request.

    Method
    GetAction
    Get details (name, description, parameters) about all actions associated
with application

    Method
    NewJob
    Create new job object.

    Method
    NewJobData
    Insert new job_data record. Called by async jobs to log progress. Data
inserted here can be viewed by user by polling the respective job object
endpoint.

    Method
    GetJobs
    Get all actively running jobs. Pulling from mongo could possibly be more
efficient (maybe) than using in-memory root_tree because we're querying on
the status field

    Method
    GetJobData
    Get job data for a specific job sorted by created_datetime
(ascending)

    Method
    SaveJobResults
    Called at the end of async jobs. Changes state of job object to reflect
job completion.

    Method
    NewAction
    No summary

    Method
    ExecuteAction
    Spawn async job for an action

      <invisible>

          Inherited from GenericChildDataService:

    Method
    __init__
    No summary

    Method
    populate_dependencies
    Child dataservice classes may need to access methods of siblings. This
allows parent dataservice to inject cross dependencies as needed without
generating a big reference cycle.

    Method
    NewContainer
    Create new container object suitable for a root_tree reference

    Method
    UpdateObjectFromPatch
    Generic method to update an object (document) with a JSON Patch
document

    Method
    UpdateObject
    Generic method to update a particular object (document) with the data in
doc

    Method
    AddThreadLocalRootTree
    Add new node to thread-local root_tree (copy from mongo's root_tree)

    Method
    RmThreadLocalRootTree
    Remove deleted node from thread-local root_tree

      </invisible>

    def
    GetAllActions(self, app_name):

Get all actions associated with application. Get it from root_tree
because the actions are dynamically populated at the start of each
request.

    def
    GetAction(self, app_name, action_name):

Get details (name, description, parameters) about all actions associated
with application

    def
    NewJob(self, name, job_type, data):

Create new job object.

data parameter can be anything serializable (including None) so that's
all we will check for

    def
    NewJobData(self, data):

Insert new job_data record. Called by async jobs to log progress. Data
inserted here can be viewed by user by polling the respective job object
endpoint.

Only valid to be called in an asynch context, so assert we have a valid
job_id

    def
    GetJobs(self, active):

Get all actively running jobs. Pulling from mongo could possibly be more
efficient (maybe) than using in-memory root_tree because we're querying on
the status field

    def
    GetJobData(self, job_id):

Get job data for a specific job sorted by created_datetime
(ascending)

    def
    SaveJobResults(self, results):

Called at the end of async jobs. Changes state of job object to reflect
job completion.

    def
    NewAction(self, app_name, action_name, params):

Register new dynamically-loaded action in root_tree. These are loaded
from plugins at the start of each request Note that action is added to
in-memory root_tree object (not the root_tree record in mongo) because it
is not persistent. Note further that this is *our* (meaning this thread's)
root_tree and will only be in effect for the duration of this request, so
we don't care about any root_tree updates by other threads running
concurrently

    def
    ExecuteAction(self, app_name, action_name, params):

Spawn async job for an action

    <address>
      API Documentation for elita, generated by pydoctor at 2014-10-29 15:25:55.
    </address>


text:
<?php

namespace Http\Adapter\Guzzle5\Tests;

use GuzzleHttp\Ring\Client\CurlHandler;

/**
 * @requires PHP 5.5
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class CurlHttpAdapterTest extends HttpAdapterTest
{
    /**
     * {@inheritdoc}
     */
    protected function createHandler()
    {
        return new CurlHandler();
    }
}


text:
import sys
if sys.version_info < (2, 5):
    from md5 import md5
else:
    from hashlib import md5

class AuthMethodMetaclass(type):
    register = []

    def __new__(cls, what, bases=None, dict=None):
        if 'hidden' not in dict: dict['hidden'] = False
        klass = type.__new__(cls, what, bases, dict)
        AuthMethodMetaclass.register += [klass]
        return klass

    def __unicode__(cls):
        return cls.__name__

class BaseAuthenticationMethod(object):
    hidden = True     # If hidden is set to True, the authentication method is not shown in admin interface

    @classmethod
    def get_password(cls, mail_user, password):
        """
        Returns the value of password to be used with this authentication method
        (e.g. MD5 hash of the original password)

        If the method returns None, it means that this authentication method doesn't
        use passwords stored in the app's database (e.g. uses external Kerberos auth)
        """
        return None

    @classmethod
    def authenticate(cls, mail_user, password):
        """Should return True if login is successful, False otherwise"""
        processed_password = cls.get_password(mail_user, password)
        return (processed_password is not None) and (processed_password == mail_user.internal_password)

    __metaclass__ = AuthMethodMetaclass

class MD5NameHostnamePwdAuthenticationMethod(BaseAuthenticationMethod):
    @classmethod
    def get_password(cls, mail_user, password):
        if isinstance(password, unicode):
            password = password.encode('utf-8')
        digest_base = "%s:%s" % (mail_user.internal_username.lower().replace('@', ':').encode(), password)
        return md5(digest_base).hexdigest()

class MD5AuthenticationMethod(BaseAuthenticationMethod):
    @classmethod
    def get_password(cls, mail_user, password):
        if isinstance(password, unicode):
            password = password.encode('utf-8')
        return md5(password).hexdigest()

class PlaintextAuthenticationMethod(BaseAuthenticationMethod):
    @classmethod
    def get_password(cls, mail_user, password):
        return password

try:
    import kerberos
except ImportError:
    pass
else:
    class KerberosAuthenticationMethod(BaseAuthenticationMethod):
        @classmethod
        def authenticate(cls, mail_user, password):
            mail_user = mail_user.internal_username.split("+")[-1] # Allow to have more than 1 krb-authenticated account for user
            mail_user = mail_user.split("@")
            if len(mail_user) != 2: # Failed to split to [username, domain]
                return False
            username, domain = mail_user[0], mail_user[1].upper() # Kerberos uses uppercase domains
            mail_user = "@".join((username, domain))
            try:
                result = kerberos.checkPassword(mail_user, password.encode('utf-8'), "", domain)
            except kerberos.KrbError:
                return False
            return result


text:
package mb.scopegraph.pepm16.esop15.lazy;

import java.util.Map;

import io.usethesource.capsule.Set;
import mb.scopegraph.pepm16.ILabel;
import mb.scopegraph.pepm16.IOccurrence;
import mb.scopegraph.pepm16.IScope;
import mb.scopegraph.pepm16.path.IPath;
import mb.scopegraph.pepm16.path.IScopePath;
import mb.scopegraph.regexp.IRegExpMatcher;

interface EnvL<S extends IScope, L extends ILabel, O extends IOccurrence> {

    <P extends IPath<S, L, O>> IEsopEnv<S, L, O, P> apply(Set.Immutable<O> seenI, IRegExpMatcher<L> re,
            IScopePath<S, L, O> path, IEsopEnv.Filter<S, L, O, P> filter, Map<L, IEsopEnv<S, L, O, P>> env_lCache);

}


text:
package storagebase

// Strip removes all state changes from the ReplicatedEvalResult,
// leaving only metadata behind.
//
// TODO(bdarnell): this method is insufficiently tested; there are
// no tests that fail if it becomes a no-op.
func (rResult *ReplicatedEvalResult) Strip() {
	*rResult = ReplicatedEvalResult{}
}