text:
module ActionMailer
  class Base

    # Specify the layout name
    adv_attr_accessor :layout

    def render_message(method_name, body)
      layout = @layout ? @layout.to_s : self.class.to_s.underscore
      md = /^([^\.]+)\.([^\.]+\.[^\.]+)\.(rhtml|rxml)$/.match(method_name)
      layout << ".#{md.captures[1]}" if md && md.captures[1]
      layout << ".rhtml"
      if File.exists?(File.join(layouts_path, layout))
        body[:content_for_layout] = render(:file => method_name, :body => body)
        ActionView::Base.new(layouts_path, body, self).render(:file => layout)
      else
        render :file => method_name, :body => body
      end
    end

    def layouts_path
      File.join(template_root, 'layouts')
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
module Wupee
  module AttachedObject
    extend ActiveSupport::Concern

    included do
      has_many :notifications_as_attached_object, as: :attached_object, dependent: :destroy, class_name: "Wupee::Notification"
    end
  end
end


text:
namespace tracing {

// Fill the information about flow event in EventContext.
//
// BEWARE: this function currently sets the TrackEvent's LegacyEvent field, and
// thus should be used from within trace macros that do not set the LegacyEvent
// field themselves. As it is, it is fine to call this method from the typed
// TRACE_EVENT macro.
//
// TODO(b/147673438): Change to the new model flow events when finalized
void COMPONENT_EXPORT(TRACING_CPP) FillFlowEvent(
    const perfetto::EventContext&,
    perfetto::protos::pbzero::TrackEvent::LegacyEvent::FlowDirection,
    uint64_t bind_id);

}  // namespace tracing

#endif  // SERVICES_TRACING_PUBLIC_CPP_PERFETTO_FLOW_EVENT_UTILS_H_


text:
#ifndef VOS_COND_H
#define VOS_COND_H

namespace VPP{
typedef struct
{
#if VOS_APP_OS == VOS_OS_WIN32
    HANDLE  event;
#else
    pthread_cond_t cond;
    pthread_mutex_t  mutex;
#endif
}VOS_COND;

    LONG VOS_CondInit(VOS_COND* pCond);
    LONG VOS_CondWait(VOS_COND* pCond);
    LONG VOS_CondTimeWait(VOS_COND* pCond,LONG lSeconds);
    LONG VOS_CondSignal(VOS_COND* pCond);
    LONG VOS_CondDestroy(VOS_COND* pCond);

}//end namespace

#endif /* __VOS_COND_H__ */


text:
package com.google.firebase.database.core;

import com.google.android.gms.common.internal.Preconditions;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DatabaseException;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.android.AndroidPlatform;
import com.google.firebase.database.connection.ConnectionContext;
import com.google.firebase.database.connection.ConnectionTokenProvider;
import com.google.firebase.database.connection.HostInfo;
import com.google.firebase.database.connection.PersistentConnection;
import com.google.firebase.database.core.persistence.NoopPersistenceManager;
import com.google.firebase.database.core.persistence.PersistenceManager;
import com.google.firebase.database.core.utilities.DefaultRunLoop;
import com.google.firebase.database.logging.LogWrapper;
import com.google.firebase.database.logging.Logger;
import java.io.File;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;

public class Context {

  private static final long DEFAULT_CACHE_SIZE = 10 * 1024 * 1024;

  protected Logger logger;
  protected EventTarget eventTarget;
  protected TokenProvider authTokenProvider;
  protected TokenProvider appCheckTokenProvider;
  protected RunLoop runLoop;
  protected String persistenceKey;
  protected List<String> loggedComponents;
  protected String userAgent;
  protected Logger.Level logLevel = Logger.Level.INFO;
  protected boolean persistenceEnabled;
  protected long cacheSize = DEFAULT_CACHE_SIZE;
  protected FirebaseApp firebaseApp;
  private PersistenceManager forcedPersistenceManager;
  private boolean frozen = false;
  private boolean stopped = false;

  private Platform platform;

  private Platform getPlatform() {
    if (platform == null) {
      initializeAndroidPlatform();
    }
    return platform;
  }

  private synchronized void initializeAndroidPlatform() {
    platform = new AndroidPlatform(this.firebaseApp);
  }

  public boolean isFrozen() {
    return frozen;
  }

  public boolean isStopped() {
    return stopped;
  }

  synchronized void freeze() {
    if (!frozen) {
      frozen = true;
      initServices();
    }
  }

  public void requireStarted() {
    if (stopped) {
      restartServices();
      stopped = false;
    }
  }

  private void initServices() {
    // Do the logger first, so that other components can get a LogWrapper
    ensureLogger();
    // Cache platform
    getPlatform();
    ensureUserAgent();
    // ensureStorage();
    ensureEventTarget();
    ensureRunLoop();
    ensureSessionIdentifier();
    ensureAuthTokenProvider();
    ensureAppTokenProvider();
  }

  private void restartServices() {
    eventTarget.restart();
    runLoop.restart();
  }

  void stop() {
    stopped = true;
    eventTarget.shutdown();
    runLoop.shutdown();
  }

  protected void assertUnfrozen() {
    if (isFrozen()) {
      throw new DatabaseException(
          "Modifications to DatabaseConfig objects must occur before they are in use");
    }
  }

  public List<String> getOptDebugLogComponents() {
    return this.loggedComponents;
  }

  public Logger.Level getLogLevel() {
    return this.logLevel;
  }

  public Logger getLogger() {
    return this.logger;
  }

  public LogWrapper getLogger(String component) {
    return new LogWrapper(logger, component);
  }

  public LogWrapper getLogger(String component, String prefix) {
    return new LogWrapper(logger, component, prefix);
  }

  public ConnectionContext getConnectionContext() {
    return new ConnectionContext(
        this.getLogger(),
        wrapTokenProvider(this.getAuthTokenProvider(), this.getExecutorService()),
        wrapTokenProvider(this.getAppCheckTokenProvider(), this.getExecutorService()),
        this.getExecutorService(),
        this.isPersistenceEnabled(),
        FirebaseDatabase.getSdkVersion(),
        this.getUserAgent(),
        firebaseApp.getOptions().getApplicationId(),
        this.getSSLCacheDirectory().getAbsolutePath());
  }

  PersistenceManager getPersistenceManager(String firebaseId) {
    // TODO[persistence]: Create this once and store it.
    if (forcedPersistenceManager != null) {
      return forcedPersistenceManager;
    }
    if (this.persistenceEnabled) {
      PersistenceManager cache = platform.createPersistenceManager(this, firebaseId);
      if (cache == null) {
        throw new IllegalArgumentException(
            "You have enabled persistence, but persistence is not supported on "
                + "this platform.");
      }
      return cache;
    } else {
      return new NoopPersistenceManager();
    }
  }

  public boolean isPersistenceEnabled() {
    return this.persistenceEnabled;
  }

  public long getPersistenceCacheSizeBytes() {
    return this.cacheSize;
  }

  // For testing
  void forcePersistenceManager(PersistenceManager persistenceManager) {
    this.forcedPersistenceManager = persistenceManager;
  }

  public EventTarget getEventTarget() {
    return eventTarget;
  }

  public RunLoop getRunLoop() {
    return runLoop;
  }

  public String getUserAgent() {
    return userAgent;
  }

  public String getPlatformVersion() {
    return getPlatform().getPlatformVersion();
  }

  public String getSessionPersistenceKey() {
    return this.persistenceKey;
  }

  public TokenProvider getAuthTokenProvider() {
    return this.authTokenProvider;
  }

  public TokenProvider getAppCheckTokenProvider() {
    return this.appCheckTokenProvider;
  }

  public PersistentConnection newPersistentConnection(
      HostInfo info, PersistentConnection.Delegate delegate) {
    return getPlatform().newPersistentConnection(this, this.getConnectionContext(), info, delegate);
  }

  private ScheduledExecutorService getExecutorService() {
    RunLoop loop = this.getRunLoop();
    if (!(loop instanceof DefaultRunLoop)) {
      // TODO: We really need to remove this option from the public DatabaseConfig
      // object
      throw new RuntimeException("Custom run loops are not supported!");
    }
    return ((DefaultRunLoop) loop).getExecutorService();
  }

  private void ensureLogger() {
    if (logger == null) {
      logger = getPlatform().newLogger(this, logLevel, loggedComponents);
    }
  }

  private void ensureRunLoop() {
    if (runLoop == null) {
      runLoop = platform.newRunLoop(this);
    }
  }

  private void ensureEventTarget() {
    if (eventTarget == null) {
      eventTarget = getPlatform().newEventTarget(this);
    }
  }

  private void ensureUserAgent() {
    if (userAgent == null) {
      userAgent = buildUserAgent(getPlatform().getUserAgent(this));
    }
  }

  private void ensureAuthTokenProvider() {
    Preconditions.checkNotNull(
        authTokenProvider, "You must register an authTokenProvider before initializing Context.");
  }

  private void ensureAppTokenProvider() {
    Preconditions.checkNotNull(
        appCheckTokenProvider,
        "You must register an appCheckTokenProvider before initializing Context.");
  }

  private void ensureSessionIdentifier() {
    if (persistenceKey == null) {
      persistenceKey = "default";
    }
  }

  private String buildUserAgent(String platformAgent) {
    StringBuilder sb =
        new StringBuilder()
            .append("Firebase/")
            .append(Constants.WIRE_PROTOCOL_VERSION)
            .append("/")
            .append(FirebaseDatabase.getSdkVersion())
            .append("/")
            .append(platformAgent);
    return sb.toString();
  }

  private static ConnectionTokenProvider wrapTokenProvider(
      final TokenProvider provider, ScheduledExecutorService executorService) {
    return (forceRefresh, callback) ->
        provider.getToken(
            forceRefresh,
            new TokenProvider.GetTokenCompletionListener() {
              @Override
              public void onSuccess(String token) {
                executorService.execute(() -> callback.onSuccess(token));
              }

              @Override
              public void onError(String error) {
                executorService.execute(() -> callback.onError(error));
              }
            });
  }

  public File getSSLCacheDirectory() {
    return getPlatform().getSSLCacheDirectory();
  }
}


text:
package com.kakao.hbase.common;

import org.junit.Assert;
import org.junit.Test;

public class LoadEntryTest {
    @Test
    public void testDataLocalityToString() throws Exception {
        Assert.assertEquals("100.00%", LoadEntry.DataLocality.toString(1.00001));
        Assert.assertEquals("-0.00%", LoadEntry.DataLocality.toString(-0.000001));
        Assert.assertEquals("-0.01%", LoadEntry.DataLocality.toString(-0.00005));
        Assert.assertEquals("0.01%", LoadEntry.DataLocality.toString(0.00005));
        Assert.assertEquals("100.00%", LoadEntry.DataLocality.toString(0.999999));
    }

    @Test
    public void testDataLocalityToRateString() throws Exception {
        Assert.assertEquals("5.00%/s", LoadEntry.DataLocality.toRateString(0.05, 1000));
        Assert.assertEquals("2.50%/s", LoadEntry.DataLocality.toRateString(0.05, 2000));
        Assert.assertEquals("0.03%/s", LoadEntry.DataLocality.toRateString(0.0005, 2000));
    }

    @Test
    public void testCompareAndCompareTo() throws Exception {
        RatioNumber number1 = new RatioNumber(100, 0.1);
        RatioNumber number2 = new RatioNumber(100, 0.2);
        RatioNumber number3 = new RatioNumber(100, 0.1);
        Double number4 = 1.0;

        Assert.assertEquals(-1, LoadEntry.DataLocality.compare(number1, number2));
        Assert.assertEquals(1, LoadEntry.DataLocality.compare(number2, number1));
        Assert.assertEquals(0, LoadEntry.DataLocality.compare(number1, number3));
        Assert.assertEquals(-1, LoadEntry.DataLocality.compare(number1, number4));
        Assert.assertEquals(1, LoadEntry.DataLocality.compare(number4, number1));

        Assert.assertEquals(-1, number1.compareTo(number2));
        Assert.assertEquals(1, number2.compareTo(number1));
        Assert.assertEquals(0, number1.compareTo(number3));
    }

    @Test
    public void testCompareTo() throws Exception {
        RatioNumber number1 = new RatioNumber(100, 0.1);
        RatioNumber number2 = new RatioNumber(100, 0.2);
        RatioNumber number3 = new RatioNumber(100, 0.1);

        Assert.assertEquals(-1, number1.compareTo(number2));
        Assert.assertEquals(1, number2.compareTo(number1));
        Assert.assertEquals(0, number1.compareTo(number3));
    }
}


text:
namespace media {

class AudioLog;
class AudioManager;
class AudioOutputController;
class AudioParameters;
class AudioSyncReader;

class MEDIA_EXPORT AudioOutputDelegateImpl : public AudioOutputDelegate {
 public:
  AudioOutputDelegateImpl(EventHandler* handler,
                          AudioManager* audio_manager,
                          std::unique_ptr<AudioLog> audio_log,
                          int stream_id,
                          int render_frame_id,
                          const AudioParameters& params,
                          const std::string& output_device_id,
                          base::SingleThreadTaskRunner* io_task_runner);

  ~AudioOutputDelegateImpl() override;

  // AudioOutputDelegate implementation.
  int GetStreamId() const override;
  void OnPlayStream() override;
  void OnPauseStream() override;
  void OnSetVolume(double volume) override;

 private:
  class ControllerEventHandler;

  void SendCreatedNotification();
  void OnError();
  void UpdatePlayingState(bool playing);

  EventHandler* subscriber_;
  std::unique_ptr<AudioLog> const audio_log_;
  std::unique_ptr<ControllerEventHandler> controller_event_handler_;
  std::unique_ptr<AudioSyncReader> reader_;
  scoped_refptr<AudioOutputController> controller_;
  const int stream_id_;
  base::SingleThreadTaskRunner* const io_task_runner_;

  bool playing_ = false;
  base::WeakPtrFactory<AudioOutputDelegateImpl> weak_factory_;
  DISALLOW_COPY_AND_ASSIGN(AudioOutputDelegateImpl);
};

}  // namespace media

#endif  // CHROMIUM_MEDIA_LIB_AUDIO_OUTPUT_DELEGATE_IMPL_H_


text:
import {
  parseGuid,
  WebApiConfig,
  retrieveMultiple,
  createWithReturnData,
  update,
  unboundAction
} from "xrm-webapi/dist/xrm-webapi-node";

import { AuthenticationContext, TokenResponse } from "adal-node";

function getWebResourceType(type: string): number {
  switch (type) {
    case "HTML":
      return 1;
    case "CSS":
      return 2;
    case "JavaScript":
      return 3;
    case "XML":
      return 4;
    case "PNG":
      return 5;
    case "JPG":
      return 6;
    case "GIF":
      return 7;
    case "XAP":
      return 8;
    case "XSL":
      return 9;
    case "ICO":
      return 10;
    case "SVG":
      return 11;
    case "RESX":
      return 12;
  }
}

export interface Config {
  tenant: string;
  clientId?: string;
  clientSecret?: string;
  server: string;
  username?: string;
  password?: string;
  webResources: WebResource[];
  solution: string;
}

export interface WebResource {
  displayname?: string;
  name?: string;
  type?: string;
  content?: string;
  path?: string;
  webresourcetype?: number;
}

export interface WebResourceAsset {
  content: string;
  path: string;
}

enum UpsertType {
  create,
  update
}

interface Upsert {
  id: string;
  type: UpsertType;
}

function authenticate(config: Config): Promise<string> {
  return new Promise((resolve, reject) => {
    // authenticate
    const authorityHostUrl: string = `https://login.windows.net/${config.tenant}`;
    const context = new AuthenticationContext(authorityHostUrl);
    const clientId: string = config.clientId || "c67c746f-9745-46eb-83bb-5742263736b7";

    // use client id/secret auth
    if (config.clientSecret != null && config.clientSecret !== "") {
      context.acquireTokenWithClientCredentials(config.server, clientId, config.clientSecret,
        (ex: Error, token: TokenResponse) => {
          if (ex) {
            reject(ex);
          } else {
            resolve(token.accessToken);
          }
        }
      );
    // username/password authentication
    } else {
      context.acquireTokenWithUsernamePassword(config.server, config.username, config.password, clientId,
        (ex: Error, token: TokenResponse) => {
          if (ex) {
            reject(ex);
          } else {
            resolve(token.accessToken);
          }
        }
      );
    }
  });
}

async function getUpsert(config: Config, asset: WebResourceAsset, token: string): Promise<Upsert> {
  // get web resource from config
  let resource: WebResource[] = config.webResources.filter(wr => wr.path === asset.path);

  if (resource.length === 0) {
    console.log("Web resource " + asset.path + " is not configured");
    return null;
  } else {
    const apiConfig = new WebApiConfig("8.2", token, config.server);

    // check if web resource already exists
    const options: string = `$select=webresourceid&$filter=name eq '${resource[0].name}'`;

    try {
      const response = await retrieveMultiple(apiConfig, "webresourceset", options);

      // create or update web resource
      let webResource: WebResource = {
        content: new Buffer(asset.content).toString("base64")
      };

      if (response.value.length === 0) {
        console.log(`Creating web resource ${resource[0].name}`);

        webResource.webresourcetype = getWebResourceType(resource[0].type);
        webResource.name = resource[0].name;
        webResource.displayname = resource[0].displayname || resource[0].name;

        const result = await createWithReturnData(apiConfig, "webresourceset", webResource, "$select=webresourceid");

        return {
          id: result.webresourceid,
          type: UpsertType.create
        };
      } else {
        console.log(`Updating web resource ${resource[0].name}`);

        await update(apiConfig, "webresourceset", parseGuid(response.value[0].webresourceid), webResource);

        return {
          id: response.value[0].webresourceid,
          type: UpsertType.update
        };
      }
    } catch (error) {
      throw new Error(error.message);
    }
  }
}

export async function upload(config: Config, assets: WebResourceAsset[]): Promise<any> {
  let token: string;

  try {
    token = await authenticate(config);
  } catch (error) {
    throw new Error(error);
  }

  console.log("\r\nUploading web resources...");

  // retrieve assets from CRM then create/update
  let upserts: Upsert[];

  const promises: Promise<any>[] = assets.map(asset => getUpsert(config, asset, token));

  try {
    upserts = await Promise.all(promises);
  } catch (error) {
    throw new Error(error.message);
  }

  // publish resources
  console.log("Publishing web resources...");

  // get updates and inserts
  const updates: string[] = [];
  const inserts: string[] = [];

  for (let u of upserts) {
    if (u != null) {
      if (u.type === UpsertType.update) {
        updates.push(`<webresource>{${u.id}}</webresource>`);
      } else {
        inserts.push(u.id);
      }
    }
  }

  const tasks: any[] = [];

  // publish all updates at once
  if (updates.length > 0) {
    tasks.push({
      action: "PublishXml",
      data: {
        ParameterXml: `<importexportxml><webresources>${updates.join(
          ""
        )}</webresources></importexportxml>`
      }
    });
  }

  // add solution component individually
  for (let i of inserts) {
    const item: object = {
      action: "AddSolutionComponent",
      data: {
        ComponentId: i,
        ComponentType: 61,
        SolutionUniqueName: config.solution,
        AddRequiredComponents: false,
        IncludedComponentSettingsValues: null
      }
    };

    tasks.push(item);
  }

  const apiConfig = new WebApiConfig("8.2", token, config.server);

  for (let i: number = 0; i < tasks.length; i++) {
    try {
      await unboundAction(apiConfig, tasks[i].action, tasks[i].data);
    } catch (error) {
      throw new Error(error.message);
    }
  }

  console.log("Uploaded and published web resources\r\n");
}


text:
/*
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.comcast.cdn.traffic_control.traffic_router.core.util;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.whenNew;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Fetcher.class, URL.class, InputStreamReader.class})
@PowerMockIgnore("javax.net.ssl.*")
public class FetcherTest {

    @Test
    public void itChecksIfDataHasChangedSinceLastFetch() throws Exception {
        InputStream inputStream = mock(InputStream.class);

        InputStreamReader inputStreamReader = mock(InputStreamReader.class);
        whenNew(InputStreamReader.class).withArguments(inputStream).thenReturn(inputStreamReader);

        BufferedReader bufferedReader = mock(BufferedReader.class);
        when(bufferedReader.readLine()).thenReturn(null);

        whenNew(BufferedReader.class).withArguments(inputStreamReader).thenReturn(bufferedReader);

        HttpURLConnection httpURLConnection = mock(HttpURLConnection.class);
        when(httpURLConnection.getInputStream()).thenReturn(inputStream);

        URL url = mock(URL.class);
        when(url.openConnection()).thenReturn(httpURLConnection);
        whenNew(URL.class).withArguments("http://www.example.com").thenReturn(url);

        Fetcher fetcher = new Fetcher();
        fetcher.fetchIfModifiedSince("http://www.example.com", 123456L);
        verify(httpURLConnection).setIfModifiedSince(123456L);
    }
}


text:
use std::any::Any;
use std::num::NonZeroU32;
#[cfg(feature = "toml")]
use std::path::Path;
use std::time::Duration;

use crossbeam_channel::{self, Receiver, Sender};

use crate::{
    backend, direction,
    event::{Event, EventResult},
    printer::Printer,
    theme,
    view::{self, Finder, IntoBoxedView, Position, View},
    views::{self, LayerPosition},
    Dump, Vec2,
};

static DEBUG_VIEW_NAME: &str = "_cursive_debug_view";

// How long we wait between two empty input polls
const INPUT_POLL_DELAY_MS: u64 = 30;

/// Central part of the cursive library.
///
/// It initializes ncurses on creation and cleans up on drop.
/// To use it, you should populate it with views, layouts, and callbacks,
/// then start the event loop with `run()`.
///
/// It uses a list of screen, with one screen active at a time.
pub struct Cursive {
    theme: theme::Theme,

    // The main view
    root: views::OnEventView<views::ScreensView<views::StackView>>,

    menubar: views::Menubar,

    // Last layer sizes of the stack view.
    // If it changed, clear the screen.
    last_sizes: Vec<Vec2>,

    running: bool,

    backend: Box<dyn backend::Backend>,

    // Handle asynchronous callbacks
    cb_source: Receiver<Box<dyn FnOnce(&mut Cursive) + Send>>,
    cb_sink: Sender<Box<dyn FnOnce(&mut Cursive) + Send>>,

    // User-provided data.
    user_data: Box<dyn Any>,

    // Handle auto-refresh when no event is received.
    fps: Option<NonZeroU32>,
    boring_frame_count: u32,
}

/// Identifies a screen in the cursive root.
pub type ScreenId = usize;

/// Convenient alias to the result of `Cursive::cb_sink`.
///
/// # Notes
///
/// Callbacks need to be `Send`, which can be limiting in some cases.
///
/// In some case [`send_wrapper`] may help you work around that.
///
/// [`send_wrapper`]: https://crates.io/crates/send_wrapper
pub type CbSink = Sender<Box<dyn FnOnce(&mut Cursive) + Send>>;

impl Cursive {
    /// Shortcut for `Cursive::try_new` with non-failible init function.
    ///
    /// You probably don't want to use this function directly, unless you're
    /// using a non-standard backend. Built-in backends have dedicated functions.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use cursive_core::{Cursive, backend};
    /// let siv = Cursive::new(backend::Dummy::init);
    /// ```
    pub fn new<F>(backend_init: F) -> Self
    where
        F: FnOnce() -> Box<dyn backend::Backend>,
    {
        Self::try_new::<_, ()>(|| Ok(backend_init())).unwrap()
    }

    /// Creates a new Cursive root, and initialize the back-end.
    ///
    /// You probably don't want to use this function directly, unless you're
    /// using a non-standard backend. Built-in backends have dedicated functions in the
    /// [`CursiveExt`] trait.
    ///
    /// [`CursiveExt`]: https://docs.rs/cursive/0/cursive/trait.CursiveExt.html
    pub fn try_new<F, E>(backend_init: F) -> Result<Self, E>
    where
        F: FnOnce() -> Result<Box<dyn backend::Backend>, E>,
    {
        let theme = theme::load_default();

        let (cb_sink, cb_source) = crossbeam_channel::unbounded();

        let backend = backend_init()?;
        let mut cursive = Cursive {
            theme,
            root: views::OnEventView::new(views::ScreensView::single_screen(
                views::StackView::new(),
            )),
            last_sizes: Vec::new(),
            menubar: views::Menubar::new(),
            running: true,
            cb_source,
            cb_sink,
            backend,
            fps: None,
            boring_frame_count: 0,
            user_data: Box::new(()),
        };
        cursive.reset_default_callbacks();

        Ok(cursive)
    }

    /// Creates a new Cursive root using a [dummy backend].
    ///
    /// Nothing will be output. This is mostly here for tests.
    ///
    /// [dummy backend]: backend::Dummy
    pub fn dummy() -> Self {
        Self::new(backend::Dummy::init)
    }

    /// Sets some data to be stored in Cursive.
    ///
    /// It can later on be accessed with `Cursive::user_data()`
    pub fn set_user_data<T: Any>(&mut self, user_data: T) {
        self.user_data = Box::new(user_data);
    }

    /// Attempts to access the user-provided data.
    ///
    /// If some data was set previously with the same type, returns a
    /// reference to it.
    ///
    /// If nothing was set or if the type is different, returns `None`.
    pub fn user_data<T: Any>(&mut self) -> Option<&mut T> {
        self.user_data.downcast_mut()
    }

    /// Attemps to take by value the current user-data.
    ///
    /// If successful, this will replace the current user-data with the unit
    /// type `()`.
    ///
    /// If the current user data is not of the requested type, `None` will be
    /// returned.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let mut siv = cursive_core::Cursive::dummy();
    ///
    /// // Start with a simple `Vec<i32>` as user data.
    /// siv.set_user_data(vec![1i32, 2, 3]);
    /// assert_eq!(siv.user_data::<Vec<i32>>(), Some(&mut vec![1i32, 2, 3]));
    ///
    /// // Let's mutate the data a bit.
    /// siv.with_user_data(|numbers: &mut Vec<i32>| numbers.push(4));
    ///
    /// // If mutable reference is not enough, we can take the data by value.
    /// let data: Vec<i32> = siv.take_user_data().unwrap();
    /// assert_eq!(data, vec![1i32, 2, 3, 4]);
    ///
    /// // At this point the user data was removed and is no longer available.
    /// assert_eq!(siv.user_data::<Vec<i32>>(), None);
    /// ```
    pub fn take_user_data<T: Any>(&mut self) -> Option<T> {
        // Start by taking the user data and replacing it with a dummy.
        let user_data = std::mem::replace(&mut self.user_data, Box::new(()));

        // Downcast the data to the requested type.
        // If it works, unbox it.
        // It if doesn't, take it back.
        user_data
            .downcast()
            .map_err(|user_data| {
                // If we asked for the wrong type, put it back.
                self.user_data = user_data;
            })
            .map(|boxed| *boxed)
            .ok()
    }

    /// Runs the given closure on the stored user data, if any.
    ///
    /// If no user data was supplied, or if the type is different, nothing
    /// will be run.
    ///
    /// Otherwise, the result will be returned.
    pub fn with_user_data<F, T, R>(&mut self, f: F) -> Option<R>
    where
        F: FnOnce(&mut T) -> R,
        T: Any,
    {
        self.user_data().map(f)
    }

    /// Show the debug console.
    ///
    /// Currently, this will show logs if [`logger::init()`](crate::logger::init()) was called.
    pub fn show_debug_console(&mut self) {
        self.add_layer(
            views::Dialog::around(
                views::ScrollView::new(views::NamedView::new(
                    DEBUG_VIEW_NAME,
                    views::DebugView::new(),
                ))
                .scroll_x(true),
            )
            .title("Debug console"),
        );
    }

    /// Show the debug console, or hide it if it's already visible.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use cursive_core::Cursive;
    /// # let mut siv = Cursive::dummy();
    /// siv.add_global_callback('~', Cursive::toggle_debug_console);
    /// ```
    pub fn toggle_debug_console(&mut self) {
        if let Some(pos) =
            self.screen_mut().find_layer_from_name(DEBUG_VIEW_NAME)
        {
            self.screen_mut().remove_layer(pos);
        } else {
            self.show_debug_console();
        }
    }

    /// Returns a sink for asynchronous callbacks.
    ///
    /// Returns the sender part of a channel, that allows to send
    /// callbacks to `self` from other threads.
    ///
    /// Callbacks will be executed in the order
    /// of arrival on the next event cycle.
    ///
    /// # Notes
    ///
    /// Callbacks need to be `Send`, which can be limiting in some cases.
    ///
    /// In some case [`send_wrapper`] may help you work around that.
    ///
    /// [`send_wrapper`]: https://crates.io/crates/send_wrapper
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use cursive_core::*;
    /// let mut siv = Cursive::dummy();
    ///
    /// // quit() will be called during the next event cycle
    /// siv.cb_sink().send(Box::new(|s| s.quit())).unwrap();
    /// ```
    pub fn cb_sink(&self) -> &CbSink {
        &self.cb_sink
    }

    /// Selects the menubar.
    pub fn select_menubar(&mut self) {
        self.menubar.take_focus(direction::Direction::none());
    }

    /// Sets the menubar autohide feature.
    ///
    /// * When enabled (default), the menu is only visible when selected.
    /// * When disabled, the menu is always visible and reserves the top row.
    pub fn set_autohide_menu(&mut self, autohide: bool) {
        self.menubar.autohide = autohide;
    }

    /// Access the menu tree used by the menubar.
    ///
    /// This allows to add menu items to the menubar.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use cursive_core::{Cursive, event};
    /// # use cursive_core::views::{Dialog};
    /// # use cursive_core::traits::*;
    /// # use cursive_core::menu::*;
    /// #
    /// let mut siv = Cursive::dummy();
    ///
    /// siv.menubar()
    ///    .add_subtree("File",
    ///         MenuTree::new()
    ///             .leaf("New", |s| s.add_layer(Dialog::info("New file!")))
    ///             .subtree("Recent", MenuTree::new().with(|tree| {
    ///                 for i in 1..100 {
    ///                     tree.add_leaf(format!("Item {}", i), |_| ())
    ///                 }
    ///             }))
    ///             .delimiter()
    ///             .with(|tree| {
    ///                 for i in 1..10 {
    ///                     tree.add_leaf(format!("Option {}", i), |_| ());
    ///                 }
    ///             })
    ///             .delimiter()
    ///             .leaf("Quit", |s| s.quit()))
    ///    .add_subtree("Help",
    ///         MenuTree::new()
    ///             .subtree("Help",
    ///                      MenuTree::new()
    ///                          .leaf("General", |s| {
    ///                              s.add_layer(Dialog::info("Help message!"))
    ///                          })
    ///                          .leaf("Online", |s| {
    ///                              s.add_layer(Dialog::info("Online help?"))
    ///                          }))
    ///             .leaf("About",
    ///                   |s| s.add_layer(Dialog::info("Cursive v0.0.0"))));
    ///
    /// siv.add_global_callback(event::Key::Esc, |s| s.select_menubar());
    /// ```
    pub fn menubar(&mut self) -> &mut views::Menubar {
        &mut self.menubar
    }

    /// Returns the currently used theme.
    pub fn current_theme(&self) -> &theme::Theme {
        &self.theme
    }

    /// Sets the current theme.
    pub fn set_theme(&mut self, theme: theme::Theme) {
        self.theme = theme;
        self.clear();
    }

    /// Updates the current theme.
    pub fn update_theme(&mut self, f: impl FnOnce(&mut theme::Theme)) {
        // We don't just expose a `current_theme_mut` because we may want to
        // run some logic _after_ setting the theme.
        // Though right now, it's only clearing the screen, so...
        let mut theme = self.theme.clone();
        f(&mut theme);
        self.set_theme(theme);
    }

    /// Clears the screen.
    ///
    /// Users rarely have to call this directly.
    pub fn clear(&mut self) {
        self.backend
            .clear(self.theme.palette[theme::PaletteColor::Background]);
    }

    /// Loads a theme from the given file.
    ///
    /// `filename` must point to a valid toml file.
    ///
    /// Must have the `toml` feature enabled.
    #[cfg(feature = "toml")]
    pub fn load_theme_file<P: AsRef<Path>>(
        &mut self,
        filename: P,
    ) -> Result<(), theme::Error> {
        theme::load_theme_file(filename).map(|theme| self.set_theme(theme))
    }

    /// Loads a theme from the given string content.
    ///
    /// Content must be valid toml.
    ///
    /// Must have the `toml` feature enabled.
    #[cfg(feature = "toml")]
    pub fn load_toml(&mut self, content: &str) -> Result<(), theme::Error> {
        theme::load_toml(content).map(|theme| self.set_theme(theme))
    }

    /// Sets the refresh rate, in frames per second.
    ///
    /// Note that the actual frequency is not guaranteed.
    ///
    /// Between 0 and 30. Call with `fps = 0` to disable (default value).
    pub fn set_fps(&mut self, fps: u32) {
        self.fps = NonZeroU32::new(fps);
    }

    /// Enables or disables automatic refresh of the screen.
    ///
    /// This is a shortcut to call `set_fps` with `30` or `0` depending on
    /// `autorefresh`.
    pub fn set_autorefresh(&mut self, autorefresh: bool) {
        self.set_fps(if autorefresh { 30 } else { 0 });
    }

    /// Returns a reference to the currently active screen.
    pub fn screen(&self) -> &views::StackView {
        self.root.get_inner().screen().unwrap()
    }

    /// Returns a mutable reference to the currently active screen.
    pub fn screen_mut(&mut self) -> &mut views::StackView {
        self.root.get_inner_mut().screen_mut().unwrap()
    }

    /// Returns the id of the currently active screen.
    pub fn active_screen(&self) -> ScreenId {
        self.root.get_inner().active_screen()
    }

    /// Adds a new screen, and returns its ID.
    pub fn add_screen(&mut self) -> ScreenId {
        self.root
            .get_inner_mut()
            .add_screen(views::StackView::new())
    }

    /// Convenient method to create a new screen, and set it as active.
    pub fn add_active_screen(&mut self) -> ScreenId {
        let res = self.add_screen();
        self.set_screen(res);
        res
    }

    /// Sets the active screen. Panics if no such screen exist.
    pub fn set_screen(&mut self, screen_id: ScreenId) {
        self.root.get_inner_mut().set_active_screen(screen_id);
    }

    /// Tries to find the view pointed to by the given selector.
    ///
    /// Runs a closure on the view once it's found, and return the
    /// result.
    ///
    /// If the view is not found, or if it is not of the asked type,
    /// returns None.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use cursive_core::{Cursive, views, view};
    /// # use cursive_core::traits::*;
    /// let mut siv = Cursive::dummy();
    ///
    /// siv.add_layer(views::TextView::new("Text #1").with_name("text"));
    ///
    /// siv.add_global_callback('p', |s| {
    ///     s.call_on(
    ///         &view::Selector::Id("text"),
    ///         |view: &mut views::TextView| {
    ///             view.set_content("Text #2");
    ///         },
    ///     );
    /// });
    /// ```
    pub fn call_on<V, F, R>(
        &mut self,
        sel: &view::Selector<'_>,
        callback: F,
    ) -> Option<R>
    where
        V: View,
        F: FnOnce(&mut V) -> R,
    {
        self.root.call_on(sel, callback)
    }

    /// Tries to find the view identified by the given id.
    ///
    /// Convenient method to use `call_on` with a `view::Selector::Id`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use cursive_core::{Cursive, views};
    /// # use cursive_core::traits::*;
    /// let mut siv = Cursive::dummy();
    ///
    /// siv.add_layer(views::TextView::new("Text #1")
    ///                               .with_name("text"));
    ///
    /// siv.add_global_callback('p', |s| {
    ///     s.call_on_name("text", |view: &mut views::TextView| {
    ///         view.set_content("Text #2");
    ///     });
    /// });
    /// ```
    pub fn call_on_name<V, F, R>(
        &mut self,
        name: &str,
        callback: F,
    ) -> Option<R>
    where
        V: View,
        F: FnOnce(&mut V) -> R,
    {
        self.call_on(&view::Selector::Name(name), callback)
    }

    /// Same as [`call_on_name`](Cursive::call_on_name).
    #[deprecated(note = "`call_on_id` is being renamed to `call_on_name`")]
    pub fn call_on_id<V, F, R>(&mut self, id: &str, callback: F) -> Option<R>
    where
        V: View,
        F: FnOnce(&mut V) -> R,
    {
        self.call_on_name(id, callback)
    }

    /// Convenient method to find a view wrapped in [`NamedView`].
    ///
    /// This looks for a `NamedView<V>` with the given name, and return
    /// a [`ViewRef`] to the wrapped view. The `ViewRef` implements
    /// `DerefMut<Target=T>`, so you can treat it just like a `&mut T`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use cursive_core::Cursive;
    /// # use cursive_core::views::{TextView, ViewRef};
    /// # let mut siv = Cursive::dummy();
    /// use cursive_core::traits::Identifiable;
    ///
    /// siv.add_layer(TextView::new("foo").with_name("id"));
    ///
    /// // Could be called in a callback
    /// let mut view: ViewRef<TextView> = siv.find_name("id").unwrap();
    /// view.set_content("bar");
    /// ```
    ///
    /// Note that you must specify the exact type for the view you're after; for example, using the
    /// wrong item type in a `SelectView` will not find anything:
    ///
    /// ```rust
    /// # use cursive_core::Cursive;
    /// # use cursive_core::views::{SelectView};
    /// # let mut siv = Cursive::dummy();
    /// use cursive_core::traits::Identifiable;
    ///
    /// let select = SelectView::new().item("zero", 0u32).item("one", 1u32);
    /// siv.add_layer(select.with_name("select"));
    ///
    /// // Specifying a wrong type will not return anything.
    /// assert!(siv.find_name::<SelectView<String>>("select").is_none());
    ///
    /// // Omitting the type will use the default type, in this case `String`.
    /// assert!(siv.find_name::<SelectView>("select").is_none());
    ///
    /// // But with the correct type, it works fine.
    /// assert!(siv.find_name::<SelectView<u32>>("select").is_some());
    /// ```
    ///
    /// [`NamedView`]: views::NamedView
    /// [`ViewRef`]: views::ViewRef
    pub fn find_name<V>(&mut self, id: &str) -> Option<views::ViewRef<V>>
    where
        V: View,
    {
        self.call_on_name(id, views::NamedView::<V>::get_mut)
    }

    /// Same as [`find_name`](Cursive::find_name).
    #[deprecated(note = "`find_id` is being renamed to `find_name`")]
    pub fn find_id<V>(&mut self, id: &str) -> Option<views::ViewRef<V>>
    where
        V: View,
    {
        self.find_name(id)
    }

    /// Moves the focus to the view identified by `name`.
    ///
    /// Convenient method to call `focus` with a [`view::Selector::Name`].
    pub fn focus_name(&mut self, name: &str) -> Result<(), ()> {
        self.focus(&view::Selector::Name(name))
    }

    /// Same as [`focus_name`](Cursive::focus_name).
    #[deprecated(note = "`focus_id` is being renamed to `focus_name`")]
    pub fn focus_id(&mut self, id: &str) -> Result<(), ()> {
        self.focus(&view::Selector::Name(id))
    }

    /// Moves the focus to the view identified by `sel`.
    pub fn focus(&mut self, sel: &view::Selector<'_>) -> Result<(), ()> {
        self.root.focus_view(sel)
    }

    /// Adds a global callback.
    ///
    /// Will be triggered on the given key press when no view catches it.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use cursive_core::*;
    /// let mut siv = Cursive::dummy();
    ///
    /// siv.add_global_callback('q', |s| s.quit());
    /// ```
    pub fn add_global_callback<F, E: Into<Event>>(&mut self, event: E, cb: F)
    where
        F: FnMut(&mut Cursive) + 'static,
    {
        self.set_on_post_event(event.into(), cb);
    }

    /// Registers a callback for ignored events.
    ///
    /// This is the same as `add_global_callback`, but can register any `EventTrigger`.
    pub fn set_on_post_event<F, E>(&mut self, trigger: E, cb: F)
    where
        F: FnMut(&mut Cursive) + 'static,
        E: Into<crate::event::EventTrigger>,
    {
        self.root.set_on_event(trigger, crate::immut1!(cb));
    }

    /// Registers a priotity callback.
    ///
    /// If an event matches the given trigger, it will not be sent to the view
    /// tree and will go to the given callback instead.
    ///
    /// Note that regular "post-event" callbacks will also be skipped for
    /// these events.
    pub fn set_on_pre_event<F, E>(&mut self, trigger: E, cb: F)
    where
        F: FnMut(&mut Cursive) + 'static,
        E: Into<crate::event::EventTrigger>,
    {
        self.root.set_on_pre_event(trigger, crate::immut1!(cb));
    }

    /// Registers an inner priority callback.
    ///
    /// See [`OnEventView`] for more information.
    ///
    /// [`OnEventView`]: crate::views::OnEventView::set_on_pre_event_inner()
    pub fn set_on_pre_event_inner<E, F>(&mut self, trigger: E, cb: F)
    where
        E: Into<crate::event::EventTrigger>,
        F: Fn(&Event) -> Option<EventResult> + 'static,
    {
        self.root
            .set_on_pre_event_inner(trigger, move |_, event| cb(event));
    }

    /// Registers an inner callback.
    ///
    /// See [`OnEventView`] for more information.
    ///
    /// [`OnEventView`]: crate::views::OnEventView::set_on_event_inner()
    pub fn set_on_event_inner<E, F>(&mut self, trigger: E, cb: F)
    where
        E: Into<crate::event::EventTrigger>,
        F: Fn(&Event) -> Option<EventResult> + 'static,
    {
        self.root
            .set_on_event_inner(trigger, move |_, event| cb(event));
    }

    /// Sets the only global callback for the given event.
    ///
    /// Any other callback for this event will be removed.
    ///
    /// See also [`Cursive::add_global_callback`].
    pub fn set_global_callback<F, E: Into<Event>>(&mut self, event: E, cb: F)
    where
        F: FnMut(&mut Cursive) + 'static,
    {
        let event = event.into();
        self.clear_global_callbacks(event.clone());
        self.add_global_callback(event, cb);
    }

    /// Fetches the type name of a view in the tree.
    pub fn debug_name(&mut self, name: &str) -> Option<&'static str> {
        let mut result = None;

        self.root.call_on_any(
            &view::Selector::Name(name),
            &mut |v: &mut dyn crate::View| result = Some(v.type_name()),
        );
        result
    }

    /// Removes any callback tied to the given event.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cursive_core::Cursive;
    /// let mut siv = Cursive::dummy();
    ///
    /// siv.add_global_callback('q', |s| s.quit());
    /// siv.clear_global_callbacks('q');
    /// ```
    pub fn clear_global_callbacks<E>(&mut self, event: E)
    where
        E: Into<Event>,
    {
        let event = event.into();
        self.root.clear_event(event);
    }

    /// This resets the default callbacks.
    ///
    /// Currently this mostly includes exiting on Ctrl-C.
    pub fn reset_default_callbacks(&mut self) {
        self.set_on_pre_event(Event::CtrlChar('c'), |s| s.quit());
        self.set_on_pre_event(Event::Exit, |s| s.quit());

        self.set_on_pre_event(Event::WindowResize, |s| s.clear());
    }

    /// Add a layer to the current screen.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cursive_core::{Cursive, views};
    /// let mut siv = Cursive::dummy();
    ///
    /// siv.add_layer(views::TextView::new("Hello world!"));
    /// ```
    pub fn add_layer<T>(&mut self, view: T)
    where
        T: IntoBoxedView,
    {
        self.screen_mut().add_layer(view);
    }

    /// Adds a new full-screen layer to the current screen.
    ///
    /// Fullscreen layers have no shadow.
    pub fn add_fullscreen_layer<T>(&mut self, view: T)
    where
        T: IntoBoxedView,
    {
        self.screen_mut().add_fullscreen_layer(view);
    }

    /// Convenient method to remove a layer from the current screen.
    pub fn pop_layer(&mut self) -> Option<Box<dyn View>> {
        self.screen_mut().pop_layer()
    }

    /// Convenient stub forwarding layer repositioning.
    pub fn reposition_layer(
        &mut self,
        layer: LayerPosition,
        position: Position,
    ) {
        self.screen_mut().reposition_layer(layer, position);
    }

    /// Processes an event.
    ///
    /// * If the menubar is active, it will be handled the event.
    /// * The view tree will be handled the event.
    /// * If ignored, global_callbacks will be checked for this event.
    pub fn on_event(&mut self, event: Event) {
        if let Event::Mouse {
            event, position, ..
        } = event
        {
            if event.grabs_focus()
                && !self.menubar.autohide
                && !self.menubar.has_submenu()
                && position.y == 0
            {
                self.select_menubar();
            }
        }

        if self.menubar.receive_events() {
            self.menubar.on_event(event).process(self);
        } else {
            let offset = if self.menubar.autohide { 0 } else { 1 };

            let result =
                View::on_event(&mut self.root, event.relativized((0, offset)));

            if let EventResult::Consumed(Some(cb)) = result {
                cb(self);
            }
        }
    }

    /// Returns the size of the screen, in characters.
    pub fn screen_size(&self) -> Vec2 {
        self.backend.screen_size()
    }

    fn layout(&mut self) {
        let size = self.screen_size();
        let offset = if self.menubar.autohide { 0 } else { 1 };
        let size = size.saturating_sub((0, offset));
        self.root.layout(size);
    }

    fn draw(&mut self) {
        // TODO: do not allocate in the default, fast path?
        let sizes = self.screen().layer_sizes();
        if self.last_sizes != sizes {
            // TODO: Maybe we only need to clear if the _max_ size differs?
            // Or if the positions change?
            self.clear();
            self.last_sizes = sizes;
        }

        let printer =
            Printer::new(self.screen_size(), &self.theme, &*self.backend);

        let selected = self.menubar.receive_events();

        // Print the stackview background before the menubar
        let offset = if self.menubar.autohide { 0 } else { 1 };

        let sv_printer = printer.offset((0, offset)).focused(!selected);
        self.root.draw(&sv_printer);

        self.root.get_inner().draw_bg(&sv_printer);

        // Draw the currently active screen
        // If the menubar is active, nothing else can be.
        // Draw the menubar?
        if self.menubar.visible() {
            let printer = printer.focused(self.menubar.receive_events());
            self.menubar.draw(&printer);
        }

        // finally draw stackview layers
        // using variables from above
        self.root.get_inner().draw_fg(&sv_printer);
    }

    /// Returns `true` until [`quit(&mut self)`] is called.
    ///
    /// [`quit(&mut self)`]: #method.quit
    pub fn is_running(&self) -> bool {
        self.running
    }

    /// Runs the event loop.
    ///
    /// It will wait for user input (key presses)
    /// and trigger callbacks accordingly.
    ///
    /// Internally, it calls [`step(&mut self)`] until [`quit(&mut self)`] is
    /// called.
    ///
    /// After this function returns, you can call it again and it will start a
    /// new loop.
    ///
    /// [`step(&mut self)`]: #method.step
    /// [`quit(&mut self)`]: #method.quit
    pub fn run(&mut self) {
        self.running = true;

        self.refresh();

        // And the big event loop begins!
        while self.running {
            self.step();
        }
    }

    /// Performs a single step from the event loop.
    ///
    /// Useful if you need tighter control on the event loop.
    /// Otherwise, [`run(&mut self)`] might be more convenient.
    ///
    /// Returns `true` if an input event or callback was received
    /// during this step, and `false` otherwise.
    ///
    /// [`run(&mut self)`]: #method.run
    pub fn step(&mut self) -> bool {
        let received_something = self.process_events();
        self.post_events(received_something);
        received_something
    }

    /// Performs the first half of `Self::step()`.
    ///
    /// This is an advanced method for fine-tuned manual stepping;
    /// you probably want [`run`][1] or [`step`][2].
    ///
    /// This processes any pending event or callback. After calling this,
    /// you will want to call [`post_events`][3] with the result from this
    /// function.
    ///
    /// Returns `true` if an event or callback was received,
    /// and `false` otherwise.
    ///
    /// [1]: Cursive::run()
    /// [2]: Cursive::step()
    /// [3]: Cursive::post_events()
    pub fn process_events(&mut self) -> bool {
        // Things are boring if nothing significant happened.
        let mut boring = true;

        // First, handle all available input
        while let Some(event) = self.backend.poll_event() {
            boring = false;
            self.on_event(event);

            if !self.running {
                return true;
            }
        }

        // Then, handle any available callback
        while let Ok(cb) = self.cb_source.try_recv() {
            boring = false;
            cb(self);

            if !self.running {
                return true;
            }
        }

        !boring
    }

    /// Performs the second half of `Self::step()`.
    ///
    /// This is an advanced method for fine-tuned manual stepping;
    /// you probably want [`run`][1] or [`step`][2].
    ///
    /// You should call this after [`process_events`][3].
    ///
    /// [1]: Cursive::run()
    /// [2]: Cursive::step()
    /// [3]: Cursive::process_events()
    pub fn post_events(&mut self, received_something: bool) {
        let boring = !received_something;
        // How many times should we try if it's still boring?
        // Total duration will be INPUT_POLL_DELAY_MS * repeats
        // So effectively fps = 1000 / INPUT_POLL_DELAY_MS / repeats
        if !boring
            || self
                .fps
                .map(|fps| 1000 / INPUT_POLL_DELAY_MS as u32 / fps.get())
                .map(|repeats| self.boring_frame_count >= repeats)
                .unwrap_or(false)
        {
            // We deserve to draw something!

            if boring {
                // We're only here because of a timeout.
                self.on_event(Event::Refresh);
            }

            self.refresh();
        }

        if boring {
            std::thread::sleep(Duration::from_millis(INPUT_POLL_DELAY_MS));
            self.boring_frame_count += 1;
        }
    }

    /// Refresh the screen with the current view tree state.
    pub fn refresh(&mut self) {
        self.boring_frame_count = 0;

        // Do we need to redraw everytime?
        // Probably, actually.
        // TODO: Do we need to re-layout everytime?
        self.layout();

        // TODO: Do we need to redraw every view every time?
        // (Is this getting repetitive? :p)
        self.draw();
        self.backend.refresh();
    }

    /// Stops the event loop.
    pub fn quit(&mut self) {
        self.running = false;
    }

    /// Does not do anything.
    pub fn noop(&mut self) {
        // foo
    }

    /// Return the name of the backend used.
    ///
    /// Mostly used for debugging.
    pub fn backend_name(&self) -> &str {
        self.backend.name()
    }

    /// Dump the current state of the Cursive root.
    ///
    /// *It will clear out this `Cursive` instance* and save everything, including:
    /// * The view tree
    /// * Callbacks
    /// * Menubar
    /// * User data
    /// * Callback sink
    ///
    /// After calling this, the cursive object will be as if newly created.
    pub fn dump(&mut self) -> crate::Dump {
        let (cb_sink, cb_source) = crossbeam_channel::unbounded();
        let root = views::OnEventView::new(views::ScreensView::single_screen(
            views::StackView::new(),
        ));
        Dump {
            cb_sink: std::mem::replace(&mut self.cb_sink, cb_sink),
            cb_source: std::mem::replace(&mut self.cb_source, cb_source),
            fps: self.fps.take(),
            menubar: std::mem::take(&mut self.menubar),
            root_view: std::mem::replace(&mut self.root, root),
            theme: std::mem::take(&mut self.theme),
            user_data: std::mem::replace(&mut self.user_data, Box::new(())),
        }
    }

    /// Restores the state from a previous dump.
    ///
    /// This will discard everything from this `Cursive` instance.
    /// In particular:
    /// * All current views will be dropped, replaced by the dump.
    /// * All callbacks will be replaced.
    /// * Menubar will be replaced.
    /// * User Data will be replaced.
    /// * The callback channel will be replaced - any previous call to
    ///   `cb_sink` on this instance will be disconnected.
    pub fn restore(&mut self, dump: Dump) {
        self.cb_sink = dump.cb_sink;
        self.cb_source = dump.cb_source;
        self.fps = dump.fps;
        self.menubar = dump.menubar;
        self.root = dump.root_view;
        self.theme = dump.theme;
        self.user_data = dump.user_data;
        self.clear();
    }
}

impl Drop for Cursive {
    fn drop(&mut self) {
        self.backend.finish();
    }
}


text:
<!DOCTYPE HTML>

    <meta charset="utf-8">
    <title>HelloWorld</title>
    <meta name="viewport"
          content="width=device-width,initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no,target-densitydpi=device-dpi"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>

    <meta name="full-screen" content="true"/>
    <meta name="screen-orientation" content="portrait"/>
    <meta name="x5-fullscreen" content="true"/>
    <meta name="360-fullscreen" content="true"/>
    <base href="../"/>


text:
'use strict';

import nls = require('vs/nls');
import { readFile } from 'vs/base/node/pfs';
import * as semver from 'semver';
import * as path from 'path';
import Event, { Emitter, chain } from 'vs/base/common/event';
import { index } from 'vs/base/common/arrays';
import { LinkedMap as Map } from 'vs/base/common/map';
import { assign } from 'vs/base/common/objects';
import { ThrottledDelayer } from 'vs/base/common/async';
import { isPromiseCanceledError } from 'vs/base/common/errors';
import { TPromise } from 'vs/base/common/winjs.base';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { IPager, mapPager, singlePagePager } from 'vs/base/common/paging';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import {
	IExtensionManagementService, IExtensionGalleryService, ILocalExtension, IGalleryExtension, IQueryOptions, IExtensionManifest,
	InstallExtensionEvent, DidInstallExtensionEvent, LocalExtensionType, DidUninstallExtensionEvent, IExtensionEnablementService, IExtensionTipsService
} from 'vs/platform/extensionManagement/common/extensionManagement';
import { getGalleryExtensionIdFromLocal, getGalleryExtensionTelemetryData, getLocalExtensionTelemetryData } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IChoiceService, IMessageService } from 'vs/platform/message/common/message';
import Severity from 'vs/base/common/severity';
import URI from 'vs/base/common/uri';
import { IExtension, IExtensionDependencies, ExtensionState, IExtensionsWorkbenchService, IExtensionsConfiguration, ConfigurationKey } from 'vs/workbench/parts/extensions/common/extensions';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IURLService } from 'vs/platform/url/common/url';
import { ExtensionsInput } from 'vs/workbench/parts/extensions/common/extensionsInput';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import product from 'vs/platform/node/product';

interface IExtensionStateProvider {
	(extension: Extension): ExtensionState;
}

class Extension implements IExtension {

	public disabledGlobally = false;
	public disabledForWorkspace = false;

	constructor(
		private galleryService: IExtensionGalleryService,
		private stateProvider: IExtensionStateProvider,
		public local: ILocalExtension,
		public gallery: IGalleryExtension = null
	) { }

	get type(): LocalExtensionType {
		return this.local ? this.local.type : null;
	}

	get name(): string {
		return this.gallery ? this.gallery.name : this.local.manifest.name;
	}

	get displayName(): string {
		if (this.gallery) {
			return this.gallery.displayName || this.gallery.name;
		}

		return this.local.manifest.displayName || this.local.manifest.name;
	}

	get id(): string {
		if (this.gallery) {
			return this.gallery.id;
		}
		return getGalleryExtensionIdFromLocal(this.local);
	}

	get publisher(): string {
		return this.gallery ? this.gallery.publisher : this.local.manifest.publisher;
	}

	get publisherDisplayName(): string {
		if (this.gallery) {
			return this.gallery.publisherDisplayName || this.gallery.publisher;
		}

		if (this.local.metadata && this.local.metadata.publisherDisplayName) {
			return this.local.metadata.publisherDisplayName;
		}

		return this.local.manifest.publisher;
	}

	get version(): string {
		return this.local ? this.local.manifest.version : this.gallery.version;
	}

	get latestVersion(): string {
		return this.gallery ? this.gallery.version : this.local.manifest.version;
	}

	get description(): string {
		return this.gallery ? this.gallery.description : this.local.manifest.description;
	}

	get url(): string {
		if (!product.extensionsGallery) {
			return null;
		}

		return `${product.extensionsGallery.itemUrl}?itemName=${this.publisher}.${this.name}`;
	}

	get iconUrl(): string {
		return this.galleryIconUrl || this.localIconUrl || this.defaultIconUrl;
	}

	get iconUrlFallback(): string {
		return this.galleryIconUrlFallback || this.localIconUrl || this.defaultIconUrl;
	}

	private get localIconUrl(): string {
		return this.local && this.local.manifest.icon
			&& URI.file(path.join(this.local.path, this.local.manifest.icon)).toString();
	}

	private get galleryIconUrl(): string {
		return this.gallery && this.gallery.assets.icon.uri;
	}

	private get galleryIconUrlFallback(): string {
		return this.gallery && this.gallery.assets.icon.fallbackUri;
	}

	private get defaultIconUrl(): string {
		return require.toUrl('../browser/media/defaultIcon.png');
	}

	get licenseUrl(): string {
		return this.gallery && this.gallery.assets.license && this.gallery.assets.license.uri;
	}

	get state(): ExtensionState {
		return this.stateProvider(this);
	}

	get installCount(): number {
		return this.gallery ? this.gallery.installCount : null;
	}

	get rating(): number {
		return this.gallery ? this.gallery.rating : null;
	}

	get ratingCount(): number {
		return this.gallery ? this.gallery.ratingCount : null;
	}

	get outdated(): boolean {
		return !!this.gallery && this.type === LocalExtensionType.User && semver.gt(this.latestVersion, this.version);
	}

	get telemetryData(): any {
		const { local, gallery } = this;

		if (gallery) {
			return getGalleryExtensionTelemetryData(gallery);
		} else {
			return getLocalExtensionTelemetryData(local);
		}
	}

	getManifest(): TPromise<IExtensionManifest> {
		if (this.gallery) {
			return this.galleryService.getManifest(this.gallery);
		}

		return TPromise.as(this.local.manifest);
	}

	getReadme(): TPromise<string> {
		if (this.gallery) {
			return this.galleryService.getReadme(this.gallery);
		}

		if (this.local && this.local.readmeUrl) {
			const uri = URI.parse(this.local.readmeUrl);
			return readFile(uri.fsPath, 'utf8');
		}

		return TPromise.wrapError<string>('not available');
	}

	getChangelog(): TPromise<string> {
		if (this.gallery && this.gallery.assets.changelog) {
			return this.galleryService.getChangelog(this.gallery);
		}

		const changelogUrl = this.local && this.local.changelogUrl;

		if (!changelogUrl) {
			return TPromise.wrapError<string>('not available');
		}

		const uri = URI.parse(changelogUrl);

		if (uri.scheme === 'file') {
			return readFile(uri.fsPath, 'utf8');
		}

		return TPromise.wrapError<string>('not available');
	}

	get dependencies(): string[] {
		const { local, gallery } = this;
		if (local && local.manifest.extensionDependencies) {
			return local.manifest.extensionDependencies;
		}
		if (gallery) {
			return gallery.properties.dependencies;
		}
		return [];
	}
}

class ExtensionDependencies implements IExtensionDependencies {

	private _hasDependencies: boolean = null;

	constructor(private _extension: IExtension, private _identifier: string, private _map: Map<string, IExtension>, private _dependent: IExtensionDependencies = null) { }

	get hasDependencies(): boolean {
		if (this._hasDependencies === null) {
			this._hasDependencies = this.computeHasDependencies();
		}
		return this._hasDependencies;
	}

	get extension(): IExtension {
		return this._extension;
	}

	get identifier(): string {
		return this._identifier;
	}

	get dependent(): IExtensionDependencies {
		return this._dependent;
	}

	get dependencies(): IExtensionDependencies[] {
		if (!this.hasDependencies) {
			return [];
		}
		return this._extension.dependencies.map(d => new ExtensionDependencies(this._map.get(d), d, this._map, this));
	}

	private computeHasDependencies(): boolean {
		if (this._extension && this._extension.dependencies.length > 0) {
			let dependent = this._dependent;
			while (dependent !== null) {
				if (dependent.identifier === this.identifier) {
					return false;
				}
				dependent = dependent.dependent;
			}
			return true;
		}
		return false;
	}
}

enum Operation {
	Installing,
	Updating,
	Uninstalling
}

interface IActiveExtension {
	operation: Operation;
	extension: Extension;
	start: Date;
}

function toTelemetryEventName(operation: Operation) {
	switch (operation) {
		case Operation.Installing: return 'extensionGallery:install';
		case Operation.Updating: return 'extensionGallery:update';
		case Operation.Uninstalling: return 'extensionGallery:uninstall';
	}

	return '';
}

export class ExtensionsWorkbenchService implements IExtensionsWorkbenchService {

	private static SyncPeriod = 1000 * 60 * 60 * 12; // 12 hours

	_serviceBrand: any;
	private stateProvider: IExtensionStateProvider;
	private installing: IActiveExtension[] = [];
	private uninstalling: IActiveExtension[] = [];
	private installed: Extension[] = [];
	private syncDelayer: ThrottledDelayer<void>;
	private autoUpdateDelayer: ThrottledDelayer<void>;
	private disposables: IDisposable[] = [];

	private _onChange: Emitter<void> = new Emitter<void>();
	get onChange(): Event<void> { return this._onChange.event; }

	constructor(
		@IInstantiationService private instantiationService: IInstantiationService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IExtensionManagementService private extensionService: IExtensionManagementService,
		@IExtensionGalleryService private galleryService: IExtensionGalleryService,
		@IConfigurationService private configurationService: IConfigurationService,
		@ITelemetryService private telemetryService: ITelemetryService,
		@IMessageService private messageService: IMessageService,
		@IChoiceService private choiceService: IChoiceService,
		@IURLService urlService: IURLService,
		@IExtensionEnablementService private extensionEnablementService: IExtensionEnablementService,
		@IExtensionTipsService private tipsService: IExtensionTipsService,
		@IWorkspaceContextService private workspaceContextService: IWorkspaceContextService,
	) {
		this.stateProvider = ext => this.getExtensionState(ext);

		extensionService.onInstallExtension(this.onInstallExtension, this, this.disposables);
		extensionService.onDidInstallExtension(this.onDidInstallExtension, this, this.disposables);
		extensionService.onUninstallExtension(this.onUninstallExtension, this, this.disposables);
		extensionService.onDidUninstallExtension(this.onDidUninstallExtension, this, this.disposables);
		extensionEnablementService.onEnablementChanged(this.onEnablementChanged, this, this.disposables);

		this.syncDelayer = new ThrottledDelayer<void>(ExtensionsWorkbenchService.SyncPeriod);
		this.autoUpdateDelayer = new ThrottledDelayer<void>(1000);

		chain(urlService.onOpenURL)
			.filter(uri => /^extension/.test(uri.path))
			.on(this.onOpenExtensionUrl, this, this.disposables);

		this.queryLocal().done(() => this.eventuallySyncWithGallery(true));
	}

	get local(): IExtension[] {
		const installing = this.installing
			.filter(e => !this.installed.some(installed => installed.id === e.extension.id))
			.map(e => e.extension);

		return [...this.installed, ...installing];
	}

	queryLocal(): TPromise<IExtension[]> {
		return this.extensionService.getInstalled().then(result => {
			const installedById = index(this.installed, e => e.local.id);
			const globallyDisabledExtensions = this.extensionEnablementService.getGloballyDisabledExtensions();
			const workspaceDisabledExtensions = this.extensionEnablementService.getWorkspaceDisabledExtensions();
			this.installed = result.map(local => {
				const extension = installedById[local.id] || new Extension(this.galleryService, this.stateProvider, local);
				extension.local = local;
				extension.disabledGlobally = globallyDisabledExtensions.indexOf(extension.id) !== -1;
				extension.disabledForWorkspace = workspaceDisabledExtensions.indexOf(extension.id) !== -1;
				return extension;
			});

			this._onChange.fire();
			return this.local;
		});
	}

	queryGallery(options: IQueryOptions = {}): TPromise<IPager<IExtension>> {
		return this.galleryService.query(options)
			.then(result => mapPager(result, gallery => this.fromGallery(gallery)))
			.then(null, err => {
				if (/No extension gallery service configured/.test(err.message)) {
					return TPromise.as(singlePagePager([]));
				}

				return TPromise.wrapError<IPager<IExtension>>(err);
			});
	}

	loadDependencies(extension: IExtension): TPromise<IExtensionDependencies> {
		if (!extension.dependencies.length) {
			return TPromise.wrap<IExtensionDependencies>(null);
		}

		return this.galleryService.getAllDependencies((<Extension>extension).gallery)
			.then(galleryExtensions => galleryExtensions.map(galleryExtension => this.fromGallery(galleryExtension)))
			.then(extensions => [...this.local, ...extensions])
			.then(extensions => {
				const map = new Map<string, IExtension>();
				for (const extension of extensions) {
					map.set(extension.id, extension);
				}
				return new ExtensionDependencies(extension, extension.id, map);
			});
	}

	open(extension: IExtension, sideByside: boolean = false): TPromise<any> {
		return this.editorService.openEditor(this.instantiationService.createInstance(ExtensionsInput, extension), null, sideByside);
	}

	private fromGallery(gallery: IGalleryExtension): Extension {
		const installed = this.installed.filter(installed => installed.id === gallery.id)[0];

		if (installed) {
			// Loading the compatible version only there is an engine property
			// Otherwise falling back to old way so that we will not make many roundtrips
			if (gallery.properties.engine) {
				this.galleryService.loadCompatibleVersion(gallery).then(compatible => this.syncLocalWithGalleryExtension(installed, compatible));
			} else {
				this.syncLocalWithGalleryExtension(installed, gallery);
			}
			return installed;
		}

		return new Extension(this.galleryService, this.stateProvider, null, gallery);
	}

	private syncLocalWithGalleryExtension(local: Extension, gallery: IGalleryExtension) {
		local.gallery = gallery;
		this._onChange.fire();
		this.eventuallyAutoUpdateExtensions();
	}

	checkForUpdates(): TPromise<void> {
		return this.syncDelayer.trigger(() => this.syncWithGallery(), 0);
	}

	private eventuallySyncWithGallery(immediate = false): void {
		const loop = () => this.syncWithGallery().then(() => this.eventuallySyncWithGallery());
		const delay = immediate ? 0 : ExtensionsWorkbenchService.SyncPeriod;

		this.syncDelayer.trigger(loop, delay)
			.done(null, err => null);
	}

	private syncWithGallery(): TPromise<void> {
		const names = this.installed
			.filter(e => e.type === LocalExtensionType.User)
			.map(e => e.id);

		if (names.length === 0) {
			return TPromise.as(null);
		}

		return this.queryGallery({ names, pageSize: names.length }) as TPromise<any>;
	}

	private eventuallyAutoUpdateExtensions(): void {
		this.autoUpdateDelayer.trigger(() => this.autoUpdateExtensions())
			.done(null, err => null);
	}

	private autoUpdateExtensions(): TPromise<any> {
		const config = this.configurationService.getConfiguration<IExtensionsConfiguration>(ConfigurationKey);

		if (!config.autoUpdate) {
			return TPromise.as(null);
		}

		const toUpdate = this.local.filter(e => e.outdated && (e.state !== ExtensionState.Installing));
		return TPromise.join(toUpdate.map(e => this.install(e, false)));
	}

	canInstall(extension: IExtension): boolean {
		if (!(extension instanceof Extension)) {
			return false;
		}

		return !!(extension as Extension).gallery;
	}

	install(extension: string | IExtension, promptToInstallDependencies: boolean = true): TPromise<void> {
		if (typeof extension === 'string') {
			return this.extensionService.install(extension);
		}

		if (!(extension instanceof Extension)) {
			return undefined;
		}

		const ext = extension as Extension;
		const gallery = ext.gallery;

		if (!gallery) {
			return TPromise.wrapError<void>(new Error('Missing gallery'));
		}

		return this.extensionService.installFromGallery(gallery, promptToInstallDependencies);
	}

	setEnablement(extension: IExtension, enable: boolean, workspace: boolean = false): TPromise<any> {
		if (extension.type === LocalExtensionType.System) {
			return TPromise.wrap(null);
		}

		return this.promptAndSetEnablement(extension, enable, workspace).then(reload => {
			this.telemetryService.publicLog(enable ? 'extension:enable' : 'extension:disable', extension.telemetryData);
		});
	}

	uninstall(extension: IExtension): TPromise<void> {
		if (!(extension instanceof Extension)) {
			return undefined;
		}

		const ext = extension as Extension;
		const local = ext.local || this.installed.filter(e => e.id === extension.id)[0].local;

		if (!local) {
			return TPromise.wrapError<void>(new Error('Missing local'));
		}

		return this.extensionService.uninstall(local);

	}

	private promptAndSetEnablement(extension: IExtension, enable: boolean, workspace: boolean): TPromise<any> {
		const allDependencies = this.getDependenciesRecursively(extension, this.local, enable, workspace, []);
		if (allDependencies.length > 0) {
			if (enable) {
				return this.promptForDependenciesAndEnable(extension, allDependencies, workspace);
			} else {
				return this.promptForDependenciesAndDisable(extension, allDependencies, workspace);
			}
		}
		return this.checkAndSetEnablement(extension, [], enable, workspace);
	}

	private promptForDependenciesAndEnable(extension: IExtension, dependencies: IExtension[], workspace: boolean): TPromise<any> {
		const message = nls.localize('enableDependeciesConfirmation', "Enabling '{0}' also enable its dependencies. Would you like to continue?", extension.displayName);
		const options = [
			nls.localize('enable', "Yes"),
			nls.localize('doNotEnable', "No")
		];
		return this.choiceService.choose(Severity.Info, message, options, 1, true)
			.then<void>(value => {
				if (value === 0) {
					return this.checkAndSetEnablement(extension, dependencies, true, workspace);
				}
				return TPromise.as(null);
			});
	}

	private promptForDependenciesAndDisable(extension: IExtension, dependencies: IExtension[], workspace: boolean): TPromise<void> {
		const message = nls.localize('disableDependeciesConfirmation', "Would you like to disable '{0}' only or its dependencies also?", extension.displayName);
		const options = [
			nls.localize('disableOnly', "Only"),
			nls.localize('disableAll', "All"),
			nls.localize('cancel', "Cancel")
		];
		return this.choiceService.choose(Severity.Info, message, options, 2, true)
			.then<void>(value => {
				if (value === 0) {
					return this.checkAndSetEnablement(extension, [], false, workspace);
				}
				if (value === 1) {
					return this.checkAndSetEnablement(extension, dependencies, false, workspace);
				}
				return TPromise.as(null);
			});
	}

	private checkAndSetEnablement(extension: IExtension, dependencies: IExtension[], enable: boolean, workspace: boolean): TPromise<any> {
		if (!enable) {
			let dependents = this.getDependentsAfterDisablement(extension, dependencies, this.local, workspace);
			if (dependents.length) {
				return TPromise.wrapError<void>(this.getDependentsErrorMessage(extension, dependents));
			}
		}
		return TPromise.join([extension, ...dependencies].map(e => this.doSetEnablement(e, enable, workspace)));
	}

	private getDependenciesRecursively(extension: IExtension, installed: IExtension[], enable: boolean, workspace: boolean, checked: IExtension[]): IExtension[] {
		if (checked.indexOf(extension) !== -1) {
			return [];
		}
		checked.push(extension);
		if (!extension.dependencies || extension.dependencies.length === 0) {
			return [];
		}
		const dependenciesToDisable = installed.filter(i => {
			// Do not include extensions which are already disabled and request is to disable
			if (!enable && (workspace ? i.disabledForWorkspace : i.disabledGlobally)) {
				return false;
			}
			return i.type === LocalExtensionType.User && extension.dependencies.indexOf(i.id) !== -1;
		});
		const depsOfDeps = [];
		for (const dep of dependenciesToDisable) {
			depsOfDeps.push(...this.getDependenciesRecursively(dep, installed, enable, workspace, checked));
		}
		return [...dependenciesToDisable, ...depsOfDeps];
	}

	private getDependentsAfterDisablement(extension: IExtension, dependencies: IExtension[], installed: IExtension[], workspace: boolean): IExtension[] {
		return installed.filter(i => {
			if (i.dependencies.length === 0) {
				return false;
			}
			if (i === extension) {
				return false;
			}
			const disabled = workspace ? i.disabledForWorkspace : i.disabledGlobally;
			if (disabled) {
				return false;
			}
			if (dependencies.indexOf(i) !== -1) {
				return false;
			}
			return i.dependencies.some(dep => {
				if (extension.id === dep) {
					return true;
				}
				return dependencies.some(d => d.id === dep);
			});
		});
	}

	private getDependentsErrorMessage(extension: IExtension, dependents: IExtension[]): string {
		if (dependents.length === 1) {
			return nls.localize('singleDependentError', "Cannot disable extension '{0}'. Extension '{1}' depends on this.", extension.displayName, dependents[0].displayName);
		}
		if (dependents.length === 2) {
			return nls.localize('twoDependentsError', "Cannot disable extension '{0}'. Extensions '{1}' and '{2}' depend on this.",
				extension.displayName, dependents[0].displayName, dependents[1].displayName);
		}
		return nls.localize('multipleDependentsError', "Cannot disable extension '{0}'. Extensions '{1}', '{2}' and others depend on this.",
			extension.displayName, dependents[0].displayName, dependents[1].displayName);
	}

	private doSetEnablement(extension: IExtension, enable: boolean, workspace: boolean): TPromise<boolean> {
		if (workspace) {
			return this.extensionEnablementService.setEnablement(extension.id, enable, workspace);
		}

		const globalElablement = this.extensionEnablementService.setEnablement(extension.id, enable, false);
		if (enable && this.workspaceContextService.hasWorkspace()) {
			const workspaceEnablement = this.extensionEnablementService.setEnablement(extension.id, enable, true);
			return TPromise.join([globalElablement, workspaceEnablement]).then(values => values[0] || values[1]);
		}
		return globalElablement;
	}

	private onInstallExtension(event: InstallExtensionEvent): void {
		const { gallery } = event;

		if (!gallery) {
			return;
		}

		let extension = this.installed.filter(e => e.id === gallery.id)[0];

		if (!extension) {
			extension = new Extension(this.galleryService, this.stateProvider, null, gallery);
		}

		extension.gallery = gallery;

		const start = new Date();
		const operation = Operation.Installing;
		this.installing.push({ operation, extension, start });

		this._onChange.fire();
	}

	private onDidInstallExtension(event: DidInstallExtensionEvent): void {
		const { local, zipPath, error, gallery } = event;
		const installing = gallery ? this.installing.filter(e => e.extension.id === gallery.id)[0] : null;
		const extension: Extension = installing ? installing.extension : zipPath ? new Extension(this.galleryService, this.stateProvider, null) : null;
		if (extension) {
			this.installing = installing ? this.installing.filter(e => e !== installing) : this.installing;

			if (!error) {
				extension.local = local;

				const installed = this.installed.filter(e => e.id === extension.id)[0];
				if (installed) {
					if (installing) {
						installing.operation = Operation.Updating;
					}
					installed.local = local;
				} else {
					this.installed.push(extension);
				}
			}
			if (extension.gallery) {
				// Report telemetry only for gallery extensions
				this.reportTelemetry(installing, !error);
			}
		}
		this._onChange.fire();
	}

	private onUninstallExtension(id: string): void {
		const extension = this.installed.filter(e => e.local.id === id)[0];
		const newLength = this.installed.filter(e => e.local.id !== id).length;
		// TODO: Ask @Joao why is this?
		if (newLength === this.installed.length) {
			return;
		}

		const start = new Date();
		const operation = Operation.Uninstalling;
		const uninstalling = this.uninstalling.filter(e => e.extension.local.id === id)[0] || { id, operation, extension, start };
		this.uninstalling = [uninstalling, ...this.uninstalling.filter(e => e.extension.local.id !== id)];

		this._onChange.fire();
	}

	private onDidUninstallExtension({ id, error }: DidUninstallExtensionEvent): void {
		if (!error) {
			this.installed = this.installed.filter(e => e.local.id !== id);
		}

		const uninstalling = this.uninstalling.filter(e => e.extension.local.id === id)[0];
		this.uninstalling = this.uninstalling.filter(e => e.extension.local.id !== id);
		if (!uninstalling) {
			return;
		}

		if (!error) {
			this.reportTelemetry(uninstalling, true);
		}

		this._onChange.fire();
	}

	private onEnablementChanged(extensionIdentifier: string) {
		const [extension] = this.local.filter(e => e.id === extensionIdentifier);
		if (extension) {
			const globallyDisabledExtensions = this.extensionEnablementService.getGloballyDisabledExtensions();
			const workspaceDisabledExtensions = this.extensionEnablementService.getWorkspaceDisabledExtensions();
			extension.disabledGlobally = globallyDisabledExtensions.indexOf(extension.id) !== -1;
			extension.disabledForWorkspace = workspaceDisabledExtensions.indexOf(extension.id) !== -1;
			this._onChange.fire();
		}
	}

	private getExtensionState(extension: Extension): ExtensionState {
		if (extension.gallery && this.installing.some(e => e.extension.gallery && e.extension.gallery.id === extension.gallery.id)) {
			return ExtensionState.Installing;
		}

		if (this.uninstalling.some(e => e.extension.id === extension.id)) {
			return ExtensionState.Uninstalling;
		}

		const local = this.installed.filter(e => e === extension || (e.gallery && extension.gallery && e.gallery.id === extension.gallery.id))[0];
		return local ? ExtensionState.Installed : ExtensionState.Uninstalled;
	}

	private reportTelemetry(active: IActiveExtension, success: boolean): void {
		const data = active.extension.telemetryData;
		const duration = new Date().getTime() - active.start.getTime();
		const eventName = toTelemetryEventName(active.operation);

		this.telemetryService.publicLog(eventName, assign(data, { success, duration }));
	}

	private onError(err: any): void {
		if (isPromiseCanceledError(err)) {
			return;
		}

		const message = err && err.message || '';

		if (/getaddrinfo ENOTFOUND|getaddrinfo ENOENT|connect EACCES|connect ECONNREFUSED/.test(message)) {
			return;
		}

		this.messageService.show(Severity.Error, err);
	}

	private onOpenExtensionUrl(uri: URI): void {
		const match = /^extension\/([^/]+)$/.exec(uri.path);

		if (!match) {
			return;
		}

		const extensionId = match[1];

		this.queryGallery({ names: [extensionId] })
			.done(result => {
				if (result.total < 1) {
					return;
				}

				const extension = result.firstPage[0];
				const promises = [this.open(extension)];

				if (this.local.every(local => local.id !== extension.id)) {
					promises.push(this.install(extension));
				}

				TPromise.join(promises)
					.done(null, error => this.onError(error));
			});
	}

	dispose(): void {
		this.syncDelayer.cancel();
		this.disposables = dispose(this.disposables);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FSecure.Utils.ExtensionMethods
{
    public static class DateExtensions
    {
        public static DateTime DateTimeSince1970Utc {
            get
            {
                return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            }
        }
        public static long ToMillisecondsSince1970(this DateTime date)
        {
            var diff = date.ToUniversalTime().Subtract(DateTimeSince1970Utc);
            return (long)diff.TotalMilliseconds;
        }

        public static DateTime ToDateTimeFromMillisecondsSince1970(this long time)
        {
            var date = DateTimeSince1970Utc + TimeSpan.FromMilliseconds(time);

            return date;
        }

        public static long ToMillisecondsSince1970(this DateTimeOffset date)
        {
            var diff = date.UtcDateTime.Subtract(DateTimeSince1970Utc);
            return (long)diff.TotalMilliseconds;
        }

        public static DateTimeOffset ToDateTimeOffsetFromMillisecondsSince1970(this long time)
        {
            return new DateTimeOffset(time.ToDateTimeFromMillisecondsSince1970());
        }
    }
}


text:
module RailsWorkflow
  module ApplicationHelper
  end
end


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Config.Net.Stores.Formats.Ini
{
   class StructuredIniFile
   {
      private const string _sectionBegin = "[";
      private const string _sectionEnd = "]";
      private static readonly char[] _sectionTrims = {'[', ']'};

      private readonly IniSection _globalSection;
      private readonly List<IniSection> _sections = new List<IniSection>();
      private readonly Dictionary<string, IniKeyValue> _fullKeyNameToValue = new Dictionary<string, IniKeyValue>(StringComparer.InvariantCultureIgnoreCase);

      public StructuredIniFile()
      {
         _globalSection = new IniSection(null);
         _sections.Add(_globalSection);
      }

      public string? this[string key]
      {
         get
         {
            if(key == null) return null;

            IniKeyValue? value;
            return !_fullKeyNameToValue.TryGetValue(key, out value) ? null : value.Value;
         }
         set
         {
            if(key == null) return;

            IniSection.SplitKey(key, out string? sectionName, out string keyName);
            IniSection? section = sectionName == null
               ? _globalSection
               : _sections.FirstOrDefault(s => s.Name == sectionName);
            if(section == null)
            {
               section = new IniSection(sectionName);
               _sections.Add(section);
            }
            IniKeyValue? ikv = section.Set(keyName, value);

            //update the local cache
            if(ikv != null)
            {
               if(value == null)
               {
                  _fullKeyNameToValue.Remove(key);
               }
               else
               {
                  _fullKeyNameToValue[key] = ikv;
               }
            }
         }
      }

      public static StructuredIniFile ReadFrom(Stream inputStream, bool parseInlineComments, bool unescapeNewLines = false)
      {
         if(inputStream == null) throw new ArgumentNullException(nameof(inputStream));

         var file = new StructuredIniFile();

         using(var reader = new StreamReader(inputStream))
         {
            IniSection section = file._globalSection;

            string? line;
            while((line = reader.ReadLine()) != null)
            {
               line = line.Trim();

               if(line.StartsWith(_sectionBegin))
               {
                  //start new section
                  line = line.Trim();
                  section = new IniSection(line);
                  file._sections.Add(section);
               }
               else if(line.StartsWith(IniComment.CommentSeparator))
               {
                  //whole line is a comment
                  string comment = line.Substring(1).Trim();
                  section.Add(new IniComment(comment));
               }
               else
               {
                  IniKeyValue? ikv = IniKeyValue.FromLine(line, parseInlineComments, unescapeNewLines);
                  if(ikv == null) continue;

                  section.Add(ikv);
                  string fullKey = section.Name == null
                     ? ikv.Key
                     : $"{section.Name}{IniSection.SectionKeySeparator}{ikv.Key}";
                  file._fullKeyNameToValue[fullKey] = ikv;

               }
            }
         }

         return file;
      }

      public void WriteTo(Stream outputStream)
      {
         if(outputStream == null) throw new ArgumentNullException(nameof(outputStream));

         using(var writer = new StreamWriter(outputStream))
         {
            foreach(IniSection section in _sections)
            {
               if(section.Name != null)
               {
                  writer.WriteLine();
                  writer.WriteLine($"{_sectionBegin}{section.Name}{_sectionEnd}");
               }

               section.WriteTo(writer);
            }
         }
      }

      //private static
   }
}


text:
CatarsePaytech::Engine.routes.draw do
  namespace :payment do
    get '/paytech/:id/review' => 'paytech#review', :as => 'review_paytech'
    match '/paytech/:id/notifications' => 'paytech#notifications',  :as => 'notifications_paytech'
    match '/paytech/:id/pay'           => 'paytech#pay',            :as => 'pay_paytech'
    match '/paytech/:id/success'       => 'paytech#success',        :as => 'success_paytech'
    match '/paytech/:id/cancel'        => 'paytech#cancel',         :as => 'cancel_paytech'
  end
end


text:
author: dema
comments: true
date: 2008-11-20 10:03:03+00:00
layout: post
slug: tutti-a-roma-al-romecamp2008
title: 'Tutti a Roma al Romecamp2008 '
wordpress_id: 540
categories:
- barcamp
tags:
- barcamp
- roma
---

[![romecamp](http://dema.tv/wp-content/uploads/2008/11/romecamp1.jpg)](http://www.barcamp.org/romecamp2008)

Talk sul fututo della società , della tecnologia e dell'ambiente , sano cazzeggio annunciato , tanta gente.

Io sarò lì dalle 10 di Sabato 22 Novembre fino a notte fonda.


text:
var currentPage = 0;
var lineCtx = document.getElementById('line-analysis').getContext('2d');
var pieCtx = document.getElementById('pie-analysis').getContext('2d');
var deviceMap = {};
var lineData = {
  labels : [],
  datasets : [
    {
    fillColor : "rgba(220,220,220,0.5)",
    strokeColor : "rgba(220,220,220,1)",
    pointColor : "rgba(220,220,220,1)",
    pointStrokeColor : "#fff",
    data: []
    }
  ]
};
var pieData = []
var lineChart = new Chart(lineCtx);
var pieChart = new Chart(pieCtx);

var socket = io.connect('/');
var wattage;
$.getJSON('/api/usage', function(info){
  wattage = info.usage;
  $('#watts').html(wattage);
  setInterval(function(){
    variance = wattage + Math.round(Math.random() * 3);
    $('#watts').html(variance);
    // update lineData
    lineData.labels.push(moment().format('s'));
    lineData.datasets[0].data.push(variance);

    lineData.labels = lineData.labels.splice(-20);
    lineData.datasets[0].data = lineData.datasets[0].data.splice(-20);
    lineChart.Line(lineData, {animation: false, scaleOverride: true, scaleSteps: 15, scaleStartValue: 1800, scaleStepWidth: 200});

    // update pie data
    var pieData = [];
    for (var deviceName in deviceMap){
      if (deviceMap[deviceName].status === 'on')
        deviceMap[deviceName].value+= deviceMap[deviceName].power;
      pieData.push(deviceMap[deviceName]);
    }

    pieChart.Pie(pieData, {animation: false});
  }, 1000);
});
socket.on('update', function(newWattage){
  wattage = newWattage;
  console.log(wattage);
  $.getJSON('/api/guess/devices', function(devices){
    $('#question').html('Did you turn one of these on?').addClass('text-success');
    $('#buttons-container').empty();
    devices.forEach(function(device){
      $('#buttons-container').append('
<button class="btn btn-info btn-lg btn-block device-btn slideUp" data-name="' + device.name + '">' + device.name + '
</button>
');
    });
    $('#buttons-container').append('
<button class="btn btn-lg btn-block device-btn">Other...</button>
');
    $('#buttons-container').hide().fadeIn(1000);
    $('.device-btn').click(function(){
        $.post('/api/device', {name: $(this).data('name')}, function(){
          $('#question').html('Great!  Let\'s do another one!
 (Turn on another device)').removeClass('text-success');
          $('#buttons-container').empty();
        });
    });
  });
});
socket.on('device.on', function(device){
  deviceMap[device.name] = {
    value: device.power,
    power: device.power,
    label: device.name,
    status: 'on',
    labelColor: '#ffffff',
    color: getRandomColor()
  };
  $.bootstrapGrowl(device.name + ' just turned on');
});
socket.on('device.off', function(device){
  if (deviceMap[device.name]){
    deviceMap[device.name].status = "off";
  }
  $.bootstrapGrowl(device.name + ' just turned off');
});
$('#start-btn').click(function(){
  nextPage();
})
$('#continue-btn').click(function(){
  nextPage();
  $.post('/api/complete', {}, function(){
    $.getJSON('/api/devices', function(devices){
      console.log(devices);
      devices.forEach(function(device){
        deviceMap[device.name] = {
          value: device.power,
          power: device.power,
          status: 'on',
          label: device.name,
          labelColor: "#ffffff",
          color: getRandomColor()
        }
      });
    });
  });
});
function nextPage(){
  $('.page').hide();
  currentPage++;
  $('.page').eq(currentPage).show();
}
function getRandomColor() {
  var letters = '0123456789ABCDEF'.split('');
  var color = '#';
  for (var i = 0; i < 6; i++ ) {
    color += letters[Math.round(Math.random() * 15)];
  }
  return color;
}
$.post('/api/start');


text: function child(){alert('child');}


text:
import React from "react"

class RustSignUp extends React.Component {
  render() {
    return (

Rust For JavaScript Developers

Because learning Rust with a JavaScript background doesn't have to be hard.

          <form id="signup-form" method="post" className="thtrm-form u-distance-medium" action="https://gmail.us3.list-manage.com/subscribe/post?u=06cf39a53e3ac1a4db816a8f1&id=08cf21d77b" noValidate target="_blank">

              <input type="text" nane="FNAME" id="mce-FNAME" className="thtrm-form__input--text" placeholder="Your firstname" />
              <input type="email" name="EMAIL" id="mce-EMAIL" className="thtrm-form__input--text" placeholder="Your email" />

              <button type="submit" className="thtrm-button">Help me learn Rust!</button>

So you want to learn Rust?

              I started learning Rust out of curiosity with zero experience in systems programming. I know the pain. With Rust for JavaScript Developers I'm creating an online resource with free content about the Rust programming language, primarily (but not only) aimed at developers with a strong JavaScript background.

- @PascalPrecht

          </form>

    )
  }
}

export default RustSignUp


text:
FROM toopher/centos-i386:centos5
MAINTAINER Thomas Edwin Santosa <thomas@katalisindonesia.com>

# inspired from https://github.com/alclouds/docker-postgres8/

VOLUME /var/lib/pgsql
COPY start.sh /

COPY CentOS-510.repo /etc/yum.repos.d/

RUN rm /etc/yum.repos.d/CentOS-Base.repo
# install postgres 8.1.23
RUN sed -i 's/\$basearch/i386/g' /etc/yum.repos.d/CentOS-Vault.repo
RUN yum list postgresql-server
RUN yum -y update && yum -y install postgresql-server.i386 && yum -y reinstall glibc-common && yum -y clean all \
	&& chmod +x /start.sh

EXPOSE 5432/tcp

#Indonesian locale
RUN /usr/bin/localedef -f UTF-8 -i id_ID id_ID.UTF-8

CMD ["/start.sh"]


text:
package ru.job4j.control.models;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * class User - модель пользователя.
 */
public class User {
    /**
     * ID пользователя.
     */
    private int id;
    /**
     * Имя пользователя.
     */
    private String name;
    /**
     * Пароль пользователя.
     */
    private String password;
    /**
     * ID адреса пользователя.
     */
    private int addressId;
    /**
     * ID роли пользователя.
     */
    private int roleId;
    /**
     * Множество музыкальных предпочтений.
     */
    private Set<Integer> musicTypeId = new LinkedHashSet<>();

    /**
     * Setters and Getters.
     */

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAddressId() {
        return addressId;
    }

    public void setAddressId(int addressId) {
        this.addressId = addressId;
    }

    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Set<Integer> getMusicTypeId() {
        return musicTypeId;
    }

    public void setMusicTypeId(Set<Integer> musicType) {
        this.musicTypeId.addAll(musicType);
    }

    public void setMusicTypeId(int musicTypeId) {
        this.musicTypeId.add(musicTypeId);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        User user = (User) o;

        if (getId() != user.getId()) {
            return false;
        }
        if (getAddressId() != user.getAddressId()) {
            return false;
        }
        if (getRoleId() != user.getRoleId()) {
            return false;
        }
        if (getName() != null ? !getName().equals(user.getName()) : user.getName() != null) {
            return false;
        }
        if (getPassword() != null ? !getPassword().equals(user.getPassword()) : user.getPassword() != null) {
            return false;
        }

        return getMusicTypeId() != null ? getMusicTypeId().equals(user.getMusicTypeId()) : user.getMusicTypeId() == null;
    }

    @Override
    public int hashCode() {
        int result = getId();
        result = 31 * result + (getName() != null ? getName().hashCode() : 0);
        result = 31 * result + (getPassword() != null ? getPassword().hashCode() : 0);
        result = 31 * result + getAddressId();
        result = 31 * result + getRoleId();
        result = 31 * result + (getMusicTypeId() != null ? getMusicTypeId().hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return String.format("User{id=%s, name=%s, password=%s, addressId=%s, roleId=%s, musicTypeId=%s}",
                this.id, this.name, this.password, this.addressId, this.roleId, this.musicTypeId);
    }
}


text:
package com.salesmanager.core.business.shipping.model;

public enum ShippingDescription {

	SHORT_DESCRIPTION, LONG_DESCRIPTION
}


text:
<?php

namespace DataSift\Storyplayer\Injectables;

use DataSift\Storyplayer\OutputLib\DataFormatter;

/**
 * support for converting data for printing
 *
 * @category  Libraries
 * @package   Storyplayer/Injectables
 * @author    Stuart Herbert <stuart.herbert@datasift.com>
 * @copyright 2011-present Mediasift Ltd www.datasift.com
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @link      http://datasift.github.io/storyplayer
 */
trait DataFormatterSupport
{
    public $dataFormatter;

    /**
     *
     * @return void
     */
    public function initDataFormatterSupport()
    {
        $this->dataFormatter = new DataFormatter();
    }
}


text:
@interface CrestedDuck : NSObject <Duck>

@end