text:
class CBCGFileDialog;

class CBCGFDTabWnd : public CBCGTabWnd
{
public:
	CBCGFDTabWnd ()
	{
		m_pParent = NULL;
		m_bIsDlgControl = TRUE;
	}

	virtual void FireChangeActiveTab (int nNewTab);
	CBCGFileDialog*	m_pParent;

	afx_msg BOOL OnEraseBkgnd(CDC* pDC);
	DECLARE_MESSAGE_MAP()
};

/////////////////////////////////////////////////////////////////////////////
// CBCGFileDialog dialog

class BCGCONTROLBARDLLEXPORT CBCGFileDialog : public CFileDialog
{
	friend class CBCGFDTabWnd;

	DECLARE_DYNAMIC(CBCGFileDialog)

public:
	//----------------
	// Initialization:
	//----------------
	CBCGFileDialog (LPCTSTR lpszCaption,
		BOOL bNewPage,
		LPCTSTR lpszDefExt = NULL,
		LPCTSTR lpszFileName = NULL,
		DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
		LPCTSTR lpszFilter = NULL,
		CWnd* pParentWnd = NULL);
	virtual ~CBCGFileDialog ();

	void SetDlgIcon (HICON hIconBig, HICON hIconSmall = NULL);

	void SetNewImagesList (CImageList* pImagesNew)
	{
		m_pImagesNew = pImagesNew;
	}

	void SetLogoBitmap (CBitmap* pBmpLogo)
	{
		m_pBmpLogo = pBmpLogo;
	}

    //fdncred
    void SetExtraWidth(int iExtraWidth)
    {
        m_iExtraWidth = iExtraWidth;
    }

    void SetExtraHeight(int iExtraHeight)
    {
        m_iExtraHeight = iExtraHeight;
    }

	void AddNewItem (LPCTSTR lpszName, int iIconIndex);

	//---------
	// Results:
	//---------
	enum SelectedPage
	{
		BCGFileNew,
		BCGFileOpen,
		BCGFileRecent
	};

	SelectedPage GetPage () const
	{
		return m_nPage;
	}

	const CString& GetRecentFilePath () const
	{
		ASSERT (m_nPage == BCGFileRecent);
		return m_strRecentFilePath;
	}

	int GetNewItemIndex () const
	{
		ASSERT (m_nPage == BCGFileNew);
		return m_iNewItemIndex;
	}

protected:

	//------------------------
	// Internal notifications:
	//------------------------
	void OnTabSelchange ();
	void OnItemDblClick ();
	void CollectControls ();

	static LRESULT CALLBACK WindowProcNew(HWND hwnd,UINT message, WPARAM wParam, LPARAM lParam);

protected:
	//{{AFX_MSG(CBCGFileDialog)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()

	virtual void OnInitDone();

// Attributes:
public:
	static WNDPROC m_wndProc;

protected:
	CBCGFDTabWnd		m_wndTab;
	CStatic				m_wndDummy;
	CListCtrl			m_wndNewList;
	CListCtrl			m_wndRecentList;
	CList<HWND, HWND>	m_lstFDControls;

	CImageList*			m_pImagesNew;
	CImageList			m_ImagesRecent;

	CObList				m_lstNewItems;
	BOOL				m_bNewPage;
	SelectedPage		m_nPage;

	CString				m_strCaption;

	CString				m_strRecentFilePath;
	int					m_iNewItemIndex;

	CString				m_strFilter;

	CBitmap*			m_pBmpLogo;
	CRect				m_rectLogo;

	HICON				m_hIconBig;
	HICON				m_hIconSmall;

	int					m_iLogoAreaHeight;
    int                 m_iExtraWidth;
    int                 m_iExtraHeight;
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_BCGFILEDIALOG_H__6975A857_62DC_11D2_8BF2_00A0C9B05590__INCLUDED_)


text:
namespace content {

namespace {

// This class wraps a mojo::AssociatedInterfacePtr<URLLoader>. It also is a
// URLLoader implementation and delegates URLLoader calls to the wrapped loader.
class DelegatingURLLoader final : public mojom::URLLoader {
 public:
  explicit DelegatingURLLoader(mojom::URLLoaderAssociatedPtr loader)
      : binding_(this), loader_(std::move(loader)) {}
  ~DelegatingURLLoader() override {}

  void FollowRedirect() override { loader_->FollowRedirect(); }

  mojom::URLLoaderPtr CreateInterfacePtrAndBind() {
    auto p = binding_.CreateInterfacePtrAndBind();
    // This unretained pointer is safe, because |binding_| is owned by |this|
    // and the callback will never be called after |this| is destroyed.
    binding_.set_connection_error_handler(
        base::Bind(&DelegatingURLLoader::Cancel, base::Unretained(this)));
    return p;
  }

 private:
  // Called when the mojom::URLLoaderPtr in the service worker is deleted.
  void Cancel() {
    // Cancel loading as stated in url_loader.mojom.
    loader_ = nullptr;
  }

  mojo::Binding<mojom::URLLoader> binding_;
  mojom::URLLoaderAssociatedPtr loader_;

  DISALLOW_COPY_AND_ASSIGN(DelegatingURLLoader);
};

// This class wraps a mojo::InterfacePtr<URLLoaderClient>. It also is a
// URLLoaderClient implementation and delegates URLLoaderClient calls to the
// wrapped client.
class DelegatingURLLoaderClient final : public mojom::URLLoaderClient {
 public:
  explicit DelegatingURLLoaderClient(mojom::URLLoaderClientPtr client)
      : binding_(this), client_(std::move(client)) {}
  ~DelegatingURLLoaderClient() override {
    if (!completed_) {
      // Let the service worker know that the request has been canceled.
      ResourceRequestCompletionStatus status;
      status.error_code = net::ERR_ABORTED;
      client_->OnComplete(status);
    }
  }

  void OnDataDownloaded(int64_t data_length, int64_t encoded_length) override {
    client_->OnDataDownloaded(data_length, encoded_length);
  }
  void OnReceiveCachedMetadata(const std::vector<uint8_t>& data) override {
    client_->OnReceiveCachedMetadata(data);
  }
  void OnTransferSizeUpdated(int32_t transfer_size_diff) override {
    client_->OnTransferSizeUpdated(transfer_size_diff);
  }
  void OnReceiveResponse(
      const ResourceResponseHead& head,
      mojom::DownloadedTempFilePtr downloaded_file) override {
    client_->OnReceiveResponse(head, std::move(downloaded_file));
  }
  void OnReceiveRedirect(const net::RedirectInfo& redirect_info,
                         const ResourceResponseHead& head) override {
    client_->OnReceiveRedirect(redirect_info, head);
  }
  void OnStartLoadingResponseBody(
      mojo::ScopedDataPipeConsumerHandle body) override {
    client_->OnStartLoadingResponseBody(std::move(body));
  }
  void OnComplete(
      const ResourceRequestCompletionStatus& completion_status) override {
    client_->OnComplete(completion_status);
    completed_ = true;
  }

  void Bind(mojom::URLLoaderClientAssociatedPtrInfo* ptr_info,
            mojo::AssociatedGroup* associated_group) {
    binding_.Bind(ptr_info, associated_group);
  }

 private:
  mojo::AssociatedBinding<mojom::URLLoaderClient> binding_;
  mojom::URLLoaderClientPtr client_;
  bool completed_ = false;

  DISALLOW_COPY_AND_ASSIGN(DelegatingURLLoaderClient);
};

using EventType = ServiceWorkerMetrics::EventType;
EventType ResourceTypeToEventType(ResourceType resource_type) {
  switch (resource_type) {
    case RESOURCE_TYPE_MAIN_FRAME:
      return EventType::FETCH_MAIN_FRAME;
    case RESOURCE_TYPE_SUB_FRAME:
      return EventType::FETCH_SUB_FRAME;
    case RESOURCE_TYPE_SHARED_WORKER:
      return EventType::FETCH_SHARED_WORKER;
    case RESOURCE_TYPE_SERVICE_WORKER:
    case RESOURCE_TYPE_LAST_TYPE:
      NOTREACHED() << resource_type;
      return EventType::FETCH_SUB_RESOURCE;
    default:
      return EventType::FETCH_SUB_RESOURCE;
  }
}

std::unique_ptr<base::Value> NetLogServiceWorkerStatusCallback(
    ServiceWorkerStatusCode status,
    net::NetLogCaptureMode) {
  std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
  dict->SetString("status", ServiceWorkerStatusToString(status));
  return std::move(dict);
}

std::unique_ptr<base::Value> NetLogFetchEventCallback(
    ServiceWorkerStatusCode status,
    ServiceWorkerFetchEventResult result,
    net::NetLogCaptureMode) {
  std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
  dict->SetString("status", ServiceWorkerStatusToString(status));
  dict->SetBoolean("has_response",
                   result == SERVICE_WORKER_FETCH_EVENT_RESULT_RESPONSE);
  return std::move(dict);
}

void EndNetLogEventWithServiceWorkerStatus(const net::NetLogWithSource& net_log,
                                           net::NetLogEventType type,
                                           ServiceWorkerStatusCode status) {
  net_log.EndEvent(type,
                   base::Bind(&NetLogServiceWorkerStatusCallback, status));
}

ServiceWorkerMetrics::EventType FetchTypeToWaitUntilEventType(
    ServiceWorkerFetchType type) {
  if (type == ServiceWorkerFetchType::FOREIGN_FETCH)
    return ServiceWorkerMetrics::EventType::FOREIGN_FETCH_WAITUNTIL;
  return ServiceWorkerMetrics::EventType::FETCH_WAITUNTIL;
}

}  // namespace

// Helper to receive the fetch event response even if
// ServiceWorkerFetchDispatcher has been destroyed.
class ServiceWorkerFetchDispatcher::ResponseCallback {
 public:
  ResponseCallback(base::WeakPtr<ServiceWorkerFetchDispatcher> fetch_dispatcher,
                   ServiceWorkerVersion* version)
      : fetch_dispatcher_(fetch_dispatcher), version_(version) {}

  void Run(int request_id,
           ServiceWorkerFetchEventResult fetch_result,
           const ServiceWorkerResponse& response,
           base::Time dispatch_event_time) {
    const bool handled =
        (fetch_result == SERVICE_WORKER_FETCH_EVENT_RESULT_RESPONSE);
    if (!version_->FinishRequest(request_id, handled, dispatch_event_time))
      NOTREACHED() << "Should only receive one reply per event";

    // |fetch_dispatcher| is null if the URLRequest was killed.
    if (fetch_dispatcher_)
      fetch_dispatcher_->DidFinish(request_id, fetch_result, response);
  }

 private:
  base::WeakPtr<ServiceWorkerFetchDispatcher> fetch_dispatcher_;
  // Owns |this|.
  ServiceWorkerVersion* version_;

  DISALLOW_COPY_AND_ASSIGN(ResponseCallback);
};

// This class keeps the URL loader related assets alive while the FetchEvent is
// ongoing in the service worker.
class ServiceWorkerFetchDispatcher::URLLoaderAssets
    : public base::RefCounted<ServiceWorkerFetchDispatcher::URLLoaderAssets> {
 public:
  URLLoaderAssets(mojom::URLLoaderFactoryPtr url_loader_factory,
                  std::unique_ptr<mojom::URLLoader> url_loader,
                  std::unique_ptr<mojom::URLLoaderClient> url_loader_client)
      : url_loader_factory_(std::move(url_loader_factory)),
        url_loader_(std::move(url_loader)),
        url_loader_client_(std::move(url_loader_client)) {}

 private:
  friend class base::RefCounted<URLLoaderAssets>;
  virtual ~URLLoaderAssets() {}

  mojom::URLLoaderFactoryPtr url_loader_factory_;
  std::unique_ptr<mojom::URLLoader> url_loader_;
  std::unique_ptr<mojom::URLLoaderClient> url_loader_client_;

  DISALLOW_COPY_AND_ASSIGN(URLLoaderAssets);
};

ServiceWorkerFetchDispatcher::ServiceWorkerFetchDispatcher(
    std::unique_ptr<ServiceWorkerFetchRequest> request,
    ServiceWorkerVersion* version,
    ResourceType resource_type,
    const base::Optional<base::TimeDelta>& timeout,
    const net::NetLogWithSource& net_log,
    const base::Closure& prepare_callback,
    const FetchCallback& fetch_callback)
    : version_(version),
      net_log_(net_log),
      prepare_callback_(prepare_callback),
      fetch_callback_(fetch_callback),
      request_(std::move(request)),
      resource_type_(resource_type),
      timeout_(timeout),
      did_complete_(false),
      weak_factory_(this) {
  net_log_.BeginEvent(net::NetLogEventType::SERVICE_WORKER_DISPATCH_FETCH_EVENT,
                      net::NetLog::StringCallback(
                          "event_type", ServiceWorkerMetrics::EventTypeToString(
                                            GetEventType())));
}

ServiceWorkerFetchDispatcher::~ServiceWorkerFetchDispatcher() {
  if (!did_complete_)
    net_log_.EndEvent(
        net::NetLogEventType::SERVICE_WORKER_DISPATCH_FETCH_EVENT);
}

void ServiceWorkerFetchDispatcher::Run() {
  DCHECK(version_->status() == ServiceWorkerVersion::ACTIVATING ||
         version_->status() == ServiceWorkerVersion::ACTIVATED)
      << version_->status();

  if (version_->status() == ServiceWorkerVersion::ACTIVATING) {
    net_log_.BeginEvent(
        net::NetLogEventType::SERVICE_WORKER_WAIT_FOR_ACTIVATION);
    version_->RegisterStatusChangeCallback(
        base::Bind(&ServiceWorkerFetchDispatcher::DidWaitForActivation,
                   weak_factory_.GetWeakPtr()));
    return;
  }
  StartWorker();
}

void ServiceWorkerFetchDispatcher::DidWaitForActivation() {
  net_log_.EndEvent(net::NetLogEventType::SERVICE_WORKER_WAIT_FOR_ACTIVATION);
  StartWorker();
}

void ServiceWorkerFetchDispatcher::StartWorker() {
  // We might be REDUNDANT if a new worker started activating and kicked us out
  // before we could finish activation.
  if (version_->status() != ServiceWorkerVersion::ACTIVATED) {
    DCHECK_EQ(ServiceWorkerVersion::REDUNDANT, version_->status());
    DidFail(SERVICE_WORKER_ERROR_ACTIVATE_WORKER_FAILED);
    return;
  }

  if (version_->running_status() == EmbeddedWorkerStatus::RUNNING) {
    DispatchFetchEvent();
    return;
  }

  net_log_.BeginEvent(net::NetLogEventType::SERVICE_WORKER_START_WORKER);
  version_->RunAfterStartWorker(
      GetEventType(), base::Bind(&ServiceWorkerFetchDispatcher::DidStartWorker,
                                 weak_factory_.GetWeakPtr()),
      base::Bind(&ServiceWorkerFetchDispatcher::DidFailToStartWorker,
                 weak_factory_.GetWeakPtr()));
}

void ServiceWorkerFetchDispatcher::DidStartWorker() {
  net_log_.EndEvent(net::NetLogEventType::SERVICE_WORKER_START_WORKER);
  DispatchFetchEvent();
}

void ServiceWorkerFetchDispatcher::DidFailToStartWorker(
    ServiceWorkerStatusCode status) {
  EndNetLogEventWithServiceWorkerStatus(
      net_log_, net::NetLogEventType::SERVICE_WORKER_START_WORKER, status);
  DidFail(status);
}

void ServiceWorkerFetchDispatcher::DispatchFetchEvent() {
  DCHECK_EQ(EmbeddedWorkerStatus::RUNNING, version_->running_status())
      << "Worker stopped too soon after it was started.";

  DCHECK(!prepare_callback_.is_null());
  base::Closure prepare_callback = prepare_callback_;
  prepare_callback.Run();

  net_log_.BeginEvent(net::NetLogEventType::SERVICE_WORKER_FETCH_EVENT);
  int fetch_event_id;
  int event_finish_id;
  if (timeout_) {
    fetch_event_id = version_->StartRequestWithCustomTimeout(
        GetEventType(),
        base::Bind(&ServiceWorkerFetchDispatcher::DidFailToDispatch,
                   weak_factory_.GetWeakPtr()),
        *timeout_, ServiceWorkerVersion::CONTINUE_ON_TIMEOUT);
    event_finish_id = version_->StartRequestWithCustomTimeout(
        FetchTypeToWaitUntilEventType(request_->fetch_type),
        base::Bind(&ServiceWorkerUtils::NoOpStatusCallback), *timeout_,
        ServiceWorkerVersion::CONTINUE_ON_TIMEOUT);
  } else {
    fetch_event_id = version_->StartRequest(
        GetEventType(),
        base::Bind(&ServiceWorkerFetchDispatcher::DidFailToDispatch,
                   weak_factory_.GetWeakPtr()));
    event_finish_id = version_->StartRequest(
        FetchTypeToWaitUntilEventType(request_->fetch_type),
        base::Bind(&ServiceWorkerUtils::NoOpStatusCallback));
  }

  ResponseCallback* response_callback =
      new ResponseCallback(weak_factory_.GetWeakPtr(), version_.get());
  version_->RegisterRequestCallback<ServiceWorkerHostMsg_FetchEventResponse>(
      fetch_event_id,
      base::Bind(&ServiceWorkerFetchDispatcher::ResponseCallback::Run,
                 base::Owned(response_callback)));

  // |event_dispatcher| is owned by |version_|. So it is safe to pass the
  // unretained raw pointer of |version_| to OnFetchEventFinished callback.
  // Pass |url_loader_assets_| to the callback to keep the URL loader related
  // assets alive while the FetchEvent is ongoing in the service worker.
  version_->event_dispatcher()->DispatchFetchEvent(
      fetch_event_id, *request_, std::move(preload_handle_),
      base::Bind(&ServiceWorkerFetchDispatcher::OnFetchEventFinished,
                 base::Unretained(version_.get()), event_finish_id,
                 url_loader_assets_));
}

void ServiceWorkerFetchDispatcher::DidFailToDispatch(
    ServiceWorkerStatusCode status) {
  EndNetLogEventWithServiceWorkerStatus(
      net_log_, net::NetLogEventType::SERVICE_WORKER_FETCH_EVENT, status);
  DidFail(status);
}

void ServiceWorkerFetchDispatcher::DidFail(ServiceWorkerStatusCode status) {
  DCHECK_NE(SERVICE_WORKER_OK, status);
  Complete(status, SERVICE_WORKER_FETCH_EVENT_RESULT_FALLBACK,
           ServiceWorkerResponse());
}

void ServiceWorkerFetchDispatcher::DidFinish(
    int request_id,
    ServiceWorkerFetchEventResult fetch_result,
    const ServiceWorkerResponse& response) {
  net_log_.EndEvent(net::NetLogEventType::SERVICE_WORKER_FETCH_EVENT);
  Complete(SERVICE_WORKER_OK, fetch_result, response);
}

void ServiceWorkerFetchDispatcher::Complete(
    ServiceWorkerStatusCode status,
    ServiceWorkerFetchEventResult fetch_result,
    const ServiceWorkerResponse& response) {
  DCHECK(!fetch_callback_.is_null());

  did_complete_ = true;
  net_log_.EndEvent(
      net::NetLogEventType::SERVICE_WORKER_DISPATCH_FETCH_EVENT,
      base::Bind(&NetLogFetchEventCallback, status, fetch_result));

  FetchCallback fetch_callback = fetch_callback_;
  scoped_refptr<ServiceWorkerVersion> version = version_;
  fetch_callback.Run(status, fetch_result, response, version);
}

bool ServiceWorkerFetchDispatcher::MaybeStartNavigationPreload(
    net::URLRequest* original_request) {
  if (resource_type_ != RESOURCE_TYPE_MAIN_FRAME &&
      resource_type_ != RESOURCE_TYPE_SUB_FRAME) {
    return false;
  }
  if (!version_->navigation_preload_state().enabled)
    return false;
  // TODO(horo): Currently NavigationPreload doesn't support request body.
  if (!request_->blob_uuid.empty())
    return false;

  ServiceWorkerVersion::NavigationPreloadSupportStatus support_status =
      version_->GetNavigationPreloadSupportStatus();
  if (support_status !=
      ServiceWorkerVersion::NavigationPreloadSupportStatus::SUPPORTED) {
    return false;
  }

  ResourceRequestInfoImpl* original_info =
      ResourceRequestInfoImpl::ForRequest(original_request);
  ResourceRequesterInfo* requester_info = original_info->requester_info();
  if (IsBrowserSideNavigationEnabled()) {
    DCHECK(requester_info->IsBrowserSideNavigation());
  } else {
    DCHECK(requester_info->IsRenderer());
    if (!requester_info->filter())
      return false;
  }

  DCHECK(!url_loader_assets_);

  mojom::URLLoaderFactoryPtr url_loader_factory;
  URLLoaderFactoryImpl::Create(
      ResourceRequesterInfo::CreateForNavigationPreload(requester_info),
      mojo::MakeRequest(&url_loader_factory));

  preload_handle_ = mojom::FetchEventPreloadHandle::New();

  ResourceRequest request;
  request.method = original_request->method();
  request.url = original_request->url();
  // TODO(horo): Set first_party_for_cookies to support Same-site Cookies.
  request.request_initiator = original_request->initiator().has_value()
                                  ? original_request->initiator()
                                  : url::Origin(original_request->url());
  request.referrer = GURL(original_request->referrer());
  request.referrer_policy = original_info->GetReferrerPolicy();
  request.visibility_state = original_info->GetVisibilityState();
  request.load_flags = original_request->load_flags();
  // Set to SUB_RESOURCE because we shouldn't trigger NavigationResourceThrottle
  // for the service worker navigation preload request.
  request.resource_type = RESOURCE_TYPE_SUB_RESOURCE;
  request.priority = original_request->priority();
  request.skip_service_worker = SkipServiceWorker::ALL;
  request.do_not_prompt_for_login = true;
  request.render_frame_id = original_info->GetRenderFrameID();
  request.is_main_frame = original_info->IsMainFrame();
  request.parent_is_main_frame = original_info->ParentIsMainFrame();

  DCHECK(net::HttpUtil::IsValidHeaderValue(
      version_->navigation_preload_state().header));
  ServiceWorkerMetrics::RecordNavigationPreloadRequestHeaderSize(
      version_->navigation_preload_state().header.length());
  request.headers = "Service-Worker-Navigation-Preload: " +
                    version_->navigation_preload_state().header;

  const int request_id = ResourceDispatcherHostImpl::Get()->MakeRequestID();
  DCHECK_LT(request_id, -1);

  preload_handle_ = mojom::FetchEventPreloadHandle::New();
  mojom::URLLoaderClientPtr url_loader_client_ptr;
  preload_handle_->url_loader_client_request =
      mojo::MakeRequest(&url_loader_client_ptr);
  auto url_loader_client = base::MakeUnique<DelegatingURLLoaderClient>(
      std::move(url_loader_client_ptr));
  mojom::URLLoaderClientAssociatedPtrInfo url_loader_client_associated_ptr_info;
  url_loader_client->Bind(&url_loader_client_associated_ptr_info,
                          url_loader_factory.associated_group());
  mojom::URLLoaderAssociatedPtr url_loader_associated_ptr;

  url_loader_factory->CreateLoaderAndStart(
      mojo::MakeRequest(&url_loader_associated_ptr,
                        url_loader_factory.associated_group()),
      original_info->GetRouteID(), request_id, request,
      std::move(url_loader_client_associated_ptr_info));

  std::unique_ptr<DelegatingURLLoader> url_loader(
      base::MakeUnique<DelegatingURLLoader>(
          std::move(url_loader_associated_ptr)));
  preload_handle_->url_loader = url_loader->CreateInterfacePtrAndBind();
  url_loader_assets_ =
      new URLLoaderAssets(std::move(url_loader_factory), std::move(url_loader),
                          std::move(url_loader_client));
  return true;
}

ServiceWorkerMetrics::EventType ServiceWorkerFetchDispatcher::GetEventType()
    const {
  if (request_->fetch_type == ServiceWorkerFetchType::FOREIGN_FETCH)
    return ServiceWorkerMetrics::EventType::FOREIGN_FETCH;
  return ResourceTypeToEventType(resource_type_);
}

// static
void ServiceWorkerFetchDispatcher::OnFetchEventFinished(
    ServiceWorkerVersion* version,
    int event_finish_id,
    scoped_refptr<URLLoaderAssets> url_loader_assets,
    ServiceWorkerStatusCode status,
    base::Time dispatch_event_time) {
  version->FinishRequest(event_finish_id, status != SERVICE_WORKER_ERROR_ABORT,
                         dispatch_event_time);
}

}  // namespace content

redpajama_set_name: RedPajamaGithub


text:
import { AppContext } from '../app';
import { Ajax } from '../base/ajax';

export interface IXLSXColumn {
  name: string;
  type: 'string' | 'float' | 'int' | 'date' | 'boolean';
}

export interface IXLSXSheet {
  title: string;
  columns: IXLSXColumn[];
  rows: { [key: string]: string | number | Date | boolean | null }[];
}

export interface IXLSXJSONFile {
  sheets: IXLSXSheet[];
}

export class XlsxUtils {
  static xlsx2json(file: File): Promise<IXLSXJSONFile> {
    const data = new FormData();
    data.set('file', file);

    return AppContext.getInstance().sendAPI('/tdp/xlsx/to_json', data, 'POST');
  }

  static xlsx2jsonArray(file: File): Promise<any[][]> {
    const data = new FormData();
    data.set('file', file);

    return AppContext.getInstance().sendAPI('/tdp/xlsx/to_json_array', data, 'POST');
  }

  static json2xlsx(file: IXLSXJSONFile): Promise<Blob> {
    return Ajax.send(AppContext.getInstance().api2absURL('/tdp/xlsx/from_json'), file, 'POST', 'blob', 'application/json');
  }

  static jsonArray2xlsx(file: any[][]): Promise<Blob> {
    return Ajax.send(AppContext.getInstance().api2absURL('/tdp/xlsx/from_json_array'), file, 'POST', 'blob', 'application/json');
  }
}


text:
using NodaTime.Utility;

namespace NodaTime.TimeZones
{
    /// <summary>
    ///  Provides a <see cref="DateTimeZone"/> wrapper class that implements a simple cache to
    ///  speed up the lookup of transitions.
    /// </summary>
    /// <remarks>
    /// <para>
    /// The cache supports mulTiple caching strategies which are implemented in nested subclasses of
    /// this one. Until we have a better sense of what the usage behavior is, we cannot tune the
    /// cache. It is possible that we may support multiple strategies selectable at runtime so the
    /// user can tune the performance based on their knowledge of how they are using the system.
    /// </para>
    /// <para>
    /// In fact, only one cache type is currently implemented: an MRU cache existed before
    /// the GetZoneIntervalPair call was created in DateTimeZone, but as it wasn't being used, it
    /// was more effort than it was worth to update. The mechanism is still available for future
    /// expansion though.
    /// </para>
    /// </remarks>
    internal sealed class CachedDateTimeZone : DateTimeZone
    {
        private readonly IZoneIntervalMap map;

        /// <summary>
        /// Gets the cached time zone.
        /// </summary>
        /// <value>The time zone.</value>
        internal DateTimeZone TimeZone { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="CachedDateTimeZone"/> class.
        /// </summary>
        /// <param name="timeZone">The time zone to cache.</param>
        /// <param name="map">The caching map</param>
        private CachedDateTimeZone(DateTimeZone timeZone, IZoneIntervalMap map) : base(timeZone.Id, false, timeZone.MinOffset, timeZone.MaxOffset)
        {
            this.TimeZone = timeZone;
            this.map = map;
        }

        /// <summary>
        /// Returns a cached time zone for the given time zone.
        /// </summary>
        /// <remarks>
        /// If the time zone is already cached or it is fixed then it is returned unchanged.
        /// </remarks>
        /// <param name="timeZone">The time zone to cache.</param>
        /// <returns>The cached time zone.</returns>
        internal static DateTimeZone ForZone(DateTimeZone timeZone)
        {
            Preconditions.CheckNotNull(timeZone, nameof(timeZone));
            if (timeZone is CachedDateTimeZone || timeZone.IsFixed)
            {
                return timeZone;
            }
            return new CachedDateTimeZone(timeZone, CachingZoneIntervalMap.CacheMap(timeZone));
        }

        /// <summary>
        /// Delegates fetching a zone interval to the caching map.
        /// </summary>
        public override ZoneInterval GetZoneInterval(Instant instant)
        {
            return map.GetZoneInterval(instant);
        }
    }
}


text:
COIN=${1:-mudcoin}

./shutdown.sh ${COIN}
docker rmi beirdo/coinnode:${COIN}
cd ${HOME}/src/coin-buildimage/node
sudo -u ${USER} git pull
sudo -u ${USER} make ${COIN}-node-pool


text:
<?xml version="1.0"?>

<iati-activities version="xx">
  <iati-activity> <!-- at least 1 -->
    <iati-identifier></iati-identifier>  <!-- 1 and only 1-->
    <reporting-org type="xx" ref="xx"><narrative>Organisation name</narrative></reporting-org> <!-- 1 and only 1-->
    <title> <!-- 1 and only 1-->
      <narrative>Xxxxxxx</narrative> <!-- At least 1-->
    </title>
    <description>
      <narrative>Xxxxxxx</narrative> <!-- At least 1-->
    </description>
    <participating-org role="xx"></participating-org> <!-- At least 1-->
    <!--<other-identifier></other-identifier>-->
    <activity-status code="xx"/> <!-- 1 and only 1-->
    <activity-date type="xx" iso-date="2013-11-27"/><!-- At least 1 --> <!--Narative allowed-->

    <crs-add>
      <loan-terms>

        <repayment-first-date iso-date="2014-011"/>

      </loan-terms>
    </crs-add>

  </iati-activity>
</iati-activities>


text:
StubWebView::StubWebView(const std::string& id) : id_(id) {}

StubWebView::~StubWebView() {}

std::string StubWebView::GetId() {
  return id_;
}

bool StubWebView::WasCrashed() {
  return false;
}

Status StubWebView::ConnectIfNecessary() {
  return Status(kOk);
}

Status StubWebView::HandleReceivedEvents() {
  return Status(kOk);
}

Status StubWebView::GetUrl(std::string* url) {
  return Status(kOk);
}

Status StubWebView::Load(const std::string& url, const Timeout* timeout) {
  return Status(kOk);
}

Status StubWebView::Reload(const Timeout* timeout) {
  return Status(kOk);
}

Status StubWebView::TraverseHistory(int delta, const Timeout* timeout) {
  return Status(kOk);
}

Status StubWebView::EvaluateScript(const std::string& frame,
                                   const std::string& function,
                                   std::unique_ptr<base::Value>* result) {
  return Status(kOk);
}

Status StubWebView::CallFunction(const std::string& frame,
                                 const std::string& function,
                                 const base::ListValue& args,
                                 std::unique_ptr<base::Value>* result) {
  return Status(kOk);
}

Status StubWebView::CallAsyncFunction(const std::string& frame,
                                      const std::string& function,
                                      const base::ListValue& args,
                                      const base::TimeDelta& timeout,
                                      std::unique_ptr<base::Value>* result) {
  return Status(kOk);
}

Status StubWebView::CallUserAsyncFunction(
    const std::string& frame,
    const std::string& function,
    const base::ListValue& args,
    const base::TimeDelta& timeout,
    std::unique_ptr<base::Value>* result) {
  return Status(kOk);
}

Status StubWebView::GetFrameByFunction(const std::string& frame,
                                       const std::string& function,
                                       const base::ListValue& args,
                                       std::string* out_frame) {
  return Status(kOk);
}

Status StubWebView::DispatchMouseEvents(const std::list<MouseEvent>& events,
                                        const std::string& frame) {
  return Status(kOk);
}

Status StubWebView::DispatchTouchEvent(const TouchEvent& event) {
  return Status(kOk);
}

Status StubWebView::DispatchTouchEvents(const std::list<TouchEvent>& events) {
  return Status(kOk);
}

Status StubWebView::DispatchKeyEvents(const std::list<KeyEvent>& events) {
  return Status(kOk);
}

Status StubWebView::GetCookies(std::unique_ptr<base::ListValue>* cookies) {
  return Status(kOk);
}

Status StubWebView::DeleteCookie(const std::string& name,
                                 const std::string& url) {
  return Status(kOk);
}

Status StubWebView::WaitForPendingNavigations(const std::string& frame_id,
                                              const Timeout& timeout,
                                              bool stop_load_on_timeout) {
  return Status(kOk);
}

Status StubWebView::IsPendingNavigation(const std::string& frame_id,
                                        const Timeout* timeout,
                                        bool* is_pending) {
  return Status(kOk);
}

JavaScriptDialogManager* StubWebView::GetJavaScriptDialogManager() {
  return NULL;
}

Status StubWebView::OverrideGeolocation(const Geoposition& geoposition) {
  return Status(kOk);
}

Status StubWebView::OverrideNetworkConditions(
    const NetworkConditions& network_conditions) {
  return Status(kOk);
}

Status StubWebView::CaptureScreenshot(std::string* screenshot) {
  return Status(kOk);
}

Status StubWebView::SetFileInputFiles(
    const std::string& frame,
    const base::DictionaryValue& element,
    const std::vector<base::FilePath>& files) {
  return Status(kOk);
}

Status StubWebView::TakeHeapSnapshot(std::unique_ptr<base::Value>* snapshot) {
  return Status(kOk);
}

Status StubWebView::StartProfile() {
  return Status(kOk);
}

Status StubWebView::EndProfile(std::unique_ptr<base::Value>* profile_data) {
  return Status(kOk);
}

Status StubWebView::SynthesizeTapGesture(int x,
                                         int y,
                                         int tap_count,
                                         bool is_long_press) {
  return Status(kOk);
}

Status StubWebView::SynthesizeScrollGesture(int x,
                                            int y,
                                            int xoffset,
                                            int yoffset) {
  return Status(kOk);
}

Status StubWebView::SynthesizePinchGesture(int x, int y, double scale_factor) {
  return Status(kOk);
}


text:
package com.eatthepath.pushy.apns.server;

import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.ssl.SslContext;

import javax.net.ssl.SSLSession;

/**
 * A simple HTTP/2 server designed to crudely emulate the behavior of a real APNs server as simply and quickly as
 * possible. Benchmark servers always accept notifications, regardless of whether they are legal or
 * well-formed, and always include the same {@code apns-id} header for any given connection. These behaviors
 * minimize the processing time consumed by the server, reducing the chances that benchmarks are measuring the
 * performance of the mock server instead of the performance of the client.
 *
 * @since 0.13.0
 */
public class BenchmarkApnsServer extends BaseHttp2Server {

    private final int maxConcurrentStreams;

    BenchmarkApnsServer(final SslContext sslContext, final EventLoopGroup eventLoopGroup, final int maxConcurrentStreams) {
        super(sslContext, eventLoopGroup);

        this.maxConcurrentStreams = maxConcurrentStreams;
    }

    @Override
    protected void addHandlersToPipeline(final SSLSession sslSession, final ChannelPipeline pipeline) {
        pipeline.addLast(new BenchmarkApnsServerHandler.BenchmarkApnsServerHandlerBuilder()
                .initialSettings(Http2Settings.defaultSettings().maxConcurrentStreams(this.maxConcurrentStreams))
                .build());
    }
}


text:
<?php

/**
 * Entity type model
 *
 * @method Mage_Eav_Model_Resource_Entity_Type _getResource()
 * @method Mage_Eav_Model_Resource_Entity_Type getResource()
 * @method Mage_Eav_Model_Entity_Type setEntityTypeCode(string $value)
 * @method string getEntityModel()
 * @method Mage_Eav_Model_Entity_Type setEntityModel(string $value)
 * @method Mage_Eav_Model_Entity_Type setAttributeModel(string $value)
 * @method Mage_Eav_Model_Entity_Type setEntityTable(string $value)
 * @method Mage_Eav_Model_Entity_Type setValueTablePrefix(string $value)
 * @method Mage_Eav_Model_Entity_Type setEntityIdField(string $value)
 * @method int getIsDataSharing()
 * @method Mage_Eav_Model_Entity_Type setIsDataSharing(int $value)
 * @method string getDataSharingKey()
 * @method Mage_Eav_Model_Entity_Type setDataSharingKey(string $value)
 * @method Mage_Eav_Model_Entity_Type setDefaultAttributeSetId(int $value)
 * @method string getIncrementModel()
 * @method Mage_Eav_Model_Entity_Type setIncrementModel(string $value)
 * @method int getIncrementPerStore()
 * @method Mage_Eav_Model_Entity_Type setIncrementPerStore(int $value)
 * @method int getIncrementPadLength()
 * @method Mage_Eav_Model_Entity_Type setIncrementPadLength(int $value)
 * @method string getIncrementPadChar()
 * @method Mage_Eav_Model_Entity_Type setIncrementPadChar(string $value)
 * @method string getAdditionalAttributeTable()
 * @method Mage_Eav_Model_Entity_Type setAdditionalAttributeTable(string $value)
 * @method Mage_Eav_Model_Entity_Type setEntityAttributeCollection(string $value)
 *
 * @category    Mage
 * @package     Mage_Eav
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Eav_Model_Entity_Type extends Mage_Core_Model_Abstract
{
    /**
     * Collection of attributes
     *
     * @var Mage_Eav_Model_Mysql4_Entity_Attribute_Collection
     */
    protected $_attributes;

    /**
     * Array of attributes
     *
     * @var array
     */
    protected $_attributesBySet             = array();

    /**
     * Collection of sets
     *
     * @var Mage_Eav_Model_Mysql4_Entity_Attribute_Set_Collection
     */
    protected $_sets;

    /**
     * Resource initialization
     */
    protected function _construct()
    {
        $this->_init('eav/entity_type');
    }

    /**
     * Load type by code
     *
     * @param string $code
     * @return Mage_Eav_Model_Entity_Type
     */
    public function loadByCode($code)
    {
        $this->_getResource()->loadByCode($this, $code);
        $this->_afterLoad();
        return $this;
    }

    /**
     * Retrieve entity type attributes collection
     *
     * @param   int $setId
     * @return  Mage_Eav_Model_Mysql4_Entity_Attribute_Collection
     */
    public function getAttributeCollection($setId = null)
    {
        if ($setId === null) {
            if ($this->_attributes === null) {
                $this->_attributes = $this->_getAttributeCollection()
                    ->setEntityTypeFilter($this);
            }
            $collection = $this->_attributes;
        } else {
            if (!isset($this->_attributesBySet[$setId])) {
                $this->_attributesBySet[$setId] = $this->_getAttributeCollection()
                    ->setEntityTypeFilter($this)
                    ->setAttributeSetFilter($setId);
            }
            $collection = $this->_attributesBySet[$setId];
        }

        return $collection;
    }

    /**
     * Init and retreive attribute collection
     *
     * @return Mage_Eav_Model_Mysql4_Entity_Attribute_Collection
     */
    protected function _getAttributeCollection()
    {
        $collection = Mage::getModel('eav/entity_attribute')->getCollection();
        $objectsModel = $this->getAttributeModel();
        if ($objectsModel) {
            $collection->setModel($objectsModel);
        }

        return $collection;
    }

    /**
     * Retrieve entity tpe sets collection
     *
     * @return Mage_Eav_Model_Mysql4_Entity_Attribute_Set_Collection
     */
    public function getAttributeSetCollection()
    {
        if (empty($this->_sets)) {
            $this->_sets = Mage::getModel('eav/entity_attribute_set')->getResourceCollection()
                ->setEntityTypeFilter($this->getId());
        }
        return $this->_sets;
    }

    /**
     * Retreive new incrementId
     *
     * @param int $storeId
     * @return string
     * @throws Exception
     */
    public function fetchNewIncrementId($storeId = null)
    {
        if (!$this->getIncrementModel()) {
            return false;
        }

        if (!$this->getIncrementPerStore() || ($storeId === null)) {
            /**
             * store_id null we can have for entity from removed store
             */
            $storeId = 0;
        }

        // Start transaction to run SELECT ... FOR UPDATE
        $this->_getResource()->beginTransaction();

        try {
            $entityStoreConfig = Mage::getModel('eav/entity_store')
                ->loadByEntityStore($this->getId(), $storeId);

            if (!$entityStoreConfig->getId()) {
                $entityStoreConfig
                    ->setEntityTypeId($this->getId())
                    ->setStoreId($storeId)
                    ->setIncrementPrefix($storeId)
                    ->save();
            }

            $incrementInstance = Mage::getModel($this->getIncrementModel())
                ->setPrefix($entityStoreConfig->getIncrementPrefix())
                ->setPadLength($this->getIncrementPadLength())
                ->setPadChar($this->getIncrementPadChar())
                ->setLastId($entityStoreConfig->getIncrementLastId())
                ->setEntityTypeId($entityStoreConfig->getEntityTypeId())
                ->setStoreId($entityStoreConfig->getStoreId());

            /**
             * do read lock on eav/entity_store to solve potential timing issues
             * (most probably already done by beginTransaction of entity save)
             */
            $incrementId = $incrementInstance->getNextId();
            $entityStoreConfig->setIncrementLastId($incrementId);
            $entityStoreConfig->save();

            // Commit increment_last_id changes
            $this->_getResource()->commit();
        } catch (Exception $e) {
            $this->_getResource()->rollBack();
            throw $e;
        }

        return $incrementId;
    }

    /**
     * Retreive entity id field
     *
     * @return string|null
     */
    public function getEntityIdField()
    {
        return isset($this->_data['entity_id_field']) ? $this->_data['entity_id_field'] : null;
    }

    /**
     * Retreive entity table name
     *
     * @return string|null
     */
    public function getEntityTable()
    {
        return isset($this->_data['entity_table']) ? $this->_data['entity_table'] : null;
    }

    /**
     * Retrieve entity table prefix name
     *
     * @return string
     */
    public function getValueTablePrefix()
    {
        $prefix = $this->getEntityTablePrefix();
        if ($prefix) {
            return $this->getResource()->getTable($prefix);
        }

        return null;
    }

    /**
     * Retrieve entity table prefix
     *
     * @return string
     */
    public function getEntityTablePrefix()
    {
        $tablePrefix = trim($this->_data['value_table_prefix']);

        if (empty($tablePrefix)) {
            $tablePrefix = $this->getEntityTable();
        }

        return $tablePrefix;
    }

    /**
     * Get default attribute set identifier for etity type
     *
     * @return string|null
     */
    public function getDefaultAttributeSetId()
    {
        return isset($this->_data['default_attribute_set_id']) ? $this->_data['default_attribute_set_id'] : null;
    }

    /**
     * Retreive entity type id
     *
     * @return string|null
     */
    public function getEntityTypeId()
    {
        return isset($this->_data['entity_type_id']) ? $this->_data['entity_type_id'] : null;
    }

    /**
     * Retreive entity type code
     *
     * @return string|null
     */
    public function getEntityTypeCode()
    {
        return isset($this->_data['entity_type_code']) ? $this->_data['entity_type_code'] : null;
    }

    /**
     * Retreive attribute codes
     *
     * @return array|null
     */
    public function getAttributeCodes()
    {
        return isset($this->_data['attribute_codes']) ? $this->_data['attribute_codes'] : null;
    }

    /**
     * Get attribute model code for entity type
     *
     * @return string
     */
    public function getAttributeModel()
    {
        if (empty($this->_data['attribute_model'])) {
            return Mage_Eav_Model_Entity::DEFAULT_ATTRIBUTE_MODEL;
        }

        return $this->_data['attribute_model'];
    }

    /**
     * Retreive resource entity object
     *
     * @return Mage_Core_Model_Resource_Abstract
     */
    public function getEntity()
    {
        return Mage::getResourceSingleton($this->_data['entity_model']);
    }

    /**
     * Return attribute collection. If not specify return default
     *
     * @return string
     */
    public function getEntityAttributeCollection()
    {
        $collection = $this->_getData('entity_attribute_collection');
        if ($collection) {
            return $collection;
        }
        return 'eav/entity_attribute_collection';
    }
}


text:
PRAGMA cache_size = 10;
      CREATE TABLE t1(i INTEGER PRIMARY KEY, j blob)
;COMMIT ; BEGIN
;SELECT COALESCE(max(i), 0) FROM t1;
          PRAGMA integrity_check
;ROLLBACK TO sp_sub_x
;DELETE FROM t1 WHERE i>sub_x
;SAVEPOINT sp_sub_k
;INSERT INTO t1(j) VALUES(randomblob(1500))
;CREATE TABLE t1(a, b);
    PRAGMA journal_mode = off;
    BEGIN;
      INSERT INTO t1 VALUES(1, 2);
    ROLLBACK;
    SELECT * FROM t1
;PRAGMA auto_vacuum = incremental;
    PRAGMA page_size = 1024;
    PRAGMA journal_mode = off;
    CREATE TABLE t1(a, b);
    INSERT INTO t1 VALUES(zeroblob(5000), zeroblob(5000));
    DELETE FROM t1;
    PRAGMA incremental_vacuum
;CREATE TABLE t1(a, b)
;INSERT INTO t1 VALUES(1, 2);


text:
import view from './view/articleByTag.js';
import * as fetchs from './fetch.js';

export { view, fetchs };


text:
package com.alibaba.nacos.api.naming.ability;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;

public class ServerNamingAbilityTest {

    private static ObjectMapper jacksonMapper;

    @BeforeClass
    public static void setUpClass() throws Exception {
        jacksonMapper = new ObjectMapper();
        jacksonMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        jacksonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    @Test
    public void testDeserializeServerNamingAbilityForNonExistItem() throws JsonProcessingException {
        String nonExistItemJson = "{\"exampleAbility\":false}";
        ServerNamingAbility actual = jacksonMapper.readValue(nonExistItemJson, ServerNamingAbility.class);
        assertFalse(actual.isSupportJraft());
    }

    @Test
    public void testEquals() throws JsonProcessingException {
        ServerNamingAbility expected = new ServerNamingAbility();
        expected.setSupportJraft(true);
        String serializeJson = jacksonMapper.writeValueAsString(expected);
        ServerNamingAbility actual = jacksonMapper.readValue(serializeJson, ServerNamingAbility.class);
        assertEquals(expected, actual);
        actual = new ServerNamingAbility();
        assertNotEquals(expected, actual);
        actual.setSupportJraft(true);
        assertEquals(expected, actual);
    }
}


text:
package minesim.events.tracker;

import org.apache.log4j.Logger;

import java.io.InvalidClassException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

//import java.util.Observable;
//import minesim.WorldTimer;

/**
 * This class acts as the handler for event checking classes. Other entities and
 * classes that are interested in an event can register a method with said
 * event, causing that method to be run when that event is triggered.
 */
public class MineEventHandler implements Observer {
    private static final Logger LOG = Logger.getLogger(MineEventHandler.class);

    int counter = 0;

    private List<EventTracker> trackedEvents = new ArrayList<>();

    private static MineEventHandler instance = new MineEventHandler();

    protected MineEventHandler() {
    }

    public static MineEventHandler getInstance() {
        return instance;
    }

    /**
     * Gets passed an event tracker and a watcher. The tracker is added to the
     * list of currently active event trackers and the watcher is passed on to
     * the tracker to be called later when it triggers.
     */
    public void registerFor(Class eventTracker, Watcher w) throws InvalidClassException {
        if (!EventTracker.class.isAssignableFrom(eventTracker))
            throw new InvalidClassException("First argument must be a class that extends minesim.events.tracker.EventTracker");
        EventTracker tracker = null;
        try {
            tracker = (EventTracker) eventTracker.getConstructor().newInstance();
        } catch (Exception e) {
            LOG.error("Couldn't instantiate the eventTracker", e);
        }

        if (tracker == null)
            throw new InvalidClassException("We couldn't instantiate the EventTracker Class");

        // Add the tracker and add it's watcher, making sure we don't double up
        int index;
        if (!trackedEvents.contains(tracker)) {
            trackedEvents.add(tracker);
            tracker.registerWatcher(w);
        }
        else if ((index = trackedEvents.indexOf(tracker)) > -1)
            trackedEvents.get(index).registerWatcher(w);
    }

    /**
     * This will be called whenever an observed event is triggered It takes the
     * triggered event and runs all the registered functions
     */
    @Override
    public void update(Observable o, Object arg) {
        EventTracker e = (EventTracker) o;
        for (Watcher w : e.getWatcherList()) {
            w.handle(arg);
        }
    }

    /**
     * Looks through the events with registered listeners and checks to see if
     * they should be triggered
     */
    public void checkEvents() {
        counter++;
        for (EventTracker e : trackedEvents) {
            if (counter % e.getFreq() == 0){
                e.checkForEvent();
            }
        }
    }

	public List<EventTracker> getTrackedEvents() {
		return trackedEvents;
	}
}


text:
def prime_sieve(n)
  vs = (2..n).to_a
  primes = []

  while !vs.empty?
    primes << vs.shift
    vs.reject! { |v| v % primes.last == 0 }
  end

  primes
end

def trial_division(n)
  return 1 if n == 1

  primes = prime_sieve((n ** 0.5).to_i + 1)
  prime_factors = []

  primes.each do |p|
    break if p * p > n
    while n % p == 0
      prime_factors << p
      n /= p
    end
  end

  prime_factors << n if n > 1

  prime_factors
end

factors = (2..20).to_a
prime_factors = factors.map { |x| trial_division(x) }
unique_factors = prime_factors.flatten.uniq.sort

factor_powers = {}
unique_factors.each do |f|
  factor_powers[f] = 0
end

prime_factors.each do |element_prime_factors|
  element_prime_factors.each do |factor|
    count = element_prime_factors.count(factor)
    factor_powers[factor] = count if count > factor_powers[factor]
  end
end

val = factor_powers.inject(1) { |acc, e| acc *= e.first ** e.last }
puts val


text:
START_ATF_NAMESPACE
    typedef unsigned int RPC_LENGTH;
END_ATF_NAMESPACE


text:
import { Router } from '@angular/router';
import { KhachHang } from '../../shared/models/KhachHang';
import { Component, OnInit } from '@angular/core';
import { Message } from 'primeng/components/common/message';
import { KhachHangService } from 'app/le-tan/khach-hang/khach-hang.service';

@Component({
  selector: 'app-khach-hang',
  templateUrl: './khach-hang.component.html',
  styleUrls: ['./khach-hang.component.scss']
})
export class KhachHangComponent implements OnInit {
  constructor(private router: Router) { }

  ngOnInit() {
    this.router.navigate(['/le-tan','khach-hang', 'danh-sach']);
  }
}


text:
% Concurrency

Concurrency and parallelism are incredibly important topics in computer
science, and are also a hot topic in industry today. Computers are gaining more
and more cores, yet many programmers aren't prepared to fully utilize them.

Rust's memory safety features also apply to its concurrency story too. Even
concurrent Rust programs must be memory safe, having no data races. Rust's type
system is up to the task, and gives you powerful ways to reason about
concurrent code at compile time.

Before we talk about the concurrency features that come with Rust, it's important
to understand something: Rust is low-level enough that the vast majority of
this is provided by the standard library, not by the language. This means that
if you don't like some aspect of the way Rust handles concurrency, you can
implement an alternative way of doing things.
[mio](https://github.com/carllerche/mio) is a real-world example of this
principle in action.

## Background: `Send` and `Sync`

Concurrency is difficult to reason about. In Rust, we have a strong, static
type system to help us reason about our code. As such, Rust gives us two traits
to help us make sense of code that can possibly be concurrent.

### `Send`

The first trait we're going to talk about is
[`Send`](../std/marker/trait.Send.html). When a type `T` implements `Send`, it indicates
to the compiler that something of this type is able to have ownership transferred
safely between threads.

This is important to enforce certain restrictions. For example, if we have a
channel connecting two threads, we would want to be able to send some data
down the channel and to the other thread. Therefore, we'd ensure that `Send` was
implemented for that type.

In the opposite way, if we were wrapping a library with FFI that isn't
threadsafe, we wouldn't want to implement `Send`, and so the compiler will help
us enforce that it can't leave the current thread.

### `Sync`

The second of these traits is called [`Sync`](../std/marker/trait.Sync.html).
When a type `T` implements `Sync`, it indicates to the compiler that something
of this type has no possibility of introducing memory unsafety when used from
multiple threads concurrently.

For example, sharing immutable data with an atomic reference count is
threadsafe. Rust provides a type like this, `Arc<T>`, and it implements `Sync`,
so it is safe to share between threads.

These two traits allow you to use the type system to make strong guarantees
about the properties of your code under concurrency. Before we demonstrate
why, we need to learn how to create a concurrent Rust program in the first
place!

## Threads

Rust's standard library provides a library for threads, which allow you to
run Rust code in parallel. Here's a basic example of using `std::thread`:

```rust
use std::thread;

fn main() {
    thread::spawn(|| {
        println!("Hello from a thread!");
    });
}
```

The `thread::spawn()` method accepts a closure, which is executed in a
new thread. It returns a handle to the thread, that can be used to
wait for the child thread to finish and extract its result:

```rust
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        "Hello from a thread!"
    });

    println!("{}", handle.join().unwrap());
}
```

Many languages have the ability to execute threads, but it's wildly unsafe.
There are entire books about how to prevent errors that occur from shared
mutable state. Rust helps out with its type system here as well, by preventing
data races at compile time. Let's talk about how you actually share things
between threads.

## Safe Shared Mutable State

Due to Rust's type system, we have a concept that sounds like a lie: "safe
shared mutable state." Many programmers agree that shared mutable state is
very, very bad.

Someone once said this:

> Shared mutable state is the root of all evil. Most languages attempt to deal
> with this problem through the 'mutable' part, but Rust deals with it by
> solving the 'shared' part.

The same [ownership system](ownership.html) that helps prevent using pointers
incorrectly also helps rule out data races, one of the worst kinds of
concurrency bugs.

As an example, here is a Rust program that would have a data race in many
languages. It will not compile:

```ignore
use std::thread;

fn main() {
    let mut data = vec![1u32, 2, 3];

    for i in 0..3 {
        thread::spawn(move || {
            data[i] += 1;
        });
    }

    thread::sleep_ms(50);
}
```

This gives us an error:

```text
8:17 error: capture of moved value: `data`
        data[i] += 1;
        ^~~~
```

In this case, we know that our code _should_ be safe, but Rust isn't sure. And
it's actually not safe: if we had a reference to `data` in each thread, and the
thread takes ownership of the reference, we have three owners! That's bad. We
can fix this by using the `Arc<T>` type, which is an atomic reference counted
pointer. The 'atomic' part means that it's safe to share across threads.

`Arc<T>` assumes one more property about its contents to ensure that it is safe
to share across threads: it assumes its contents are `Sync`. But in our
case, we want to be able to mutate the value. We need a type that can ensure
only one person at a time can mutate what's inside. For that, we can use the
`Mutex<T>` type. Here's the second version of our code. It still doesn't work,
but for a different reason:

```ignore
use std::thread;
use std::sync::Mutex;

fn main() {
    let mut data = Mutex::new(vec![1u32, 2, 3]);

    for i in 0..3 {
        let data = data.lock().unwrap();
        thread::spawn(move || {
            data[i] += 1;
        });
    }

    thread::sleep_ms(50);
}
```

Here's the error:

```text
<anon>:9:9: 9:22 error: the trait `core::marker::Send` is not implemented for the type `std::sync::mutex::MutexGuard<'_, collections::vec::Vec<u32>>` [E0277]
<anon>:11         thread::spawn(move || {
                  ^~~~~~~~~~~~~
<anon>:9:9: 9:22 note: `std::sync::mutex::MutexGuard<'_, collections::vec::Vec<u32>>` cannot be sent between threads safely
<anon>:11         thread::spawn(move || {
                  ^~~~~~~~~~~~~
```

You see, [`Mutex`](../std/sync/struct.Mutex.html) has a
[`lock`](../std/sync/struct.Mutex.html#method.lock)
method which has this signature:

```ignore
fn lock(&self) -> LockResult<MutexGuard<T>>
```

Because `Send` is not implemented for `MutexGuard<T>`, we can't transfer the
guard across thread boundaries, which gives us our error.

We can use `Arc<T>` to fix this. Here's the working version:

```rust
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let data = Arc::new(Mutex::new(vec![1u32, 2, 3]));

    for i in 0..3 {
        let data = data.clone();
        thread::spawn(move || {
            let mut data = data.lock().unwrap();
            data[i] += 1;
        });
    }

    thread::sleep_ms(50);
}
```

We now call `clone()` on our `Arc`, which increases the internal count. This
handle is then moved into the new thread. Let's examine the body of the
thread more closely:

```rust
# use std::sync::{Arc, Mutex};
# use std::thread;
# fn main() {
#     let data = Arc::new(Mutex::new(vec![1u32, 2, 3]));
#     for i in 0..3 {
#         let data = data.clone();
thread::spawn(move || {
    let mut data = data.lock().unwrap();
    data[i] += 1;
});
#     }
#     thread::sleep_ms(50);
# }
```

First, we call `lock()`, which acquires the mutex's lock. Because this may fail,
it returns an `Result<T, E>`, and because this is just an example, we `unwrap()`
it to get a reference to the data. Real code would have more robust error handling
here. We're then free to mutate it, since we have the lock.

Lastly, while the threads are running, we wait on a short timer. But
this is not ideal: we may have picked a reasonable amount of time to
wait but it's more likely we'll either be waiting longer than
necessary or not long enough, depending on just how much time the
threads actually take to finish computing when the program runs.

A more precise alternative to the timer would be to use one of the
mechanisms provided by the Rust standard library for synchronizing
threads with each other. Let's talk about one of them: channels.

## Channels

Here's a version of our code that uses channels for synchronization, rather
than waiting for a specific time:

```rust
use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc;

fn main() {
    let data = Arc::new(Mutex::new(0u32));

    let (tx, rx) = mpsc::channel();

    for _ in 0..10 {
        let (data, tx) = (data.clone(), tx.clone());

        thread::spawn(move || {
            let mut data = data.lock().unwrap();
            *data += 1;

            tx.send(());
        });
    }

    for _ in 0..10 {
        rx.recv();
    }
}
```

We use the `mpsc::channel()` method to construct a new channel. We just `send`
a simple `()` down the channel, and then wait for ten of them to come back.

While this channel is just sending a generic signal, we can send any data that
is `Send` over the channel!

```rust
use std::thread;
use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();

    for _ in 0..10 {
        let tx = tx.clone();

        thread::spawn(move || {
            let answer = 42u32;

            tx.send(answer);
        });
    }

   rx.recv().ok().expect("Could not receive answer");
}
```

A `u32` is `Send` because we can make a copy. So we create a thread, ask it to calculate
the answer, and then it `send()`s us the answer over the channel.

## Panics

A `panic!` will crash the currently executing thread. You can use Rust's
threads as a simple isolation mechanism:

```rust
use std::thread;

let result = thread::spawn(move || {
    panic!("oops!");
}).join();

assert!(result.is_err());
```

Our `Thread` gives us a `Result` back, which allows us to check if the thread
has panicked or not.


text:
package org.onehippo.cms7.essentials.dashboard.instruction.executors;

import java.util.Set;

import javax.inject.Singleton;

import org.onehippo.cms7.essentials.dashboard.ctx.PluginContext;
import org.onehippo.cms7.essentials.dashboard.instructions.Instruction;
import org.onehippo.cms7.essentials.dashboard.instructions.InstructionExecutor;
import org.onehippo.cms7.essentials.dashboard.instructions.InstructionSet;
import org.onehippo.cms7.essentials.dashboard.instructions.InstructionStatus;
import org.onehippo.cms7.essentials.dashboard.model.Restful;
import org.onehippo.cms7.essentials.dashboard.packaging.MessageGroup;
import org.springframework.stereotype.Component;

import com.google.common.collect.Multimap;

/**
 * @version "$Id$"
 */
@Component
@Singleton
public class PluginInstructionExecutor implements InstructionExecutor {

    @Override
    public InstructionStatus execute(final InstructionSet set, PluginContext context) {
        InstructionStatus status = InstructionStatus.SUCCESS;
        final Set<Instruction> instructions = set.getInstructions();
        for (Instruction instruction : instructions) {
            status = instruction.process(context, status);
        }
        return status;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Multimap<MessageGroup,Restful> getInstructionsMessages(final InstructionSet instruction, final PluginContext context) {
        MessageInstructionExecutor executor = new MessageInstructionExecutor();
        return executor.execute(instruction, context);
    }

}


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
J. Bot. 11:296. 1873

#### Original name
null

### Remarks
null


text:
import os
from Game import Game
from util import dirExists

class GamesList:
    '''
        Manages the list of games and ensures unique IDs
    '''
    if not dirExists(Game.GAMES_DIRECTORY):
        os.makedirs(Game.GAMES_DIRECTORY)
    gamesDirectories = [os.path.join(Game.GAMES_DIRECTORY, x) for x in os.listdir(Game.GAMES_DIRECTORY)]
    games = []

    @staticmethod
    def load(directory):
        '''
            Loads a game from a directory
            Returns the Game
        '''
        return Game.loadFromDirectory(directory)

    @staticmethod
    def init():
        '''
            To be called once after creation
            Loads a list of games
        '''
        for directory in GamesList.gamesDirectories:
            GamesList.addGame(GamesList.load(directory))

    @staticmethod
    def addGame(game):
        '''
            Adds a Game to the list
        '''
        GamesList.games.append(game)

    @staticmethod
    def getByID(gameID):
        # TODO: use a hash map to index games
        for i in xrange(len(GamesList.games)):
            game = GamesList.games[i]
            if game.ID == gameID:
                return game

        return None

    @staticmethod
    def removeGame(gameID):
        '''
            Removes a game from the list and deletes it
            Throws: IOError
        '''
        for i in xrange(len(GamesList.games)):
            game = GamesList.games[i]
            if game.ID == gameID:
                game.delete()
                del GamesList.games[i]
                break

    @staticmethod
    def getAllGames():
        '''
            Returns a list of Games
        '''
        GamesList.games.sort()
        return GamesList.games


text:
from distutils.core import setup

setup(name='Moman',
      version='0.2.1',
      description='A tools suite for orthographic/grammatical check',
      author='Jean-Philippe Barrette-LaPierre',
      author_email='jpb_NO_SPAM@rrette.com',
      url='http://rrette.com/moman.html',
      packages=['finenight'],
      package_dir={'finenight': 'finenight/python/'},
      scripts=['finenight/python/recognize']
      )


text:
      {% assign today = site.time | date: '%s' %}
      {% assign start = '16-08-2017 00:00:00' | date: '%s' %}
      {% assign secondsSince = today | minus: start %}

      {% assign daysSince = secondsSince | divided_by: 3600 | divided_by: 24  %}
      {% assign daysLeft = 100 | minus: daysSince  %}

      Days: {{ daysSince }}
      Days left: {{ daysLeft }}