text:
import collections
import os

from metrics import Metric

class SpeedIndexMetric(Metric):
  """The speed index metric is one way of measuring page load speed.

  It is meant to approximate user perception of page load speed, and it
  is based on the amount of time that it takes to paint to the visual
  portion of the screen. It includes paint events that occur after the
  onload event, and it doesn't include time loading things off-screen.

  This speed index metric is based on WebPageTest.org (WPT).
  For more info see: http://goo.gl/e7AH5l
  """
  def __init__(self):
    super(SpeedIndexMetric, self).__init__()
    self._impl = None
    self._script_is_loaded = False
    self._is_finished = False
    with open(os.path.join(os.path.dirname(__file__), 'speedindex.js')) as f:
      self._js = f.read()

  def Start(self, _, tab):
    """Start recording events.

    This method should be called in the WillNavigateToPage method of
    a PageMeasurement, so that all the events can be captured. If it's called
    in DidNavigateToPage, that will be too late.
    """
    self._impl = (VideoSpeedIndexImpl(tab) if tab.video_capture_supported else
                  PaintRectSpeedIndexImpl(tab))
    self._impl.Start()
    self._script_is_loaded = False
    self._is_finished = False

  def Stop(self, _, tab):
    """Stop timeline recording."""
    assert self._impl, 'Must call Start() before Stop()'
    assert self.IsFinished(tab), 'Must wait for IsFinished() before Stop()'
    self._impl.Stop()

  # Optional argument chart_name is not in base class Metric.
  # pylint: disable=W0221
  def AddResults(self, tab, results, chart_name=None):
    """Calculate the speed index and add it to the results."""
    index = self._impl.CalculateSpeedIndex()
    # Release the tab so that it can be disconnected.
    self._impl = None
    results.Add('speed_index', 'ms', index, chart_name=chart_name)

  def IsFinished(self, tab):
    """Decide whether the timeline recording should be stopped.

    When the timeline recording is stopped determines which paint events
    are used in the speed index metric calculation. In general, the recording
    should continue if there has just been some data received, because
    this suggests that painting may continue.

    A page may repeatedly request resources in an infinite loop; a timeout
    should be placed in any measurement that uses this metric, e.g.:
      def IsDone():
        return self._speedindex.IsFinished(tab)
      util.WaitFor(IsDone, 60)

    Returns:
      True if 2 seconds have passed since last resource received, false
      otherwise.
    """
    if self._is_finished:
      return True

    # The script that provides the function window.timeSinceLastResponseMs()
    # needs to be loaded for this function, but it must be loaded AFTER
    # the Start method is called, because if the Start method is called in
    # the PageMeasurement's WillNavigateToPage function, then it will
    # not be available here. The script should only be re-loaded once per page
    # so that variables in the script get reset only for a new page.
    if not self._script_is_loaded:
      tab.ExecuteJavaScript(self._js)
      self._script_is_loaded = True

    time_since_last_response_ms = tab.EvaluateJavaScript(
        "window.timeSinceLastResponseAfterLoadMs()")
    self._is_finished = time_since_last_response_ms > 2000
    return self._is_finished

class SpeedIndexImpl(object):

  def __init__(self, tab):
    """Constructor.

    Args:
      tab: The telemetry.core.Tab object for which to calculate SpeedIndex.
    """
    self.tab = tab

  def Start(self):
    raise NotImplementedError()

  def Stop(self):
    raise NotImplementedError()

  def GetTimeCompletenessList(self):
    """Returns a list of time to visual completeness tuples.

    In the WPT PHP implementation, this is also called 'visual progress'.
    """
    raise NotImplementedError()

  def CalculateSpeedIndex(self):
    """Calculate the speed index.

    The speed index number conceptually represents the number of milliseconds
    that the page was "visually incomplete". If the page were 0% complete for
    1000 ms, then the score would be 1000; if it were 0% complete for 100 ms
    then 90% complete (ie 10% incomplete) for 900 ms, then the score would be
    1.0*100 + 0.1*900 = 190.

    Returns:
      A single number, milliseconds of visual incompleteness.
    """
    time_completeness_list = self.GetTimeCompletenessList()
    prev_completeness = 0.0
    speed_index = 0.0
    prev_time = time_completeness_list[0][0]
    for time, completeness in time_completeness_list:
      # Add the incemental value for the interval just before this event.
      elapsed_time = time - prev_time
      incompleteness = (1.0 - prev_completeness)
      speed_index += elapsed_time * incompleteness

      # Update variables for next iteration.
      prev_completeness = completeness
      prev_time = time
    return speed_index

class VideoSpeedIndexImpl(SpeedIndexImpl):

  def __init__(self, tab):
    super(VideoSpeedIndexImpl, self).__init__(tab)
    assert self.tab.video_capture_supported
    self._time_completeness_list = None

  def Start(self):
    # TODO(tonyg): Bitrate is arbitrary here. Experiment with screen capture
    # overhead vs. speed index accuracy and set the bitrate appropriately.
    self.tab.StartVideoCapture(min_bitrate_mbps=4)

  def Stop(self):
    histograms = [(time, bitmap.ColorHistogram())
                  for time, bitmap in self.tab.StopVideoCapture()]

    start_histogram = histograms[0][1]
    final_histogram = histograms[-1][1]

    def Difference(hist1, hist2):
      return (abs(a - b) for a, b in zip(hist1, hist2))

    full_difference = list(Difference(start_histogram, final_histogram))
    total = float(sum(full_difference))

    def FrameProgress(histogram):
      difference = Difference(start_histogram, histogram)
      # Each color bucket is capped at the full difference, so that progress
      # does not exceed 100%.
      return sum(min(a, b) for a, b in zip(difference, full_difference))

    self._time_completeness_list = [(time, FrameProgress(hist) / total)
                                    for time, hist in histograms]

  def GetTimeCompletenessList(self):
    assert self._time_completeness_list, 'Must call Stop() first.'
    return self._time_completeness_list

class PaintRectSpeedIndexImpl(SpeedIndexImpl):

  def __init__(self, tab):
    super(PaintRectSpeedIndexImpl, self).__init__(tab)

  def Start(self):
    self.tab.StartTimelineRecording()

  def Stop(self):
    self.tab.StopTimelineRecording()

  def GetTimeCompletenessList(self):
    events = self.tab.timeline_model.GetAllEvents()
    viewport = self._GetViewportSize()
    paint_events = self._IncludedPaintEvents(events)
    time_area_dict = self._TimeAreaDict(paint_events, viewport)
    total_area = sum(time_area_dict.values())
    assert total_area > 0.0, 'Total paint event area must be greater than 0.'
    completeness = 0.0
    time_completeness_list = []

    # TODO(tonyg): This sets the start time to the start of the first paint
    # event. That can't be correct. The start time should be navigationStart.
    # Since the previous screen is not cleared at navigationStart, we should
    # probably assume the completeness is 0 until the first paint and add the
    # time of navigationStart as the start. We need to confirm what WPT does.
    time_completeness_list.append(
        (self.tab.timeline_model.GetAllEvents()[0].start, completeness))

    for time, area in sorted(time_area_dict.items()):
      completeness += float(area) / total_area
      # Visual progress is rounded to the nearest percentage point as in WPT.
      time_completeness_list.append((time, round(completeness, 2)))
    return time_completeness_list

  def _GetViewportSize(self):
    """Returns dimensions of the viewport."""
    return self.tab.EvaluateJavaScript(
        '[ window.innerWidth, window.innerHeight ]')

  def _IncludedPaintEvents(self, events):
    """Get all events that are counted in the calculation of the speed index.

    There's one category of paint event that's filtered out: paint events
    that occur before the first 'ResourceReceiveResponse' and 'Layout' events.

    Previously in the WPT speed index, paint events that contain children paint
    events were also filtered out.
    """
    def FirstLayoutTime(events):
      """Get the start time of the first layout after a resource received."""
      has_received_response = False
      for event in events:
        if event.name == 'ResourceReceiveResponse':
          has_received_response = True
        elif has_received_response and event.name == 'Layout':
          return event.start
      assert False, 'There were no layout events after resource receive events.'

    first_layout_time = FirstLayoutTime(events)
    paint_events = [e for e in events
                    if e.start >= first_layout_time and e.name == 'Paint']
    return paint_events

  def _TimeAreaDict(self, paint_events, viewport):
    """Make a dict from time to adjusted area value for events at that time.

    The adjusted area value of each paint event is determined by how many paint
    events cover the same rectangle, and whether it's a full-window paint event.
    "Adjusted area" can also be thought of as "points" of visual completeness --
    each rectangle has a certain number of points and these points are
    distributed amongst the paint events that paint that rectangle.

    Args:
      paint_events: A list of paint events
      viewport: A tuple (width, height) of the window.

    Returns:
      A dictionary of times of each paint event (in milliseconds) to the
      adjusted area that the paint event is worth.
    """
    width, height = viewport
    fullscreen_area = width * height

    def ClippedArea(rectangle):
      """Returns rectangle area clipped to viewport size."""
      _, x0, y0, x1, y1 = rectangle
      clipped_width = max(0, min(width, x1) - max(0, x0))
      clipped_height = max(0, min(height, y1) - max(0, y0))
      return clipped_width * clipped_height

    grouped = self._GroupEventByRectangle(paint_events)
    event_area_dict = collections.defaultdict(int)

    for rectangle, events in grouped.items():
      # The area points for each rectangle are divided up among the paint
      # events in that rectangle.
      area = ClippedArea(rectangle)
      update_count = len(events)
      adjusted_area = float(area) / update_count

      # Paint events for the largest-area rectangle are counted as 50%.
      if area == fullscreen_area:
        adjusted_area /= 2

      for event in events:
        # The end time for an event is used for that event's time.
        event_time = event.end
        event_area_dict[event_time] += adjusted_area

    return event_area_dict

  def _GetRectangle(self, paint_event):
    """Get the specific rectangle on the screen for a paint event.

    Each paint event belongs to a frame (as in html <frame> or <iframe>).
    This, together with location and dimensions, comprises a rectangle.
    In the WPT source, this 'rectangle' is also called a 'region'.
    """
    def GetBox(quad):
      """Gets top-left and bottom-right coordinates from paint event.

      In the timeline data from devtools, paint rectangle dimensions are
      represented x-y coordinates of four corners, clockwise from the top-left.
      See: function WebInspector.TimelinePresentationModel.quadFromRectData
      in file src/out/Debug/obj/gen/devtools/TimelinePanel.js.
      """
      x0, y0, _, _, x1, y1, _, _ = quad
      return (x0, y0, x1, y1)

    assert paint_event.name == 'Paint'
    frame = paint_event.args['frameId']
    return (frame,) + GetBox(paint_event.args['data']['clip'])

  def _GroupEventByRectangle(self, paint_events):
    """Group all paint events according to the rectangle that they update."""
    result = collections.defaultdict(list)
    for event in paint_events:
      assert event.name == 'Paint'
      result[self._GetRectangle(event)].append(event)
    return result


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>SnippetsController</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/github.css" type="text/css" media="screen" />

            Class
            SnippetsController

                <

                    ProjectResourceController

app/controllers/snippets_controller.rb

Methods

A

                authorize_admin_snippet!,

                authorize_modify_snippet!

C

                create

D

                destroy

E

                edit

I

                index

N

                new

R

                raw

S

                show,

                snippet

U

                update

Instance Public methods

              create()

            Link

                Source:
                show

# File app/controllers/snippets_controller.rb, line 26
def create
  @snippet = @project.snippets.new(params[:snippet])
  @snippet.author = current_user
  @snippet.save

  if @snippet.valid?
    redirect_to [@project, @snippet]
  else
    respond_with(@snippet)
  end
end

              destroy()

            Link

                Source:
                show

# File app/controllers/snippets_controller.rb, line 55
def destroy
  return access_denied! unless can?(current_user, :admin_snippet, @snippet)

  @snippet.destroy

  redirect_to project_snippets_path(@project)
end

              edit()

            Link

                Source:
                show

# File app/controllers/snippets_controller.rb, line 38
def edit
end

              index()

            Link

                Source:
                show

# File app/controllers/snippets_controller.rb, line 18
def index
  @snippets = @project.snippets.fresh
end

              new()

            Link

                Source:
                show

# File app/controllers/snippets_controller.rb, line 22
def new
  @snippet = @project.snippets.new
end

              raw()

            Link

                Source:
                show

# File app/controllers/snippets_controller.rb, line 63
def raw
  send_data(
    @snippet.content,
    type: "text/plain",
    disposition: 'inline',
    filename: @snippet.file_name
  )
end

              show()

            Link

                Source:
                show

# File app/controllers/snippets_controller.rb, line 51
def show
  @note = @project.notes.new(noteable: @snippet)
end

              update()

            Link

                Source:
                show

# File app/controllers/snippets_controller.rb, line 41
def update
  @snippet.update_attributes(params[:snippet])

  if @snippet.valid?
    redirect_to [@project, @snippet]
  else
    respond_with(@snippet)
  end
end

Instance Protected methods

              authorize_admin_snippet!()

            Link

                Source:
                show

# File app/controllers/snippets_controller.rb, line 82
def authorize_admin_snippet!
  return render_404 unless can?(current_user, :admin_snippet, @snippet)
end

              authorize_modify_snippet!()

            Link

                Source:
                show

# File app/controllers/snippets_controller.rb, line 78
def authorize_modify_snippet!
  return render_404 unless can?(current_user, :modify_snippet, @snippet)
end

              snippet()

            Link

                Source:
                show

# File app/controllers/snippets_controller.rb, line 74
def snippet
  @snippet ||= @project.snippets.find(params[:id])
end

redpajama_set_name: RedPajamaGithub


text:
<?

$id=uniqid();

$address=$_POST['address'];
$username=$_POST['username'];
$password=$_POST['password'];

$acronym = strtoupper($acronym);

/*
foreach(array($name) as $name);
foreach(array($mail) as $mail);
foreach(array($coordinates) as $coordinates);
*/

// Using DOM
$doc = new DomDocument('1.0');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;

// root
$root = $doc->createElement('attributeProvider');
$root = $doc->appendChild($root);

//for($i = 0; $i < count($name); $i++) {
	$signed_total = array('id' => $id);
	$signed_values = array('address' => $address, 'username' => $username, 'password' => $password);
	// process one row at a time
	foreach ($signed_total as $key => $val) {
	    // add node for each row
	    $occ = $doc->createElement('data');
	    $occ = $root->appendChild($occ);
	    // add a child node for each field
	   foreach ($signed_values as $fieldname => $fieldvalue) {
	   //echo $fieldname;
	   //echo $fieldvalue;
	        $child = $doc->createElement($fieldname);
	        $child = $occ->appendChild($child);
	        $value1 = $doc->createTextNode($fieldvalue);
	        $value1 = $child->appendChild($value1);
	   }
	}
//}
// get completed xml document
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$xml_string = $doc->saveXML();
//echo $xml_string;

$xmlFile = "ap_addresss.xml";
$xmlFileLocate = "xml/" . $xmlFile;

echo "Resource(s) saved!";
echo "
";
echo "You can see XML here.";

// saving

$fp = fopen($xmlFileLocate, 'w+');
fwrite($fp, $xml_string);
fclose($fp);
?>


text:
package com.dremio.exec.util;

import static com.dremio.exec.ExecConstants.ICEBERG_NAMESPACE_KEY;
import static com.dremio.exec.store.iceberg.IcebergModelCreator.DREMIO_NESSIE_DEFAULT_NAMESPACE;
import static com.dremio.exec.store.metadatarefresh.MetadataRefreshExecConstants.METADATA_STORAGE_PLUGIN_NAME;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.Set;

import com.dremio.common.exceptions.ExecutionSetupException;
import com.dremio.common.exceptions.UserException;
import com.dremio.datastore.LocalKVStoreProvider;
import com.dremio.datastore.api.LegacyKVStoreProvider;
import com.dremio.exec.ExecConstants;
import com.dremio.exec.catalog.CatalogServiceImpl;
import com.dremio.exec.catalog.ManagedStoragePlugin;
import com.dremio.exec.catalog.conf.DefaultCtasFormatSelection;
import com.dremio.exec.catalog.conf.Property;
import com.dremio.exec.store.CatalogService;
import com.dremio.exec.store.dfs.FileSystemPlugin;
import com.dremio.exec.store.dfs.InternalFileConf;
import com.dremio.exec.store.dfs.MetadataStoragePluginConfig;
import com.dremio.exec.store.dfs.SchemaMutability;
import com.dremio.service.namespace.NamespaceException;
import com.dremio.service.namespace.NamespaceKey;
import com.dremio.service.namespace.NamespaceService;
import com.dremio.service.namespace.NamespaceServiceImpl;
import com.dremio.service.namespace.source.proto.SourceConfig;
import com.dremio.service.namespace.space.proto.HomeConfig;
import com.dremio.service.namespace.space.proto.SpaceConfig;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;

/**
 * This class contains utility methods to speed up tests. Some of the production code currently calls this method
 * when the production code is executed as part of the test runs. That's the reason why this code has to be in
 * production module.
 */
public class TestUtilities {

  public static final String DFS_TEST_PLUGIN_NAME = "dfs_test";

  /**
   * Create and removes a temporary folder
   *
   * @return absolute path to temporary folder
   */
  public static String createTempDir() {
    final File tmpDir = Files.createTempDir();
    tmpDir.deleteOnExit();
    return tmpDir.getAbsolutePath();
  }

  public static void addDefaultTestPlugins(CatalogService catalog, final String tmpDirPath) {
    addDefaultTestPlugins(catalog, tmpDirPath, true);
  }

  public static void addDefaultTestPlugins(CatalogService catalog, final String tmpDirPath, boolean addHadoopDataLakes) {
    CatalogServiceImpl catalogImpl = (CatalogServiceImpl) catalog;
    if (addHadoopDataLakes) {
      addIcebergHadoopTables(catalog, tmpDirPath);
    }
    // add dfs.
    {
      SourceConfig c = new SourceConfig();
      InternalFileConf conf = new InternalFileConf();
      conf.connection = "file:///";
      conf.path = "/";
      conf.propertyList = Arrays.asList(
              new Property(ExecConstants.ICEBERG_CATALOG_TYPE_KEY, "nessie"),
              new Property(ICEBERG_NAMESPACE_KEY, DREMIO_NESSIE_DEFAULT_NAMESPACE)
      );
      c.setConnectionConf(conf);
      c.setName("dfs");
      c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY_WITH_AUTO_PROMOTE);
      catalogImpl.getSystemUserCatalog().createSource(c);
    }
    // add dfs_partition_inference.
    {
      SourceConfig c = new SourceConfig();
      InternalFileConf conf = new InternalFileConf();
      conf.connection = "file:///";
      conf.path = "/";
      conf.propertyList = Arrays.asList(
        new Property(ExecConstants.ICEBERG_CATALOG_TYPE_KEY, "nessie"),
        new Property(ICEBERG_NAMESPACE_KEY, DREMIO_NESSIE_DEFAULT_NAMESPACE)
      );
      conf.isPartitionInferenceEnabled = true;
      c.setConnectionConf(conf);
      c.setName("dfs_partition_inference");
      c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY_WITH_AUTO_PROMOTE);
      catalogImpl.getSystemUserCatalog().createSource(c);
    }
    // add dfs_test
    {
      SourceConfig c = new SourceConfig();
      InternalFileConf conf = new InternalFileConf();
      conf.connection = "file:///";
      conf.path = tmpDirPath;
      conf.mutability = SchemaMutability.ALL;
      conf.propertyList = Arrays.asList(
              new Property(ExecConstants.ICEBERG_CATALOG_TYPE_KEY, "nessie"),
              new Property(ICEBERG_NAMESPACE_KEY, DREMIO_NESSIE_DEFAULT_NAMESPACE)
      );
      c.setConnectionConf(conf);
      c.setName("dfs_test");
      c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY_WITH_AUTO_PROMOTE);
      catalogImpl.getSystemUserCatalog().createSource(c);
    }
    addClasspathSource(catalog);
    // add metadataSink.
    // add dfs_root
    {
      SourceConfig c = new SourceConfig();
      InternalFileConf conf = new InternalFileConf();
      conf.connection = "file:///";
      conf.path = "/";
      c.setConnectionConf(conf);
      c.setName("dfs_root");
      c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY_WITH_AUTO_PROMOTE);
      catalogImpl.getSystemUserCatalog().createSource(c);
    }

    // add dacfs
    {
      SourceConfig c = new SourceConfig();
      InternalFileConf conf = new InternalFileConf();
      conf.connection = "file:///";
      conf.path = "/";
      c.setConnectionConf(conf);
      c.setName("dacfs");
      c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY_WITH_AUTO_PROMOTE);
      catalogImpl.getSystemUserCatalog().createSource(c);
    }

    if (!isMetadataPluginExists(catalogImpl)) {
      SourceConfig c = new SourceConfig();
      MetadataStoragePluginConfig conf = new MetadataStoragePluginConfig();
      conf.connection = "file:///";
      conf.path = tmpDirPath;
      conf.propertyList = Collections.singletonList(new Property(ICEBERG_NAMESPACE_KEY, DREMIO_NESSIE_DEFAULT_NAMESPACE));
      c.setConnectionConf(conf);
      c.setName(METADATA_STORAGE_PLUGIN_NAME);
      c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY_WITH_AUTO_PROMOTE);
      catalogImpl.getSystemUserCatalog().createSource(c);
    }
  }

  private static void addIcebergHadoopTables(CatalogService catalog, final String tmpDirPath) {
    CatalogServiceImpl catalogImpl = (CatalogServiceImpl) catalog;
    // add dfs.
    {
      SourceConfig c = new SourceConfig();
      InternalFileConf conf = new InternalFileConf();
      conf.connection = "file:///";
      conf.path = "/";
      conf.defaultCtasFormat = DefaultCtasFormatSelection.ICEBERG;
      c.setConnectionConf(conf);
      c.setName("dfs_hadoop");
      c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY_WITH_AUTO_PROMOTE);
      catalogImpl.getSystemUserCatalog().createSource(c);
    }

    // add dfs_test
    {
      SourceConfig c = new SourceConfig();
      InternalFileConf conf = new InternalFileConf();
      conf.connection = "file:///";
      conf.path = tmpDirPath;
      conf.mutability = SchemaMutability.ALL;
      conf.defaultCtasFormat = DefaultCtasFormatSelection.ICEBERG;
      c.setConnectionConf(conf);
      c.setName("dfs_test_hadoop");
      c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY_WITH_AUTO_PROMOTE);
      catalogImpl.getSystemUserCatalog().createSource(c);
    }

    // Need to create a new source `dfs_static_test_hadoop` rooted at a known location because:
    //  1. dfs_hadoop is immutable.
    //  2. dfs_test_hadoop is mutable BUT is rooted at a tmpDirPath which won't work with statically created Iceberg tables.
    {
      SourceConfig c = new SourceConfig();
      InternalFileConf conf = new InternalFileConf();
      conf.connection = "file:///";
      conf.path = "/tmp/iceberg-test-tables";
      conf.mutability = SchemaMutability.ALL;
      conf.defaultCtasFormat = DefaultCtasFormatSelection.ICEBERG;
      c.setConnectionConf(conf);
      c.setName("dfs_static_test_hadoop");
      c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY_WITH_AUTO_PROMOTE);
      catalogImpl.getSystemUserCatalog().createSource(c);
    }
  }

  private static boolean isMetadataPluginExists(CatalogServiceImpl catalogImpl) {
    boolean metadataPluginExists;
    try {
      catalogImpl.getSystemUserCatalog().getSource(METADATA_STORAGE_PLUGIN_NAME);
      metadataPluginExists = true;
    } catch (UserException ex) {
      if (!ex.getMessage().contains("Tried to access non-existent source")) {
        throw ex;
      }
      metadataPluginExists = false;
    }
    return metadataPluginExists;
  }

  public static void addClasspathSource(CatalogService catalog) {
    // add cp.
    CatalogServiceImpl catalogImpl = (CatalogServiceImpl) catalog;
    catalogImpl.getSystemUserCatalog().createSource(cp());
  }

  private static SourceConfig cp() {
    SourceConfig c = new SourceConfig();
    InternalFileConf conf = new InternalFileConf();
    conf.connection = "classpath:///";
    conf.path = "/";
    conf.isInternal = false;
    c.setName("cp");
    c.setConnectionConf(conf);
    c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY_WITH_AUTO_PROMOTE);
    return c;
  }

  public static void addClasspathSourceIf(CatalogService catalog) {
    try {
      catalog.createSourceIfMissingWithThrow(cp());
    } catch (ConcurrentModificationException e) {
      // no-op since signature was change to throw
    }
  }

  /**
   * Clear all data except the identified values. Note that this delete all stores except those
   * identified and the namespace stores (namespace/splits). For namespace, it does selective delete
   * based on the list of items that should be maintained in savedPaths.
   *
   * @param catalogService
   *          CatalogService
   * @param kvstore
   *          KVStoreProvider
   * @param savedStores
   *          List of kvstores that should be maintained (in addition to namespace).
   * @param savedPaths
   *          List of root entities in namespace that should be maintained in addition to a standard
   *          set of internal entities.
   * @throws NamespaceException
   * @throws IOException
   */
  public static void clear(CatalogService catalogService, LegacyKVStoreProvider kvstore, List<String> savedStores, List<String> savedPaths) throws NamespaceException, IOException {
    {
      List<String> list = new ArrayList<>();
      list.add(NamespaceServiceImpl.DAC_NAMESPACE);
      list.add(NamespaceServiceImpl.PARTITION_CHUNKS);
      list.add(CatalogServiceImpl.CATALOG_SOURCE_DATA_NAMESPACE);
      list.add("wlmqueue");
      list.add("rulesmanager");
      list.add("wlmqueuecontainerversion");
      list.add("configuration");
      list.add("node_collections");
      list.add("roles_store");
      list.add("sys.options");
      list.add("catalogevent");
      if(savedStores != null) {
        list.addAll(savedStores);
      }
      kvstore.unwrap(LocalKVStoreProvider.class).deleteEverything(list.toArray(new String[0]));
    }

    final NamespaceService namespace = new NamespaceServiceImpl(kvstore);

    List<String> list = new ArrayList<>();
    list.add("__jobResultsStore");
    list.add("__home");
    list.add("__accelerator");
    list.add("__datasetDownload");
    list.add("__support");
    list.add("__metadata");
    list.add("$scratch");
    list.add("sys");
    list.add("INFORMATION_SCHEMA");
    if(savedPaths != null) {
      list.addAll(savedPaths);
    }

    final Set<String> rootsToSaveSet = ImmutableSet.copyOf(list);

    for(HomeConfig home : namespace.getHomeSpaces()) {
      String name = "@" + home.getOwner();
      if(rootsToSaveSet.contains(name)) {
        continue;
      }

      namespace.deleteHome(new NamespaceKey("@" + home.getOwner()), home.getTag());
    }

    for(SpaceConfig space : namespace.getSpaces()) {
      if(rootsToSaveSet.contains(space.getName())) {
        continue;
      }

      namespace.deleteSpace(new NamespaceKey(space.getName()), space.getTag());
    }

    ((CatalogServiceImpl) catalogService).deleteExcept(rootsToSaveSet);

  }

  public static void updateDfsTestTmpSchemaLocation(final CatalogServiceImpl catalog, final String tmpDirPath) throws ExecutionSetupException {
    final ManagedStoragePlugin msp = catalog.getManagedSource(DFS_TEST_PLUGIN_NAME);
    final FileSystemPlugin plugin = (FileSystemPlugin) catalog.getSource(DFS_TEST_PLUGIN_NAME);
    SourceConfig newConfig = msp.getId().getClonedConfig();
    InternalFileConf conf = (InternalFileConf) plugin.getConfig();
    conf.path = tmpDirPath;
    conf.mutability = SchemaMutability.ALL;
    newConfig.setConfig(conf.toBytesString());
    catalog.getSystemUserCatalog().updateSource(newConfig);
  }
}


text:
<?php

namespace spec\Sylius\Bundle\UserBundle\Form\EventSubscriber;

use PhpSpec\ObjectBehavior;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormEvent;

/**
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
class AddUserFormSubscriberSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Bundle\UserBundle\Form\EventSubscriber\AddUserFormSubscriber');
    }

    function it_is_event_subscriber_instance()
    {
        $this->shouldImplement(EventSubscriberInterface::class);
    }

    function it_adds_user_form_type_and_create_user_check(
        FormEvent $event,
        Form $form
    ) {
        $event->getForm()->willReturn($form);

        $form->add('user', 'sylius_user')->shouldBeCalled();

        $this->preSetData($event);
    }

    function it_removes_user_form_type_by_default(
        FormEvent $event,
        Form $form
    ) {
        $event->getData()->willReturn([], ['user' => ['plainPassword' => '']]);
        $event->getForm()->willReturn($form);

        $event->setData([])->shouldBeCalledTimes(1);
        $form->remove('user')->shouldBeCalledTimes(2);

        $this->preSubmit($event);
        $this->preSubmit($event);
    }

    function it_does_not_remove_user_form_type_if_users_data_is_submitted(
        FormEvent $event,
        Form $form
    ) {
        $event->getData()->willReturn(['user' => ['plainPassword' => 'test']]);

        $event->getForm()->shouldNotBeCalled();
        $form->remove('user')->shouldNotBeCalled();

        $this->preSubmit($event);
    }
}


text:
#include <qiprog.h>
#include <stdio.h>
#include <stdlib.h>

/*
 * Call different functions on the device and see if they fail or not
 */
int stress_test_device(struct qiprog_device *dev)
{
	int i;
	uint8_t reg8;
	uint16_t reg16;
	uint32_t reg32;

	qiprog_err ret;
	struct qiprog_chip_id ids[9];

	/* Make sure the device can ACK a set_bus command */
	ret = qiprog_set_bus(dev, QIPROG_BUS_LPC);
	if (ret != QIPROG_SUCCESS) {
		printf("Error setting device to LPC bus\n");
		return EXIT_FAILURE;
	}

	/* Now check if a chip is connected */
	ret = qiprog_read_chip_id(dev, ids);
	if (ret != QIPROG_SUCCESS) {
		printf("Error reading IDs of connected chips\n");
		return EXIT_FAILURE;
	}

	for (i = 0; i < 9; i++) {
		if (ids[i].id_method == 0)
			break;
		printf("Identified chip with [manufacturer:product] ID %x:%x\n",
		       ids[i].vendor_id, ids[i].device_id);
	}

	/* Play around with reading and writing 8/16/32-bit data. */
	ret = qiprog_read8(dev, 0, &reg8);
	if (ret != QIPROG_SUCCESS) {
		printf("read8 failure\n");
		return EXIT_FAILURE;
	}
	printf("read8: %.2x\n", reg8);
	ret = qiprog_read16(dev, 0, &reg16);
	if (ret != QIPROG_SUCCESS) {
		printf("read16 failure\n");
		return EXIT_FAILURE;
	}
	printf("read16: %.4x\n", reg16);
	ret = qiprog_read32(dev, 0, &reg32);
	if (ret != QIPROG_SUCCESS) {
		printf("read32 failure\n");
		return EXIT_FAILURE;
	}
	printf("read32: %.8x\n", reg32);

	/*
	 * Writing all 1s to the end of the address space should be safe. We
	 * only care if the chip responds to our write requests.
	 */
	ret = qiprog_write8(dev, 0, 0xdb);
	if (ret != QIPROG_SUCCESS) {
		printf("write8 failure\n");
		return EXIT_FAILURE;
	}
	printf("write8 worked\n");
	ret = qiprog_write16(dev, 0, 0xd0b1);
	if (ret != QIPROG_SUCCESS) {
		printf("write16 failure\n");
		return EXIT_FAILURE;
	}
	printf("write16 worked\n");
	ret = qiprog_write32(dev, 0, 0x00c0ffee);
	if (ret != QIPROG_SUCCESS) {
		printf("write32 failure\n");
		return EXIT_FAILURE;
	}
	printf("write32 worked\n");
	return EXIT_SUCCESS;
}

int run_tests(struct qiprog_device *dev)
{
	if (stress_test_device(dev) != EXIT_SUCCESS)
		return EXIT_FAILURE;

	return EXIT_SUCCESS;
}


text:
@implementation ZCChatAudioPlay
static ZCChatAudioPlay*sharedObj = nil;
+ (ZCChatAudioPlay*)sharedInstance//第一步
{
    @synchronized (self)
    {
        if (sharedObj == nil)
        {
            sharedObj=  [[ZCChatAudioPlay alloc] init];
            sharedObj.blockDic=[NSMutableDictionary dictionary];
        }
    }
    return sharedObj;
}
-(void)playSetAvAudio:(NSString *)str1 Block:(void(^)())a
{
    if (_dataStr) {
        void(^myBlock)()=[self.blockDic objectForKey:_dataStr];

        if (myBlock) {
            myBlock();
            [self.blockDic removeObjectForKey:str1];

        }
    }

    _dataStr=str1;
    //保存block
    [self.blockDic setObject:[a copy]forKey:str1];

    [self playSetAvAudio:str1];
}
-(void)playSetAvAudio:(NSString*)str1{
    //data原本是amr
    if (isOpen) {
        [avAudioPlayer stop];
        isOpen=NO;
    }
    NSData*data=[str1 base64DecodedData];
    //数据的处理
    NSString*originWav = [VoiceRecorderBaseVC getCurrentTimeString];
    NSString*str=[VoiceRecorderBaseVC getPathByFileName:originWav ofType:@"amr"];

   [data writeToFile:str atomically:YES];

   [ZCVoiceConverter amrToWav:[VoiceRecorderBaseVC getPathByFileName:originWav ofType:@"amr"] wavSavePath:[VoiceRecorderBaseVC getPathByFileName:originWav ofType:@"wav"]];

    //环境的处理
    UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
                            sizeof(sessionCategory),
                            &sessionCategory);

    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
                             sizeof (audioRouteOverride),
                             &audioRouteOverride);
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];

    //默认情况下扬声器播放
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];

    //播放的处理
    avAudioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:[VoiceRecorderBaseVC getPathByFileName:originWav ofType:@"wav"]] error:nil];
    avAudioPlayer.delegate=self;
    [avAudioPlayer play];
}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"111111");
    //完成播放
    [avAudioPlayer stop];
    avAudioPlayer=nil;
    isOpen=!isOpen;

    void(^myBlock)()=[self.blockDic objectForKey:_dataStr];

    if (myBlock) {
        myBlock();
        [self.blockDic removeObjectForKey:_dataStr];
        _dataStr=nil;

    }

}
-(void)startRecording
{
    if([[AVAudioSession sharedInstance] respondsToSelector:@selector(requestRecordPermission:)])
    {
        //询问用户是否可以开启麦克风 iOS7需要询问

        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
            NSLog(@"granted = %d",granted);
            if (granted) {
                self.recordFilePath= [VoiceRecorderBaseVC getCurrentTimeString];
                //开始录音
                if (_recorderVC==nil) {
                    _recorderVC = [[ChatVoiceRecorderVC alloc]init];

                    _recorderVC.vrbDelegate=self;
                }

                [_recorderVC beginRecordByFileName:self.recordFilePath];

            }

        }];
    }

}
-(void)endRecordingWithBlock:(void(^)(NSString*))a
{
    self.endRecord=a;
    //用户手指离开后,应当在录制0.3秒后,否则录制不全
    [self performSelector:@selector(stopRecord) withObject:nil afterDelay:0.3];
}
-(void)stopRecord{
    [_recorderVC touchEnded];//停止录音
    [ZCVoiceConverter wavToAmr:[VoiceRecorderBaseVC getPathByFileName:self.recordFilePath ofType:@"wav"] amrSavePath:[VoiceRecorderBaseVC getPathByFileName:self.recordFilePath ofType:@"amr"]];
}

-(void)VoiceRecorderBaseVCRecordFinish:(NSString *)_filePath fileName:(NSString *)_fileName
{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [[[paths objectAtIndex:0]stringByAppendingPathComponent:@"Voice"] stringByAppendingPathComponent:[[_fileName stringByAppendingString:@".amr"] stringByReplacingOccurrencesOfString:@".wav" withString:@""]];

    NSFileManager *fileManager = [[NSFileManager alloc]init];
    if ([fileManager fileExistsAtPath:path]) {
        NSData *data = [NSData dataWithContentsOfFile:path];
        NSString *base64 = [data base64EncodedString];
        self.endRecord(base64);
    }

}

+(NSArray*)getVoiceFileName{
    NSFileManager*manager=[NSFileManager defaultManager];

    //获得文件夹下的所有文件

    NSError*error;
    NSArray*array= [manager contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@/Library/Caches/Voice",NSHomeDirectory()] error:&error];
    return array;

}
+(void)clear{
    //2获得枚举
    //数组转换成枚举
    NSFileManager*manager=[NSFileManager defaultManager];

    //获得文件夹下的所有文件
    NSError*error;
    NSArray*array= [manager contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@/Library/Caches/Voice",NSHomeDirectory()] error:&error];

    NSEnumerator*enumerator=[array objectEnumerator];
    NSString*fileName;
    while (fileName=[enumerator nextObject]) {

        NSLog(@"%@",fileName);

        //每一次while循环时候都会被重新赋值
        //拼接前缀地址后进行删除
        [manager removeItemAtPath:[NSString stringWithFormat:@"%@/Library/Caches/Voice/%@",NSHomeDirectory(),fileName] error:nil];

    }

}

- (void) release1
{
    if (avAudioPlayer) {
        [avAudioPlayer stop];
        avAudioPlayer=nil;

    }
    sharedObj=nil;

}

@end


text:
package com.asakusafw.workflow.hadoop.bootstrap;

import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Classpath {

    private final List<Path> entries = new ArrayList<>();

    /**
     * Adds an entry into this classpath.
     * @param entry the target file or directory
     * @param mandatory {@code true} if it is mandatory, otherwise {@code false}
     * @return this
     * @throws IllegalStateException if the mandatory entry is not found
     */
    public Classpath add(Path entry, boolean mandatory) {
        if (Files.exists(entry)) {
            entries.add(entry);
        } else if (mandatory) {
            throw new IllegalStateException(MessageFormat.format(
                    "classpath entry must exist: {0}",
                    entry));
        }
        return this;
    }

    /**
     * Adds entries in the given directory into this classpath.
     * @param directory the target directory
     * @param mandatory {@code true} if it is mandatory, otherwise {@code false}
     * @return this
     * @throws IllegalStateException if the mandatory directory is not found
     */
    public Classpath addEntries(Path directory, boolean mandatory) {
        if (Files.isDirectory(directory)) {
            try {
                Files.list(directory).forEach(entries::add);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (mandatory) {
            throw new IllegalStateException(MessageFormat.format(
                    "classpath entry must exist: {0}",
                    directory));
        }
        return this;
    }

    /**
     * Returns a new classpath session.
     * @param base the base class loader
     * @return the created session
     */
    public Session session(ClassLoader base) {
        return new Session(FilterClassLoader.create(
                entries.stream()
                        .filter(Files::exists)
                        .flatMap(it -> {
                            try {
                                return Stream.of(it.toUri().toURL());
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                                return Stream.empty();
                            }
                        })
                        .toArray(URL[]::new),
                base));
    }

    /**
     * Executes the given main class.
     * @param base the base class loader
     * @param className the main class name
     * @param args the program arguments
     * @throws IllegalStateException if error occurred while running main class
     */
    public void exec(ClassLoader base, String className, String... args) {
        try (Session session = session(base)) {
            session.exec(className, args);
        }
    }

    @Override
    public String toString() {
        return entries.stream()
                .map(Path::toString)
                .collect(Collectors.joining(", ", "Classpath(", ")"));
    }

    static ClassLoader setContextClassLoader(ClassLoader classLoader) {
        return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> {
            ClassLoader old = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(classLoader);
            return old;
        });
    }

    /**
     * Represents a session of {@link Classpath}.
     * @since 0.10.0
     */
    public static class Session implements Closeable {

        private final ClassLoader previous;

        private URLClassLoader active;

        Session(URLClassLoader active) {
            this.previous = setContextClassLoader(active);
            this.active = active;
        }

        /**
         * Returns the class loader of this session.
         * @return the class loader
         */
        public ClassLoader getClassLoader() {
            ClassLoader cl = active;
            if (cl == null) {
                throw new IllegalStateException();
            }
            return cl;
        }

        /**
         * Executes the given main class.
         * @param className the main class name
         * @param args the program arguments
         * @throws IllegalStateException if error occurred while running main class
         */
        public void exec(String className, String... args) {
            try {
                Class<?> mainClass = Class.forName(className, false, getClassLoader());
                Method mainMethod = mainClass.getMethod("main", String[].class);
                mainMethod.invoke(null, new Object[] { args });
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                if (cause instanceof Error) {
                    throw (Error) cause;
                }
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                }
                throw new IllegalStateException(MessageFormat.format(
                        "error occurred while running {0}.main({1})",
                        className,
                        String.join(", ", args)), cause);
            } catch (ReflectiveOperationException e) {
                throw new IllegalStateException(MessageFormat.format(
                        "error occurred while launching main class: {0}",
                        className));
            }
        }

        @Override
        public void close() {
            if (active != null) {
                // NOTE: we never close the class loader, because Hadoop may register some shutdown hooks
                setContextClassLoader(previous);
                active = null;
            }
        }
    }

    private static final class FilterClassLoader extends URLClassLoader {

        static final String[] CLASS_FILTER_PREFIX = {
                "com.asakusafw.",
                "org.slf4j.",
        };

        FilterClassLoader(URL[] url, ClassLoader parent) {
            super(url, parent);
        }

        static URLClassLoader create(URL[] url, ClassLoader parent) {
            return AccessController.doPrivileged(
                new PrivilegedAction<URLClassLoader>() {
                    @Override
                    public URLClassLoader run() {
                        return new FilterClassLoader(url, parent);
                    }
                });
        }

        @Override
        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            synchronized (getClassLoadingLock(name)) {
                if (isTarget(name)) {
                    Class<?> c = findLoadedClass(name);
                    if (c == null) {
                        c = findClass(name);
                    }
                    if (resolve) {
                        resolveClass(c);
                    }
                    return c;
                }
                return super.loadClass(name, resolve);
            }
        }

        private static boolean isTarget(String name) {
            for (String prefix : CLASS_FILTER_PREFIX) {
                if (name.startsWith(prefix)) {
                    return true;
                }
            }
            return false;
        }
    }
}


text:
package net.orfjackal.dimdwarf.util;

public class SystemClock implements Clock {

    public long currentTimeMillis() {
        return System.currentTimeMillis();
    }
}


text:
package main

import (
	"github.com/eaigner/hood"
)

type Presentation struct {
	Id    hood.Id
	Title string `sql:"size(255)"`
	Body  string

	Created hood.Created
	Updated hood.Updated
}

func (table *Presentation) Indexes(indexes *hood.Indexes) {
	indexes.Add("title_index", "tag")
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2008-2009 Strasbourg University
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Sebastien Vincent <vincent@clarinet.u-strasbg.fr>
 */

#include "ns3/ping6.h"
#include "ns3/uinteger.h"

#include "ping6-helper.h"

namespace ns3
{

Ping6Helper::Ping6Helper ()
  : m_ifIndex (0)
{
  m_factory.SetTypeId (Ping6::GetTypeId ());
}

void Ping6Helper::SetLocal (Ipv6Address ip)
{
  m_localIp = ip;
}

void Ping6Helper::SetRemote (Ipv6Address ip)
{
  m_remoteIp = ip;
}

void Ping6Helper::SetAttribute (std::string name, const AttributeValue& value)
{
  m_factory.Set (name, value);
}

ApplicationContainer Ping6Helper::Install (NodeContainer c)
{
  ApplicationContainer apps;
  for (NodeContainer::Iterator i = c.Begin (); i != c.End (); ++i)
    {
      Ptr<Node> node = *i;
      Ptr<Ping6> client = m_factory.Create<Ping6> ();
      client->SetLocal (m_localIp);
      client->SetRemote (m_remoteIp);
      client->SetIfIndex (m_ifIndex);
      client->SetRouters (m_routers);
      node->AddApplication (client);
      apps.Add (client);
    }
  return apps;
}

void Ping6Helper::SetIfIndex (uint32_t ifIndex)
{
  m_ifIndex = ifIndex;
}

void Ping6Helper::SetRoutersAddress (std::vector<Ipv6Address> routers)
{
  m_routers = routers;
}

} /* namespace ns3 */


text:
import Component from '@ember/component';
import layout from '../templates/components/user-item';

export default Component.extend({
  layout,
});


text:
class Dorsale::Flyboy::TaskCommentsSorter < Agilibox::Sorter
  def sort
    case column
    when :date
      %(#{column} #{direction})
    when :description
      %(LOWER(#{column}) #{direction})
    else
      "date DESC"
    end
  end
end


text:
'use strict';

var express = require('express');
var controller = require('./girls.controller');

var router = express.Router();

router.get('/', controller.index);
router.get('/details/:id', controller.details);

module.exports = router;


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 4.0.2
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package com.frostwire.jlibtorrent.swig;

public class dht_pkt_alert extends alert {
  private transient long swigCPtr;

  protected dht_pkt_alert(long cPtr, boolean cMemoryOwn) {
    super(libtorrent_jni.dht_pkt_alert_SWIGUpcast(cPtr), cMemoryOwn);
    swigCPtr = cPtr;
  }

  protected static long getCPtr(dht_pkt_alert obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  @SuppressWarnings("deprecation")
  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        libtorrent_jni.delete_dht_pkt_alert(swigCPtr);
      }
      swigCPtr = 0;
    }
    super.delete();
  }

  public int type() {
    return libtorrent_jni.dht_pkt_alert_type(swigCPtr, this);
  }

  public alert_category_t category() {
    return new alert_category_t(libtorrent_jni.dht_pkt_alert_category(swigCPtr, this), true);
  }

  public String what() {
    return libtorrent_jni.dht_pkt_alert_what(swigCPtr, this);
  }

  public String message() {
    return libtorrent_jni.dht_pkt_alert_message(swigCPtr, this);
  }

  public byte_const_span pkt_buf() {
    return new byte_const_span(libtorrent_jni.dht_pkt_alert_pkt_buf(swigCPtr, this), true);
  }

  public void setDirection(dht_pkt_alert.direction_t value) {
    libtorrent_jni.dht_pkt_alert_direction_set(swigCPtr, this, value.swigValue());
  }

  public dht_pkt_alert.direction_t getDirection() {
    return dht_pkt_alert.direction_t.swigToEnum(libtorrent_jni.dht_pkt_alert_direction_get(swigCPtr, this));
  }

  public udp_endpoint get_node() {
    return new udp_endpoint(libtorrent_jni.dht_pkt_alert_get_node(swigCPtr, this), true);
  }

  public final static class direction_t {
    public final static dht_pkt_alert.direction_t incoming = new dht_pkt_alert.direction_t("incoming");
    public final static dht_pkt_alert.direction_t outgoing = new dht_pkt_alert.direction_t("outgoing");

    public final int swigValue() {
      return swigValue;
    }

    public String toString() {
      return swigName;
    }

    public static direction_t swigToEnum(int swigValue) {
      if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue)
        return swigValues[swigValue];
      for (int i = 0; i < swigValues.length; i++)
        if (swigValues[i].swigValue == swigValue)
          return swigValues[i];
      throw new IllegalArgumentException("No enum " + direction_t.class + " with value " + swigValue);
    }

    private direction_t(String swigName) {
      this.swigName = swigName;
      this.swigValue = swigNext++;
    }

    private direction_t(String swigName, int swigValue) {
      this.swigName = swigName;
      this.swigValue = swigValue;
      swigNext = swigValue+1;
    }

    private direction_t(String swigName, direction_t swigEnum) {
      this.swigName = swigName;
      this.swigValue = swigEnum.swigValue;
      swigNext = this.swigValue+1;
    }

    private static direction_t[] swigValues = { incoming, outgoing };
    private static int swigNext = 0;
    private final int swigValue;
    private final String swigName;
  }

  public final static alert_category_t static_category = new alert_category_t(libtorrent_jni.dht_pkt_alert_static_category_get(), false);
  public final static int priority = libtorrent_jni.dht_pkt_alert_priority_get();
  public final static int alert_type = libtorrent_jni.dht_pkt_alert_alert_type_get();
}


text:
package com.cloudTop.starshare.widget.emoji;

import android.content.Context;
import android.widget.ImageView;

/**
 * CSDN_LQR
 * 图片加载器(交由外部工程决定)
 */
public interface IImageLoader {

    void displayImage(Context context, String path, ImageView imageView);
}


text:
package gnu.mapping;
import gnu.kawa.io.InPort;
import gnu.kawa.io.OutPort;

public class RunnableClosure<T>
  implements
  /* #ifdef JAVA5 */
  java.util.concurrent.Callable<T>,
  /* #endif */
  Runnable
{
  T result;
  CallContext context;

  // These are only used to when we need to override the parents' in/out/err
  // in the child.  This is not needed for normal RunnableClosure objects, but (say)
  // when starting a repl in a new window.  In that case we could do te
  // in/out/err override in the 'action'.  FIXME.
  private InPort in;
  private OutPort out;
  private OutPort err;
  Throwable exception;

  Procedure action;
  String name;

  static int nrunnables=0;

  public String getName() {
    return name;
  }

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

  public RunnableClosure (Procedure action, CallContext parentContext)
  {
    setName("r"+nrunnables++);
    this.action = action;
  }

  public RunnableClosure (Procedure action,
			  InPort in, OutPort out, OutPort err)
  {
    this(action, CallContext.getInstance());
    this.in = in;
    this.out = out;
    this.err = err;
  }

  public RunnableClosure (Procedure action)
  {
    this(action, CallContext.getInstance());
  }

  /** Get the CallContext we use for this Thread. */
  public final CallContext getCallContext() { return context; }

  public void run ()
  {
    try
      {
        Environment env = Environment.getCurrent();
        String name = getName();
        if (env != null && env.getSymbol() == null && name != null)
          {
            env.setName(name);
          }
        if (context == null)
          context = CallContext.getInstance();
        else
          CallContext.setInstance(context);
	if (in != null)
	  InPort.setInDefault(in);
	if (out != null)
	  OutPort.setOutDefault(out);
	if (err != null)
	  OutPort.setErrDefault(err);
	result = (T) action.apply0 ();
      }
    catch (Error ex)
      {
        throw ex;
      }
    catch (Throwable ex)
      {
	exception = ex;
      }
  }

  /** Get the result of running this {@code Runnable}.
   * The result is a value or a thrown exception.
   * Should be called after {#code run} finishes. */
  Object getResult () throws Throwable
  {
    Throwable ex = exception;
    if (ex != null)
      throw ex;
    return result;
  }

  public T call()
    throws Exception
  {
    run();
    Throwable ex = exception;
    if (ex != null)
      {
        if (ex instanceof Exception)
          throw (Exception) ex;
        else if (ex instanceof Error)
          throw (Error) ex;
        else
          throw new RuntimeException(ex);
      }
    return result;
  }

  public String toString() {
    StringBuffer buf = new StringBuffer();
    buf.append ("#<runnable ");
    buf.append(getName());
    buf.append(">");
    return buf.toString();
  }
}


text:
@interface FakeLocation : NSObject
@end


text:
/**
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
 */

/**
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function(s) {
    var len = s.length;
    var uniqCharHash = {};
    var uniqCharArray = [];

    for(let i = 0; i < len; i++){
        if(typeof uniqCharHash[s[i]] === 'undefined'){
            uniqCharHash[s[i]] = 0;
            uniqCharArray.push(s[i]);
        } else {
            uniqCharArray.indexOf(s[i]) >= 0 && uniqCharArray.splice(uniqCharArray.indexOf(s[i]), 1);
        }
    }

    return s.indexOf(uniqCharArray[0]);
};


text:
/*
*******************************************************************************
*   BOLOS TEE Samples
*   (c) 2016 Ledger
*
*  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.
********************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "bolos.h"

int main(int argc, char **argv) {
	unsigned char data[256];
	unsigned char data2[256];
	//int scope = BLS_SCOPE_DEVICE;
	//int scope = BLS_SCOPE_SESSION;
	int scope = BLS_SCOPE_APPLICATION;
	bls_copy_input_parameters(data, 0, 1);
	if (data[0] != 0x00) {
		unsigned char size = data[0];
		bls_copy_input_parameters(data, 1, size);
		int result = bls_unwrap(scope, data, size, data2, sizeof(data2));
		if (result == 0) {
			bls_debug("Unwrap fail wat");
		}
		else {
			bls_set_return(data2, result);
		}
	}
	else {
		int i;
		for (i=0; i<10; i++) {
			data[i] = i;
		}
		int result = bls_wrap(scope, data, 10, data2, sizeof(data2));
		if (result == 0) {
			bls_debug("Wrap fail");
		}
		else {
			bls_set_return(data2, result);
		}
	}
}


text:
#ifndef CRUFT_UTIL_TIME_PARSE_HPP
#define CRUFT_UTIL_TIME_PARSE_HPP

#include "../view.hpp"

#include <chrono>
#include <ratio>

namespace util::time::iso8601 {
    /// parse ISO8601 formatted datetime strings
    ///
    /// returns nanoseconds since the UNIX epoch (excluding leap seconds).
    ///
    /// recognises fractional seconds up to the numeric limits of
    /// std::chrono::nanoseconds.
    ///
    /// may throw on improperly formatted strings or unrepresentable values.
    std::chrono::nanoseconds
    parse (util::view<const char*>);
}

#endif


text:
const ReactDOMServer = require('react-dom/server');
const path = require('path');
const CookieJar = require('../utils/CookieJar');
const detectDevice = require('../utils/detectDevice');
const detectLocale = require('../utils/detectLocale');
const handleCsrfProtection = require('../utils/handleCsrfProtection');
const getRealPath = require('../utils/getRealPath');
const generateHtmlSnippets = require('../utils/generateHtmlSnippets');
const paths = require('../../config/paths');

module.exports = function createAppOnServer(config) {
  return (req, res) => {
    const cookies = new CookieJar(req, res);

    const [locale, localeSource] = detectLocale(req, cookies, config.intl);
    const device = detectDevice(req, cookies, config.media);
    const csrfHeader = handleCsrfProtection(cookies, config.network);
    const [basename, realPath] = getRealPath(req, locale, localeSource);

    const ctx = {
      basename,
      path: realPath,
      ssr: config.ssr,
      network: {
        csrfHeader,
      },
      media: {
        device,
      },
      intl: {
        locale,
        localeSource,
        defaultLocale: config.intl.defaultLocale,
        locales: config.intl.locales,
      },
    };

    const headers = {
      create: () => ({
        cookie: cookies.serialize(),
        ...csrfHeader,
      }),
    };

    const ctxServerOnly = {
      ...ctx,
      req,
      res,
      network: {
        ...ctx.network,
        cookies,
        headers,
      },
    };

    // Do not cache webpack-manifest.json and all files in /app folder in development
    // See https://github.com/ProAI/react-kickstarter/issues/4
    if (process.env.NODE_ENV === 'development') {
      delete require.cache[paths.webpackManifest];

      Object.keys(require.cache).forEach((id) => {
        if (/[/\\]app[/\\]/.test(id)) delete require.cache[id];
      });
    }

    // define render, redirect and error function for hydrate function
    const render = (component, getData, meta) => {
      // eslint-disable-next-line
      const assets = require(paths.webpackManifest);
      const content = component ? ReactDOMServer.renderToString(component) : '';
      // eslint-disable-next-line
      const renderHtml = require(paths.appHtml);

      const snippets = generateHtmlSnippets(ctx, content, assets, getData ? getData() : {});

      const html = renderHtml(ctxServerOnly, snippets, meta);

      res.status(200).send(html);
    };

    const redirect = (location) => {
      res.redirect(location);
    };

    const error = (status, message) => {
      if (message) {
        res.status(status).send(message);
      } else {
        res.status(status).end();
      }
    };

    // Render page on client if server side rendering is disabled.
    // Initial state should be empty in this case.
    if (!config.ssr) {
      render();
      return;
    }

    const entry =
      process.env.NODE_ENV === 'development'
        ? paths.appServerEntry
        : path.join(paths.webpackCache, 'prod', 'server-bundle.js');

    // get hydrate function and hydrate
    // eslint-disable-next-line
    const hydrate = require(entry).default;

    hydrate(ctxServerOnly, { error, redirect, render });
  };
};


text:
local addon, ns = ...
local cfg = ns.cfg
local cast = CreateFrame("Frame")
  -- special thanks to Allez for coming up with this solution
local channelingTicks = {
	-- warlock
	[GetSpellInfo(689)] = 3, -- "Drain Life"
	[GetSpellInfo(5740)] = 4, -- "Rain of Fire"
	-- druid
	[GetSpellInfo(44203)] = 4, -- "Tranquility"
	[GetSpellInfo(16914)] = 10, -- "Hurricane"
	-- priest
	[GetSpellInfo(15407)] = 3, -- "Mind Flay"
	[GetSpellInfo(48045)] = 5, -- "Mind Sear"
	[GetSpellInfo(47540)] = 2, -- "Penance"
	-- mage
	[GetSpellInfo(5143)] = 5, -- "Arcane Missiles"
	[GetSpellInfo(10)] = 5, -- "Blizzard"
	[GetSpellInfo(12051)] = 4, -- "Evocation"
}
local ticks = {}

cast.setBarTicks = function(castBar, ticknum)
	if ticknum and ticknum > 0 then
		local delta = castBar:GetWidth() / ticknum
		for k = 1, ticknum do
			if not ticks[k] then
				ticks[k] = castBar:CreateTexture(nil, 'OVERLAY')
				ticks[k]:SetTexture(cfg.oUF.media.statusbar)
				ticks[k]:SetVertexColor(0.8, 0.6, 0.6)
				ticks[k]:SetWidth(1)
				ticks[k]:SetHeight(castBar:GetHeight())
			end
			ticks[k]:ClearAllPoints()
			ticks[k]:SetPoint("CENTER", castBar, "LEFT", delta * k, 0 )
			ticks[k]:Show()
		end
	else
		for k, v in pairs(ticks) do
			v:Hide()
		end
	end
end

cast.OnCastbarUpdate = function(self, elapsed)
if not self.Lag then self.Lag = 0 end  ------------------------------------AND THIS SDALKSJD:LKJASLDKJA:LSKDJ:LKASJD:
if GetNetStats() == 0 then return end -- test
	local currentTime = GetTime()
	if self.casting or self.channeling then
		local parent = self:GetParent()
		local duration = self.casting and self.duration + elapsed or self.duration - elapsed
		if (self.casting and duration >= self.max) or (self.channeling and duration <= 0) then
			self.casting = nil
			self.channeling = nil
			return
		end
		if parent.unit == 'player' then
			if self.delay ~= 0 then
				self.Time:SetFormattedText('%.1f | |cffff0000%.1f|r', duration, self.casting and self.max + self.delay or self.max - self.delay)
			elseif self.Lag then -- to avoid errors with the bars that actually have no Lag display
				self.Time:SetFormattedText('%.1f | %.1f', duration, self.max)
				--if self.SafeZone.timeDiff ~= 0 then self.Lag:SetFormattedText("%d ms", self.SafeZone.timeDiff * 1000) end
				if self.SafeZone and self.SafeZone.timeDiff ~= 0 then self.Lag:SetFormattedText("%d ms", self.SafeZone.timeDiff * 1000) end
			end
		else
			self.Time:SetFormattedText('%.1f | %.1f', duration, self.casting and self.max + self.delay or self.max - self.delay)
		end
		self.duration = duration
		self:SetValue(duration)
		self.Spark:SetPoint('CENTER', self, 'LEFT', (duration / self.max) * self:GetWidth(), 0)
	elseif self.fadeOut then
		self.Spark:Hide()
		local alpha = self:GetAlpha() - 0.02
		if alpha > 0 then
			self:SetAlpha(alpha)
		else
			self.fadeOut = nil
			self:Hide()
		end
	end
end

cast.OnCastSent = function(self, event, unit, spell, rank)
	if self.unit ~= unit or not self.Castbar.SafeZone then return end
	self.Castbar.SafeZone.sendTime = GetTime()
	self.Castbar.SafeZone.castSent = true
end

cast.PostCastStart = function(self, unit, name, rank, text)
	self:SetAlpha(1.0)
	self.Spark:Show()
	self:SetStatusBarColor(unpack(self.casting and self.CastingColor or self.ChannelingColor))
	if unit == 'vehicle' then
		self.SafeZone:Hide()
		self.Lag:Hide()
	elseif unit == 'player' then
		if GetNetStats() == 0 then return end -- test
		local sz = self.SafeZone
		if not sz then return end -- fix for swapped vehicles' cast bars when channeling
		--if not sz.sendTime then sz.sendTime = GetTime() end
		sz.timeDiff = 0
		self.Lag:SetText("")
		if sz.castSent == true then
			sz.timeDiff = GetTime() - sz.sendTime
			sz.timeDiff = sz.timeDiff > self.max and self.max or sz.timeDiff
			sz:SetWidth(self:GetWidth() * sz.timeDiff / self.max)
			sz:Show()
			sz.castSent = false
		end
		if not UnitInVehicle("player") then sz:Show() self.Lag:Show() else sz:Hide() self.Lag:Hide() end
		if self.casting then
			cast.setBarTicks(self, 0)
		else
			local spell = UnitChannelInfo(unit)
			self.channelingTicks = channelingTicks[spell] or 0
			cast.setBarTicks(self, self.channelingTicks)
		end
	elseif (unit == "target" or unit == "focus" or (unit and unit:find("boss%d"))) and self.interrupt then
		self:SetStatusBarColor(unpack(cfg.oUF.castbar.color.uninterruptable))
	else
		self:SetStatusBarColor(cfg.oUF.castbar.color.normal[1], cfg.oUF.castbar.color.normal[2], cfg.oUF.castbar.color.normal[3],1)
	end
end

cast.PostCastStop = function(self, unit, name, rank, castid)
	if not self.fadeOut then
		self:SetStatusBarColor(unpack(self.CompleteColor))
		self.fadeOut = true
	end
	self:SetValue(self.max)
	self:Show()
end

cast.PostChannelStop = function(self, unit, name, rank)
	cast.setBarTicks(self, 0)
	self.fadeOut = true
	self:SetValue(0)
	self:Show()
end

cast.PostCastFailed = function(self, event, unit, name, rank, castid)
	self:SetStatusBarColor(unpack(self.FailColor))
	self:SetValue(self.max)
	if not self.fadeOut then
		self.fadeOut = true
	end
	self:Show()
end
  --hand the lib to the namespace for further usage
  ns.cast = cast


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W30140_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans733.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">AREA OF DISTURBANCE — 13.2 ACRESi NOTE, THE WES WILL BE wmum
AT A SLOPE 0F 2:1 . EXCEPT THE
2 E SOUTH SIDE WILL BE AT A SLOPE 0F 3:1.
NOTE: THE SUBSOI QUANTITY LISTED CONTAINS AN ADDITIONAL 1.950 CY FOR MOVING THE EXISTING STOCKPILE.

ESTIMATED EARTH QUANTITIES
CONTINENTAL RESOURCES INC. ARE STAKED
Po Box 268870 ELIOT:st 13:33 SHEIEIIEBE GRADE ELEVA—
OKLAHOMA CITY, OKLAHOMA 73126 SUBSOIL: 37,363 CUBIC YARDS TIONs,
TOTAL CUT: 57.654 CUBIC YARDS BACKSLOPES
ASSUME!) pRoDUCTION FACILITY TOTAL FILL: 31,175 CUBIC YARDS AT 2 : 1
SECTION 7. T146N. R95w , A , DUNN COUNTY. NORTH DAKOTA finished RIg Grade ElevatIon: 2441.5 ft. ASL
DRAFT: HEDGE SCALE I = 150 DATE: 9—5-2013 PROJECT NO. 13-40

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
#ifndef UFA_VEC2_HPP
#define UFA_VEC2_HPP

#include <string>

namespace ufa
{
	/* This class implements a 2D vector. It provides mathematical operators for adding,
	 * subtracting and scaling. */
	class Vec2
	{
	public:
		float x;
		float y;

		Vec2(): x(0), y(0) { }
		Vec2(float p_x, float p_y): x(p_x), y(p_y) { }
		~Vec2() { }

		void set(const float p_x, const float p_y);
		float lengthSQ() const;
		float length() const;
		Vec2 perpendicular() const;

		Vec2& operator+=(Vec2 const& p_vec);
		Vec2& operator-=(Vec2 const& p_vec);
		Vec2& operator*=(const float p_factor);
		Vec2& operator/=(const float p_divisor);

		std::string str() const;
	};

	const Vec2 operator+(Vec2 const& p_vec1, Vec2 const& p_vec2);
	const Vec2 operator-(Vec2 const& p_vec1, Vec2 const& p_vec2);
	const Vec2 operator*(Vec2 const& p_vec, const float p_factor);
	const Vec2 operator*(const float p_factor, Vec2 const& p_vec);
	const Vec2 operator/(Vec2 const& p_vec, const float p_divisor);
	bool operator==(Vec2 const& p_vec1, Vec2 const& p_vec2);
	bool operator!=(Vec2 const& p_vec1, Vec2 const& p_vec2);
}

#endif


text:
package de.mario222k.mangarx.chapter;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

/**
 * Helper for all Toolbar Stuff.
 * Created by Mario.Sorge on 27/12/15.
 */
public class ToolbarHelper {

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler(Looper.getMainLooper());

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run () {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)
            // and API 19 (KitKat). It is safe to use them, as they are inlined
            // at compile-time and do nothing on earlier devices.
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };

    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run () {
            // Delayed display of UI elements
            ActionBar actionBar = mActivity.getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
            if (mControlsView != null) {
                mControlsView.setVisibility(View.VISIBLE);
            }
        }
    };

    @NonNull
    private AppCompatActivity mActivity;
    @Nullable
    private View mControlsView;
    private View mContentView;
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run () {
            hide();
        }
    };

    public ToolbarHelper (@NonNull AppCompatActivity activity,
                          @Nullable View controlsView,
                          @NonNull View contentView) {
        mActivity = activity;
        mControlsView = controlsView;
        mContentView = contentView;
    }

    public void setVisible (boolean isVisible) {
        mVisible = isVisible;
    }

    public void toggle () {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    public void hide () {
        // Hide UI first
        ActionBar actionBar = mActivity.getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        if (mControlsView != null) {
            mControlsView.setVisibility(View.GONE);
        }
        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay
        mHideHandler.removeCallbacks(mShowPart2Runnable);
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    @SuppressLint("InlinedApi")
    public void show () {
        // Show the system bar
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        mVisible = true;

        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable);
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }

    /**
     * Schedules a call to hide() in [delay] milliseconds, canceling any
     * previously scheduled calls.
     */
    public void delayedHide (int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }

    /**
     * Get visible state.
     *
     * @return {@code true} if visible
     */
    public boolean isVisible () {
        return mVisible;
    }

    @NonNull
    public AppCompatActivity getActivity () {
        return mActivity;
    }
}


text:
goog.module('grrUi.core.canaryOnlyDirective');
goog.module.declareLegacyNamespace();

const {ApiService} = goog.require('grrUi.core.apiService');

/**
 * Determines whether the canary mode is on.
 *
 * @param {!ApiService} grrApiService
 * @param {function(boolean)} callback The canary mode flag will be passed to
 * this callback when it'll be determined in background.
 */
var getCanaryModeValue = function(grrApiService, callback) {
  grrApiService.getCached('/users/me').then(function(response) {
    var canaryMode;

    try {
      canaryMode = /** @type {boolean} */ (
          response['data']['value']['settings']
                  ['value']['canary_mode']['value']);
    } catch(err) {
      canaryMode = false;
    }

    callback(canaryMode);
  });
};

/**
 * @constructor
 * @param {!ApiService} grrApiService
 * @ngInject
 */
const CanaryOnlyController = function(grrApiService) {
  /** @type {boolean} */
  // Hide the contents until the api call returns.
  this.canaryMode = false;

  getCanaryModeValue(grrApiService, (canaryMode) => {
    this.canaryMode = canaryMode;
  });
};

/**
 * @constructor
 * @param {!ApiService} grrApiService
 * @ngInject
 */
const NonCanaryOnlyController = function(grrApiService) {
  /** @type {boolean} */
  // Hide the contents until the api call returns.
  this.canaryMode = true;

  getCanaryModeValue(grrApiService, (canaryMode) => {
    this.canaryMode = canaryMode;
  });
};

/**
 * Directive that renders its contents only in canary mode.
 *
 * @constructor
 * @ngInject
 * @export
 * @return {angular.Directive} Directive definition object.
 */
exports.CanaryOnlyDirective = function() {
  return {
    scope: {},
    restrict: 'E',
    controller: CanaryOnlyController,
    controllerAs: 'controller',
    transclude: true,
    template: '<ng-transclude ng-if=\'controller.canaryMode\'></ng-transclude>'
  };
};

/**
 * Directive's name in Angular.
 *
 * @const
 * @export
 */
exports.CanaryOnlyDirective.directive_name = 'grrCanaryOnly';

/**
 * Directive that renders its contents only in nonCanary mode.
 *
 * @return {!angular.Directive} Directive definition object.
 * @ngInject
 * @export
 */
exports.NonCanaryOnlyDirective = function() {
  return {
    scope: {},
    restrict: 'E',
    controller: NonCanaryOnlyController,
    controllerAs: 'controller',
    transclude: true,
    template: '<ng-transclude ng-if=\'!controller.canaryMode\'></ng-transclude>'
  };
};

/**
 * Directive's name in Angular.
 *
 * @const
 * @export
 */
exports.NonCanaryOnlyDirective.directive_name = 'grrNonCanaryOnly';


text:
define(['fixtures'], function(fixtures) {
    'use strict';
    return function($httpBackend) {
        $httpBackend.when('GET', 'api/principal').respond({
            id: 0,
            email: 'admin@techdev.de',
            enabled: true,
            authorities: [
                {authority: 'ROLE_ADMIN'}
            ],
            fake: true
        });

        /**
         * Mocks a request to an entity root that can contain parameters like page, sort, size (they will be ignored though).
         * Responds with data from the fixtures.
         * @param url The URL to mock, like '/api/companies'.
         */
        function mockRoot(url) {
            //base
            $httpBackend.whenGET(url).respond(fixtures[url]);
            //with query parameters
            var pattern = new RegExp('^' + url + '\\?.*$');
            $httpBackend.whenGET(pattern).respond(fixtures[url]);
        }

        /**
         * Mocks a POST to an entity root, just answers with 201 and the data inserted.
         * @param url The url on which to mock POST.
         */
        function mockPost(url) {
            $httpBackend.whenPOST(url).respond(function(method, url, data) {
                return [201, data];
            });
        }

        /**
         * Mock patching a single entitiy
         * @param url The url to mock (e.g. 'api/employees'
         */
        function mockPatch(url) {
            var pattern = new RegExp('^' + url + '/\\d+$');
            $httpBackend.whenPATCH(pattern).respond(function(method, url, data) {
                return [200, data];
            });
        }

        //##### -- ADDRESSES
        mockPatch('api/addresses');
        $httpBackend.whenPOST('api/addresses')
            .respond(function() {
                var address = { _links: { self: { href: '' } } };
                return [200, address];
            });
        $httpBackend.whenPUT(/^api\/addresses\/\d+$/).respond(function(method, url, data) {
            return [201, data];
        });

        //#### -- BILLABLE TIMES
        mockPost('api/billableTimes');
        $httpBackend.whenGET(/^api\/billableTimes\/findEmployeeMappingByProjectAndDateBetween\?.*/)
            .respond(fixtures['api/billableTimes']);
        $httpBackend.whenGET(/^api\/billableTimes\/search\/findByDateBetween\?end=\d+&projection=withProject&start=\d+/)
            .respond(function() {
                var data = fixtures['api/billableTimes'];
                data._embedded.billableTimes.forEach(function(billableTime) {
                    billableTime.project = fixtures['api/projects']._embedded.projects[0];
                });
                return [200, data];
            });

        //#### -- COMPANIES
        mockRoot('api/companies');
        mockPost('api/companies');
        mockPatch('api/companies');
        $httpBackend.when('GET', /^api\/companies\/[\d]+$/)
            .respond(fixtures['api/companies']._embedded.companies[0]);
        $httpBackend.when('GET', /^api\/companies\/[\d]+\/projects/)
            .respond(fixtures['api/projects']);
        $httpBackend.whenGET(/^api\/companies\/search\/findByCompanyId\?companyId=\w+$/)
            .respond(fixtures['api/companies']);
        $httpBackend.whenGET(/^api\/companies\/search\/findByCompanyId\?companyId=\w+&projection=\w+$/)
            .respond(function() {
                var response = fixtures['api/companies'];
                response._embedded.companies[0].address = fixtures['api/addresses']._embedded.addresses[0];
                response._embedded.companies[0].contactPersons = fixtures['api/contactPersons']._embedded.contactPersons;
                return [200, response];
            });
        $httpBackend.whenGET(/^api\/companies\/search\/findByNameLikeIgnoreCaseOrderByNameAsc\?.*/)
            .respond(fixtures['api/companies']);

        //#### -- CONTACT PERSONS
        mockRoot('api/contactPersons');
        mockPost('api/contactPersons');
        $httpBackend.whenGET(/^api\/contactPersons\/[\d]+$/).respond(fixtures['api/contactPersons']._embedded.contactPersons[0]);
        $httpBackend.whenDELETE(/^api\/contactPersons\/\d+/).respond([204]);

        //#### -- EMPLOYEES
        mockRoot('api/employees');
        mockPatch('api/employees');
        mockPost('api/employees');
        $httpBackend.whenGET(/^api\/employees\/\d+$/).respond(fixtures['api/employees']._embedded.employees[0]);
        $httpBackend.whenGET(/^api\/employees\/\d+\?projection=withAddress$/).respond(function() {
            var employee = fixtures['api/employees']._embedded.employees[0];
            employee.address = fixtures['api/addresses']._embedded.addresses[0];
            return [200, employee];
        });
        $httpBackend.whenGET(/^api\/employees\/\d+\/self$/).respond(fixtures['api/employees']._embedded.employees[0]);
        $httpBackend.whenPUT(/^api\/employees\/\d+\/self$/).respond(function(method, url, data) {
            return [200, data];
        });
        $httpBackend.whenPUT(/^api\/employees\/\d+\/address$/).respond([204]);

        //#### -- FEDERAL STATES
        mockRoot('api/federalStates');

        //#### -- INVOICES
        mockRoot('api/invoices');
        mockPost('api/invoices');
        $httpBackend.whenGET(/^api\/invoices\/search\/findByInvoiceState\?page=\d+&projection=\w+&size=\d+&sort=creationDate&state=\w+/)
            .respond(fixtures['api/invoices']);
        $httpBackend.whenGET(/^api\/invoices\/search\/findByIdentifierLikeIgnoreCaseAndInvoiceState\?identifier=%25\w+%25&page=\d+&projection=\w+&size=\d+&sort=creationDate&state=\w+/)
            .respond(fixtures['api/invoices']);
        $httpBackend.whenGET(/^api\/invoices\/search\/findByCreationDateBetween\?end=\d+&projection=withDebitor&start=\d+/)
            .respond(function() {
                //add a debitor
                var invoices = fixtures['api/invoices'];
                invoices._embedded.invoices.forEach(function(invoice) {
                    invoice.debitor = fixtures['api/companies']._embedded.companies[0];
                });
                return [200, invoices];
            });
        $httpBackend.whenPOST(/^api\/invoices\/\d+\/markPaid$/)
            .respond([204, 'Ok.']);

        //#### -- PROJECTS
        mockRoot('api/projects');
        mockPost('api/projects');
        $httpBackend.whenGET(/^api\/projects\/\d+$/)
            .respond(fixtures['api/projects']._embedded.projects[0]);
        $httpBackend.whenGET(/api\/projects\/search\/findByNameLikeIgnoreCaseOrIdentifierLikeIgnoreCaseOrderByNameAsc\?.*/)
            .respond(fixtures['api/projects']);
        $httpBackend.whenGET(/api\/projects\/search\/findByIdentifier\?.*/)
            .respond(fixtures['api/projects']);

        //#### -- REDUCED EMPLOYEES / ADDRESSBOOK
        $httpBackend.whenGET(/^api\/address_book\?page=\d+&size=\d+/)
            .respond(fixtures['api/address_book']._embedded.reducedEmployees);

        //#### -- TRAVEL EXPENSES
        mockPost('api/travelExpenses');
        mockPatch('api/travelExpenses');
        $httpBackend.whenDELETE(/^api\/travelExpenses\/\d+/).respond([204]);

        //#### -- TRAVEL EXPENSE REPORTS
        mockPost('api/travelExpenseReports');
        $httpBackend.whenGET(/^api\/travelExpenseReports\/\d+\?projection=\w+/)
            .respond(function() {
                var fixture = fixtures['api/travelExpenseReports']._embedded.travelExpenseReports[0];
                fixture.expenses = fixtures['api/travelExpenses']._embedded.travelExpenses;
                return [200, fixture];
            });
        $httpBackend.whenGET(/^api\/travelExpenseReports\/\d+\/comments\?projection=\w+/)
            .respond(function() {
                var fixture = fixtures['api/travelExpenseReportComments']._embedded.travelExpenseReportComments;
                fixture.forEach(function(comment) {
                    comment.employee = fixtures['api/employees']._embedded.employees[0];
                });
                return [200, fixture];
            });
        $httpBackend.whenGET(/^api\/travelExpenseReports\/search\/findByEmployeeAndStatusOrderByStatusAsc\?page=\d+&projection=\w+&size=\d+&sort=\w*&status=\w+$/)
            .respond(fixtures['api/travelExpenseReports']);
        $httpBackend.whenGET(/^api\/travelExpenseReports\/search\/findByStatus\?page=\d+&projection=\w+&size=\d+&sort=[\w,\.]*&status=\w+$/)
            .respond(fixtures['api/travelExpenseReports']);
        $httpBackend.whenGET(/^api\/travelExpenseReports\/search\/findBySubmissionDateBetween\?end=\d+&projection=withEmployeeAndExpenses&start=\d+$/)
            .respond(function() {
                var data = fixtures['api/travelExpenseReports'];
                data._embedded.travelExpenseReports.forEach(function(report) {
                    report.employee = fixtures['api/employees']._embedded.employees[0];
                    report.expenses = fixtures['api/travelExpenses']._embedded.expenses;
                });
                return [200, data];
            });
        $httpBackend.whenPUT(/^api\/travelExpenseReports\/\d+\/submit/)
            .respond([204]);
        $httpBackend.whenPUT(/^api\/travelExpenseReports\/\d+\/approve/)
            .respond([204]);
        $httpBackend.whenPUT(/^api\/travelExpenseReports\/\d+\/reject/)
            .respond([204]);

        //#### -- TRANSLATIONS
        $httpBackend.whenPUT(/^api\/translations\?.*/).respond({});
        $httpBackend.whenGET(/^api\/translations\?.*/).respond({});

        //#### -- VACATION REQUESTS
        mockPost('api/vacationRequests');
        $httpBackend.whenGET(/^api\/vacationRequests\/search\/findByEmployeeOrderByStartDateAsc\?.*/)
            .respond(fixtures['api/vacationRequests']);
        $httpBackend.whenGET(/^api\/vacationRequests\/search\/findByStatusOrderBySubmissionTimeAsc\?.*/)
            .respond(fixtures['api/vacationRequests']);
        $httpBackend.whenGET(/^api\/vacationRequests\/daysPerEmployeeBetween\?end=\d+&projection=withEmployeeAndApprover&start=\d+$/)
            .respond(function() {
                var data = fixtures['api/vacationRequests'];
                data._embedded.vacationRequests.forEach(function(vacationRequest) {
                    var employee = fixtures['api/employees']._embedded.employees[0];
                    vacationRequest.employee = employee;
                    vacationRequest.approver = employee;
                });
                return [200, data];
            });
        $httpBackend.whenDELETE(/^api\/vacationRequests\/\d+/).respond([204]);
        $httpBackend.whenPUT(/^api\/vacationRequests\/\d+\/approve/).respond(function() {
            return [200, {
                approver: 'api/employees/0',
                status: 'APPROVED',
                approvalDate: new Date()
            }];
        });
        $httpBackend.whenPUT(/^api\/vacationRequests\/\d+\/reject/).respond(function() {
            return [200, {
                approver: 'api/employees/0',
                status: 'REJECTED',
                approvalDate: new Date()
            }];
        });

        //#### -- WORK TIMES
        mockPost('api/workTimes');
        $httpBackend.whenGET(/api\/workTimes\/findEmployeeMappingByProjectAndDateBetween\?.*/)
            .respond(fixtures['api/workTimes/findEmployeeMappingByProjectAndDateBetween']);
        $httpBackend.whenGET(/api\/workTimes\/search\/findByEmployeeAndDateBetweenOrderByDateAscStartTimeAsc\?.*/)
            .respond(fixtures['api/workTimes']);
        $httpBackend.whenGET(/api\/workTimes\/\d+\/project/).respond(fixtures['api/projects']._embedded.projects[0]);
        $httpBackend.whenGET(/^api\/workTimes\/search\/findByDateBetween\?end=\d+&projection=withProject&start=\d+/)
            .respond(function() {
                var data = fixtures['api/workTimes'];
                data._embedded.workTimes.forEach(function(workTime) {
                    workTime.project = fixtures['api/projects']._embedded.projects[0];
                });
                return [200, data];
            });
        $httpBackend.whenGET(/^api\/workTimes\/search\/findByDateBetween\?end=\d+&projection=withEmployee&start=\d+$/)
            .respond(function() {
                var data = fixtures['api/workTimes'];
                data._embedded.workTimes.forEach(function(workTime) {
                    workTime.employee = fixtures['api/employees']._embedded.employees[0];
                });
                return [200, data];
            });

        /* ############################ TEMPLATES ########################### */
        /*
         Just return an empty template.
         */
        $httpBackend.whenGET(/^.*\.tpl\.html$/).respond(
            [200, '

']
        );
    };
});


text:
JsErrors is a service for javascript error logging and analysis.
Instead of creating per-project javascript logging storage and review facilities, keep the logs from all your web apps in one place in the "cloud" for easy access.
It's as simple as including `<script src="..."></script>` into your page(s)

## I prefer to see it for myself

Sure thing, here's the fastest way to try it:

1. Go to [http://jserror.vkaldi.com/register](http://jserror.vkaldi.com/register) to get your ApiKey
2. Insert this snippet on top of your page (the higher, the better)

        <script type="text/javascript">
          // set options
          var _jse_options = { apiKey: 'YOUR_API_KEY' };
        </script>
        <!-- include logging script -->
        <script type="text/javascript" src="//d3ol89ay0lkrhh.cloudfront.net/assets/custom/tracking_script.js"></script>

3. That's it! Javascript errors from your page are now sent into your JsError account.
    You can check them by logging in on [http://jserror.vkaldi.com/users/sign_in](http://jserror.vkaldi.com/users/sign_in)
    Don't worry, only you can access the log!

4. Optionally, you should add an explicit try...catch logging code because JsError is able to show you more info regarding the exception that way

        <script type="text/javascript">
        	try {
        		// faulty code that fails :)
        		i_do_not_exist.method();
        	} catch (e) {
        		// log the error
        		JsErrors.LogError(e);
        	}
          // set options
          var _jse_options = { apiKey: 'YOUR_API_KEY' };
        </script>

## How and what does JsError log?

JsError attaches itself to the window.onerror event and logs any unhandled javascript errors automatically.
Optionally it can log errors explicitly via `JsErrors.LogError()` when called from your `try...catch` error handling code.

Errors are sent via Ajax or as a fallback via a hidden iframe post.
Either way, the process is seamless for the end user.

Ultimately, the error ends up on the JsError server which is hosted in an Amazon EC2 instance and can be accessed on [http://jserror.vkaldi.com](http://jserror.vkaldi.com).
For speedier delivery, the tracking script is hosted in Amazon CloudFront.

## Compatiblity

Compatibility list to be created, but in general, the tracking script should work given that the code is not using any browser specific stuff.

## Contributing

By all means, if see anything you would like to be added open an issue or better yet; contribute directly with a pull request.

## License

JsErrors is released under the [MIT License](http://www.opensource.org/licenses/MIT).
Please see the accompanying "LICENSE" file for details.