text:
package com.google.gapid.perfetto.models;

import static com.google.gapid.perfetto.views.StyleConstants.DEFAULT_COUNTER_TRACK_HEIGHT;
import static com.google.gapid.perfetto.views.StyleConstants.PROCESS_COUNTER_TRACK_HEIGHT;
import static com.google.gapid.perfetto.views.TrackContainer.group;
import static com.google.gapid.perfetto.views.TrackContainer.single;
import static java.util.logging.Level.WARNING;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.gapid.models.Perfetto;
import com.google.gapid.perfetto.canvas.Panel;
import com.google.gapid.perfetto.models.TrackConfig.Group;
import com.google.gapid.perfetto.views.AsyncPanel;
import com.google.gapid.perfetto.views.CounterPanel;
import com.google.gapid.perfetto.views.CpuFrequencyPanel;
import com.google.gapid.perfetto.views.CpuPanel;
import com.google.gapid.perfetto.views.CpuSummaryPanel;
import com.google.gapid.perfetto.views.FrameEventsPanel;
import com.google.gapid.perfetto.views.GpuQueuePanel;
import com.google.gapid.perfetto.views.ProcessSummaryPanel;
import com.google.gapid.perfetto.views.ThreadPanel;
import com.google.gapid.perfetto.views.TitlePanel;
import com.google.gapid.perfetto.views.VulkanCounterPanel;
import com.google.gapid.perfetto.views.VulkanEventPanel;
import com.google.gapid.proto.device.GpuProfiling.GpuCounterDescriptor.GpuCounterGroup;
import com.google.gapid.util.Scheduler;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * Determines what tracks to show for a trace.
 */
public class Tracks {
  private static final Logger LOG = Logger.getLogger(Tracks.class.getName());

  // CPU usage percentage at which a process/thread is considered idle.
  private static final double IDLE_PERCENT_CUTOFF = 0.001; // 0.1%.
  // Polled counters from the process_stats data source.
  private static final ImmutableSet<String> PROC_STATS_COUNTER = ImmutableSet.of(
      "mem.virt", "mem.rss", "mem.locked", "oom_score_adj"
  );

  private static final ImmutableMap<GpuCounterGroup, String> GPU_COUNTER_GROUP_NAMES =
      new ImmutableMap.Builder<GpuCounterGroup, String>()
          .put(GpuCounterGroup.UNCLASSIFIED, "General Counters")
          .put(GpuCounterGroup.SYSTEM, "System Counters")
          .put(GpuCounterGroup.VERTICES, "Vertex Counters")
          .put(GpuCounterGroup.FRAGMENTS, "Fragment Counters")
          .put(GpuCounterGroup.PRIMITIVES, "Primitive Counters")
          .put(GpuCounterGroup.MEMORY, "Memory Counters")
          .put(GpuCounterGroup.COMPUTE, "Compute Counters")
          .build();

  private Tracks() {
  }

  public static ListenableFuture<Perfetto.Data.Builder> enumerate(Perfetto.Data.Builder data) {
    return Scheduler.EXECUTOR.submit(() -> {
      enumerateCpu(data);
      enumerateCounters(data);
      enumerateGpu(data);
      enumerateFrame(data);
      enumerateProcesses(data);
      enumerateVSync(data);
      return data;
    });
  }

  private static Perfetto.Data.Builder enumerateCpu(Perfetto.Data.Builder data) {
    if (!data.getCpu().hasCpus()) {
      return data;
    }

    CpuSummaryTrack summary = new CpuSummaryTrack(data.qe, data.getCpu().count());
    boolean hasAnyFrequency = false;
    for (CpuInfo.Cpu cpu : data.getCpu().cpus()) {
      CpuTrack track = new CpuTrack(data.qe, cpu);
      data.tracks.addTrack(summary.getId(), track.getId(), "CPU " + cpu.id,
          single(state -> new CpuPanel(state, track), false, false));
      if (cpu.hasFrequency()) {
        CpuFrequencyTrack freqTrack = new CpuFrequencyTrack(data.qe, cpu);
        data.tracks.addTrack(summary.getId(), freqTrack.getId(), "CPU " + cpu.id + " Frequency",
            single(state -> new CpuFrequencyPanel(state, freqTrack), false, false));
        hasAnyFrequency = true;
      }
    }

    Group.UiFactory ui = hasAnyFrequency ?
        group(state -> new CpuSummaryPanel(state, summary), true, (group, showDetails) -> {
          for (int cpu = 0, track = 0; cpu < data.getCpu().count(); cpu++, track++) {
            if (data.getCpu().get(cpu).hasFrequency()) {
              track++;
              group.setVisible(track, showDetails);
            }
          }
        }, false) :
        group(state -> new CpuSummaryPanel(state, summary), true);
    data.tracks.addLabelGroup(null, summary.getId(), "CPU Usage", ui);
    return data;
  }

  public static Perfetto.Data.Builder enumerateCounters(Perfetto.Data.Builder data) {
    MemorySummaryTrack.enumerate(data);
    BatterySummaryTrack.enumerate(data);
    PowerSummaryTrack.enumerate(data);
    return data;
  }

  public static Perfetto.Data.Builder enumerateGpu(Perfetto.Data.Builder data) {
    Map<Long, CounterInfo> counters = data.getCounters(CounterInfo.Type.Gpu).values().stream()
        .filter(c -> c.count > 0)
        .collect(toMap(c -> c.id, c -> c));

    List<CounterInfo> gpuMemGlobalCounter =
        data.getCounters().values().stream()
            .filter(c -> c.type == CounterInfo.Type.Global &&
                c.ref == 0 /* pid - 0 */ &&
                c.count > 0 &&
                c.name.equals("GPU Memory"))
            .collect(toList());

    if (counters.isEmpty() && data.getGpu().isEmpty() && gpuMemGlobalCounter.isEmpty()) {
      // No GPU data available.
      return data;
    }

    data.tracks.addLabelGroup(null, "gpu", "GPU", group(state -> new TitlePanel("GPU"), true));

    if (!gpuMemGlobalCounter.isEmpty()) {
      if (gpuMemGlobalCounter.size() > 1) {
        LOG.log(WARNING, "Expected 1 global gpu memory counter. Found " + gpuMemGlobalCounter.size());
      }
      CounterInfo counter = gpuMemGlobalCounter.get(0);
      CounterTrack track = new CounterTrack(data.qe, counter);
      data.tracks.addTrack("gpu", track.getId(), counter.name,
          single(state -> new CounterPanel(state, track, DEFAULT_COUNTER_TRACK_HEIGHT), true,
              /*right truncate*/ true));
    }

    if (data.getGpu().queueCount() > 0) {
      String parent = "gpu";
      if (data.getGpu().queueCount() > 1) {
        data.tracks.addLabelGroup(
            "gpu", "gpu_queues", "GPU Queues", group(state -> new TitlePanel("GPU Queues"), true));
        parent = "gpu_queues";
      }
      for (GpuInfo.Queue queue : data.getGpu().queues()) {
        SliceTrack track = SliceTrack.forGpuQueue(data.qe, queue);
        data.tracks.addTrack(parent, track.getId(), queue.getDisplay(),
            single(state -> new GpuQueuePanel(state, queue, track), true, false));
      }
    }

    if (data.getGpu().vkApiEventCount() > 0) {
      String parent = "gpu";
      if (data.getGpu().vkApiEventCount() > 1) {
        data.tracks.addLabelGroup(
            "gpu", "vk_api_events", "Vulkan API Events", group(state -> new TitlePanel("Vulkan API Events"), true));
        parent = "vk_api_events";
      }
      for (GpuInfo.VkApiEvent vkApiEvent : data.getGpu().vkApiEvents()) {
        VulkanEventTrack track = new VulkanEventTrack(data.qe, vkApiEvent);
        data.tracks.addTrack(parent, track.getId(), vkApiEvent.getDisplay(),
            single(state -> new VulkanEventPanel(state, vkApiEvent, track), true, false));
      }
    }

    if (!counters.isEmpty()) {
      String parent = "gpu";
      if (counters.size() > 1) {
        data.tracks.addLabelGroup("gpu", "gpu_counters", "GPU Counters",
            group(state -> new TitlePanel("GPU Counters"), true));
        parent = "gpu_counters";
      }
      Map<CounterInfo, CounterTrack> addedTracks = Maps.newHashMap();
      Multimap<Long, Long> groups = data.getGpuCounterGroups();
      if (groups.keySet().size() > 1) {
        for (GpuCounterGroup group : GpuCounterGroup.values()) {
          if (group == GpuCounterGroup.UNRECOGNIZED) {
            continue;
          }
          Collection<Long> grouped_counters = groups.get(Long.valueOf(group.getNumber()));
          if (grouped_counters.isEmpty()) {
            continue;
          }
          parent = "gpu_counters_group_" + group.name();
          String name = GPU_COUNTER_GROUP_NAMES.get(group);
          data.tracks.addLabelGroup("gpu_counters", parent, name,
              group(state -> new TitlePanel(name), true));
          for (Long counter_id : grouped_counters) {
            CounterInfo counter = counters.get(counter_id);
            if (counter == null) {
              continue;
            }
            CounterTrack track = addedTracks.computeIfAbsent(counter, res -> new CounterTrack(data.qe, counter));
            data.tracks.addTrack(parent, group.name() + track.getId(), counter.name,
                single(state -> new CounterPanel(state, track, DEFAULT_COUNTER_TRACK_HEIGHT), true,
                  /*right truncate*/ true));
          }
        }
      } else {
        for (CounterInfo counter : counters.values()) {
          CounterTrack track = new CounterTrack(data.qe, counter);
          data.tracks.addTrack(parent, track.getId(), counter.name,
              single(state -> new CounterPanel(state, track, DEFAULT_COUNTER_TRACK_HEIGHT), true,
                  /*right truncate*/ true));
        }
      }
    }
    return data;
  }

  public static Perfetto.Data.Builder enumerateFrame(Perfetto.Data.Builder data) {
    if (data.getFrame().layerCount() > 0) {
      String parent = "sf_events";
      data.tracks.addLabelGroup(null, parent, "Surface Flinger Events",
          group(state -> new TitlePanel("Surface Flinger Events"), true));

      // We assume here that the target application's layer will generally have more
      // events than unintended layers from the likes of StatusBar, NavBar etc.
      long maxEvents = 0;
      for (FrameInfo.Layer layer : data.getFrame().layers()) {
        if (layer.numEvents > maxEvents) {
          maxEvents = layer.numEvents;
        }
      }

      for (FrameInfo.Layer layer : data.getFrame().layers()) {
        boolean expanded = (layer.numEvents == maxEvents);
        data.tracks.addLabelGroup(parent, layer.layerName, layer.layerName,
            group(state -> new TitlePanel("Layer - " + layer.layerName), expanded));
        for (FrameInfo.Event phase : layer.phaseEvents()) {
          FrameEventsTrack track = FrameEventsTrack.forFrameEvent(data.qe, layer.layerName, phase);
          data.tracks.addTrack(layer.layerName, track.getId(), phase.getDisplay(),
              single(state -> new FrameEventsPanel(state, phase, track), true, false));
        }
        String buffersGroup = "buffers_" + layer.layerName;
        data.tracks.addLabelGroup(layer.layerName, buffersGroup, "Buffers",
            group(state -> new TitlePanel("Buffers"), false));
        for (FrameInfo.Event buffer : layer.bufferEvents()) {
          FrameEventsTrack track = FrameEventsTrack.forFrameEvent(data.qe, layer.layerName, buffer);
          data.tracks.addTrack(buffersGroup, track.getId(), buffer.getDisplay(),
              single(state -> new FrameEventsPanel(state, buffer, track), true, true));
        }
      }
    }
    return data;
  }

  public static Perfetto.Data.Builder enumerateProcesses(Perfetto.Data.Builder data) {
    List<ProcessInfo> processes = Lists.newArrayList(data.getProcesses().values());
    Collections.sort(processes, (p1, p2) -> Long.compare(p2.totalDur, p1.totalDur));
    final int count = processes.size();
    if (count == 0) {
      return data;
    }

    final long idleCutoffProc = Math.round(IDLE_PERCENT_CUTOFF * data.getTraceTime().getDuration());

    data.tracks.addLabelGroup(null, "procs", "Processes",
        group(state -> new TitlePanel("Processes (" + count + ")"), true));
    // Whether we have at least two idle processes.
    boolean hasIdles = count > 1 && processes.get(processes.size() - 2).totalDur < idleCutoffProc;
    processes.forEach(process -> {
      ProcessSummaryTrack summary =
          new ProcessSummaryTrack(data.qe, data.getCpu().count(), process);
      boolean isIdleProcess = hasIdles && (process.totalDur < idleCutoffProc);
      String parent =  isIdleProcess ? "procs_idle" : "procs";
      data.tracks.addGroup(parent, summary.getId(), process.getDisplay(),
          group(state -> new ProcessSummaryPanel(state, summary), false));

      // For each process, add Vulkan memory usage counters if any exist.
      List<CounterInfo> counters = data.getCounters().values().stream()
          .filter(c -> c.type == CounterInfo.Type.Process && c.ref == process.upid &&
              c.count > 0 && c.name.startsWith("vulkan"))
          .collect(toList());
      if (!counters.isEmpty()) {
        String groupId = "vulkan_counters_" + process.upid;
        data.tracks.addLabelGroup(summary.getId(), groupId, "Vulkan Memory Usage",
            group(state -> new TitlePanel("Vulkan Memory Usage"), true));
        for (int i = 0; i < counters.size(); i++) {
          CounterInfo counter = counters.get(i);
          boolean last = i == counters.size() - 1;
          CounterTrack track = new CounterTrack(data.qe, counter);
          data.tracks.addTrack(groupId, track.getId(), counter.name,
              single(state -> new VulkanCounterPanel(state, track), last, false));
        }
      }

      // For each process, add the memory usage panel if it exists.
      ProcessMemoryTrack.enumerate(data, summary.getId(), process.upid);

      // For each process, add any other process counters if any exist.
      counters = data.getCounters().values().stream()
          .filter(c -> c.type == CounterInfo.Type.Process && c.ref == process.upid &&
              c.count > 0 && shouldShowProcessCounter(c))
          .collect(toList());
      if (!counters.isEmpty()) {
        String parentId = summary.getId();
        if (counters.size() > 3) {
          parentId = "proc_counters_" + process.upid;
          data.tracks.addLabelGroup(summary.getId(), parentId, "Process Counters",
              group(state -> new TitlePanel("Process Counters"), false));
        }
        for (int i = 0; i < counters.size(); i++) {
          CounterInfo counter = counters.get(i);
          boolean last = i == counters.size() - 1;
          CounterTrack track = new CounterTrack(data.qe, counter);
          data.tracks.addTrack(parentId, track.getId(), counter.name,
              single(state -> new CounterPanel(
                  state, track, PROCESS_COUNTER_TRACK_HEIGHT), last, false));
        }
      }

      List<AsyncInfo> asyncs = data.getAsyncs().get(process.upid);
      if (!asyncs.isEmpty()) {
        String parentId = summary.getId();
        if (asyncs.size() > 3) {
          parentId = "proc_asyncs_" + process.upid;
          data.tracks.addLabelGroup(summary.getId(), parentId, "Process Async Events",
              group(state -> new TitlePanel("Process Async Events"), false));
        }
        for (int i = 0; i < asyncs.size(); i++) {
          AsyncInfo async = asyncs.get(i);
          boolean last = i == asyncs.size() - 1;
          SliceTrack track = SliceTrack.forAsync(data.qe, async);
          data.tracks.addTrack(parentId, track.getId(), async.name,
              single(state -> new AsyncPanel(state, async, track), last, true));
        }
      }

      List<ThreadTrack> threads = process.utids.stream()
          .map(tid -> data.getThreads().get(tid))
          .filter(Objects::nonNull)
          .sorted((t1, t2) -> Long.compare(t2.totalDur, t1.totalDur))
          .map(t -> new ThreadTrack(data.qe, t))
          .collect(Collectors.toList());
      final long idleCutoffThread =
          Math.min(idleCutoffProc, Math.round(IDLE_PERCENT_CUTOFF * process.totalDur));
      // Whether we have at least two idle threads.
      boolean hasIdleThreads = threads.size() > 1 &&
          threads.get(threads.size() - 2).getThread().totalDur < idleCutoffThread;
      threads.forEach(track -> {
        boolean isIdleThread = hasIdleThreads && track.getThread().totalDur < idleCutoffThread;
        TrackConfig.Track.UiFactory<Panel> ui;
        if (track.getThread().maxDepth == 0) {
          ui = single(state -> new ThreadPanel(state, track, false), false, false);
        } else {
          boolean expanded = !isIdleProcess && !isIdleThread;
          ui = single(state -> new ThreadPanel(state, track, expanded), false,
              ThreadPanel::setExpanded, expanded, false);
        }
        String threadParent = isIdleThread ? summary.getId() + "_idle" : summary.getId();
        data.tracks.addTrack(threadParent, track.getId(), track.getThread().getDisplay(), ui);
      });
      if (hasIdleThreads) {
        int firstIdle = Collections.binarySearch(
            threads, null, (t1, $) -> Long.compare(idleCutoffThread, t1.getThread().totalDur));
        if (firstIdle < 0) {
          firstIdle = -firstIdle - 1;
        } else {
          while (firstIdle > 1 && threads.get(firstIdle - 1).getThread().totalDur == 0) {
            firstIdle--;
          }
        }
        final int idleCount = threads.size() - firstIdle;
        data.tracks.addLabelGroup(summary.getId(), summary.getId() + "_idle", "Idle Threads",
            group(state -> new TitlePanel(idleCount + " Idle Threads (< 0.1%)"), false));
      }
    });

    if (hasIdles) {
      int firstIdle = Collections.binarySearch(
          processes, null, (p1, $) -> Long.compare(idleCutoffProc, p1.totalDur));
      if (firstIdle < 0) {
        firstIdle = -firstIdle - 1;
      } else {
        while (firstIdle > 1 && processes.get(firstIdle - 1).totalDur < idleCutoffProc) {
          firstIdle--;
        }
      }
      final int idleCount = processes.size() - firstIdle;
      data.tracks.addLabelGroup("procs", "procs_idle", "Idle Processes",
          group(state -> new TitlePanel(idleCount + " Idle Processes (< 0.1%)"), false));
    }
    return data;
  }

  private static boolean shouldShowProcessCounter(CounterInfo counter) {
    if (counter.name.startsWith("vulkan")) {
      // Shown in the vulkan memory usage group.
      return false;
    }

    if (counter.name.startsWith("mem.rss.") || counter.name.startsWith("mem.ion.") ||
        "mem.swap".equals(counter.name) ||  "Heap size (KB)".equals(counter.name)) {
      // Memory counters get their own UI.
      return false;
    }

    if (PROC_STATS_COUNTER.contains(counter.name)) {
      // The process_stat counters are too infrequent to be helpful.
      return false;
    }

    if ("VSYNC-app".equals(counter.name)) {
      // VSync has a custom UI.
      return false;
    }

    return true;
  }

  public static Perfetto.Data.Builder enumerateVSync(Perfetto.Data.Builder data) {
    List<CounterInfo> counters = data.getCounters(CounterInfo.Type.Process).get("VSYNC-app");
    if (counters.size() != 1) {
      return data;
    }

    return data.setVSync(new VSync.FromSurfaceFlingerAppCounter(data.qe, counters.get(0)));
  }
}


text:
<!--
  ~
  ~     Copyright (c) 2015-2019 Automation RockStars Ltd.
  ~     All rights reserved. This program and the accompanying materials
  ~     are made available under the terms of the Apache License v2.0
  ~     which accompanies this distribution, and is available at
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~     Contributors:
  ~         Automation RockStars
  ~
  -->

<!DOCTYPE html>
<html>
<head>
    <title>Web IDE</title>
    <script src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script>
    <script src="https://code.angularjs.org/tools/system.js"></script>
    <script src="https://code.angularjs.org/tools/typescript.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/Rx.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/angular2.dev.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/http.min.js"></script>
    <script>
      System.config({
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}}
      });
      System.import('app/boot')
            .then(null, console.error.bind(console));

    </script>
</head>

<body background="grey">
<my-app>Loading...</my-app>
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
module Azure::Labservices::Mgmt::V2018_10_15
  module Models
    #
    # Settings related to creating an environment setting
    #
    class EnvironmentSettingCreationParameters

      include MsRestAzure

      # @return [ResourceSettingCreationParameters] The resource specific
      # settings
      attr_accessor :resource_setting_creation_parameters

      #
      # Mapper for EnvironmentSettingCreationParameters class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'EnvironmentSettingCreationParameters',
          type: {
            name: 'Composite',
            class_name: 'EnvironmentSettingCreationParameters',
            model_properties: {
              resource_setting_creation_parameters: {
                client_side_validation: true,
                required: true,
                serialized_name: 'resourceSettingCreationParameters',
                type: {
                  name: 'Composite',
                  class_name: 'ResourceSettingCreationParameters'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<?php

namespace Fotonica\Http\Requests;

use Fotonica\Http\Requests\Request;

class ServerConfigurationRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'number_generator_status' => 'required|integer'
        ];
    }
}


text:
import { CREATE_ADMINISTOR_INFOMATION } from 'constants/ActionTypes';
let localStorage = window.localStorage;
let localAdminInfo = JSON.parse(localStorage.getItem('adminInfo'));

const initialState = {
  adminInfo: {
    name: '',
    avator: '',
    email: '',
    gender: '',
    campous: '',
    address: '',
    phoneNum: '',
    navigation: []
  }
};

if (localAdminInfo) {
  initialState.adminInfo = localAdminInfo;
};

export function adminInfo(state = initialState, action) {

  switch (action.type) {
    case CREATE_ADMINISTOR_INFOMATION:
      let state = {
        ...state,
        adminInfo: {
          name: action.name,
          avator: action.avator,
          email: action.email,
          gender: action.gender,
          campous: action.campous,
          address: action.address,
          phoneNum: action.phoneNum,
          navigation: action.navigation
        }
      };
      window.localStorage.setItem('adminInfo',JSON.stringify(state.adminInfo));
      return state;
    default:
      return state;
  }
}


text:
export declare class UI {
    /** Shows a basic notification at the top of the page
     * @param message - Message, either single-string or multiline (punctuated by '\n')
     */
    static notify(message: string): any;
    /** Shows a basic error notification at the top of the page
     * @param error - Error object
     */
    static notify(error: Error): any;
    /** Shows a basic notification with a custom title at the top of the page
     * @param title - Title, bolded
     * @param message - Message, either single-string or multiline (punctuated by '\n')
    */
    static notify(title: string, message: string): any;
    /** Shows a basic error notification with a custom title at the top of the page
     * @param title - Title, bolded
     * @param error - Error object
     */
    static notify(title: string, error: Error): any;
    /** Shows a basic error notification, with custom parameters, at the top of the page */
    static notify(error: Error, params: {
        title?: string;
        /** custom message in place of the error text */
        message?: string;
        moreDetailsLabel?: string;
    }): any;
    /** Shows a basic notification at the top of the page, with a background color set based on the type parameter
     * @param title - Title, bolded
     * @param message - Message, either single-string or multiline (punctuated by '\n')
     * @param type - Type, determines the background color of the notification. Acceptable types are:
     *               'default' | 'success' | 'error' | 'warning' | 'severe-warning'
     */
    static notify(title: string, message: string, type: 'default' | 'success' | 'error' | 'warning' | 'severe-warning'): any;
    /** Shows a basic notification at the top of the page, with custom parameters */
    static notify(params: {
        title?: string;
        message: string;
        type?: 'default' | 'success' | 'error' | 'warning' | 'severe-warning';
    }): any;
}


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

#ifndef FLOW_TESTING_MOCK_RASTER_CACHE_H_
#define FLOW_TESTING_MOCK_RASTER_CACHE_H_

#include "flutter/flow/layers/layer.h"
#include "flutter/flow/raster_cache.h"
#include "flutter/flow/testing/mock_layer.h"
#include "flutter/testing/mock_canvas.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkColorType.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkPicture.h"

namespace flutter {
namespace testing {

/**
 * @brief A RasterCacheResult implementation that represents a cached Layer or
 * SkPicture without the overhead of storage.
 *
 * This implementation is used by MockRasterCache only for testing proper usage
 * of the RasterCache in layer unit tests.
 */
class MockRasterCacheResult : public RasterCacheResult {
 public:
  explicit MockRasterCacheResult(SkIRect device_rect);

  void draw(SkCanvas& canvas, const SkPaint* paint = nullptr) const override{};

  SkISize image_dimensions() const override { return device_rect_.size(); };

  int64_t image_bytes() const override {
    return image_dimensions().area() *
           SkColorTypeBytesPerPixel(kBGRA_8888_SkColorType);
  }

 private:
  SkIRect device_rect_;
};

/**
 * @brief A RasterCache implementation that simulates the act of rendering a
 * Layer or SkPicture without the overhead of rasterization or pixel storage.
 * This implementation is used only for testing proper usage of the RasterCache
 * in layer unit tests.
 */
class MockRasterCache : public RasterCache {
 public:
  explicit MockRasterCache(
      size_t access_threshold = 3,
      size_t picture_and_display_list_cache_limit_per_frame =
          kDefaultPictureAndDispLayListCacheLimitPerFrame)
      : RasterCache(access_threshold,
                    picture_and_display_list_cache_limit_per_frame) {}

  std::unique_ptr<RasterCacheResult> RasterizePicture(
      SkPicture* picture,
      GrDirectContext* context,
      const SkMatrix& ctm,
      SkColorSpace* dst_color_space,
      bool checkerboard) const override;

  std::unique_ptr<RasterCacheResult> RasterizeDisplayList(
      DisplayList* display_list,
      GrDirectContext* context,
      const SkMatrix& ctm,
      SkColorSpace* dst_color_space,
      bool checkerboard) const override;

  std::unique_ptr<RasterCacheResult> RasterizeLayer(
      PrerollContext* context,
      Layer* layer,
      RasterCacheLayerStrategy stategy,
      const SkMatrix& ctm,
      bool checkerboard) const override;

  void AddMockLayer(int width, int height);
  void AddMockPicture(int width, int height);

 private:
  MockCanvas mock_canvas_;
  SkColorSpace* color_space_ = mock_canvas_.imageInfo().colorSpace();
  MutatorsStack mutators_stack_;
  FixedRefreshRateStopwatch raster_time_;
  FixedRefreshRateStopwatch ui_time_;
  TextureRegistry texture_registry_;
  PrerollContext preroll_context_ = {
      // clang-format off
      .raster_cache                  = nullptr,
      .gr_context                    = nullptr,
      .view_embedder                 = nullptr,
      .mutators_stack                = mutators_stack_,
      .dst_color_space               = color_space_,
      .cull_rect                     = kGiantRect,
      .surface_needs_readback        = false,
      .raster_time                   = raster_time_,
      .ui_time                       = ui_time_,
      .texture_registry              = texture_registry_,
      .checkerboard_offscreen_layers = false,
      .frame_device_pixel_ratio      = 1.0f,
      .has_platform_view             = false,
      .has_texture_layer             = false,
      // clang-format on
  };
};

struct PrerollContextHolder {
  PrerollContext preroll_context;
  sk_sp<SkColorSpace> srgb;
};

PrerollContextHolder GetSamplePrerollContextHolder();

}  // namespace testing
}  // namespace flutter

#endif  // FLOW_TESTING_MOCK_RASTER_CACHE_H_


text:
namespace Google.Cloud.ContactCenterInsights.V1.Snippets
{
    // [START contactcenterinsights_v1_generated_ContactCenterInsights_CreateAnalysis_async_flattened_resourceNames]
    using Google.Cloud.ContactCenterInsights.V1;
    using Google.LongRunning;
    using System.Threading.Tasks;

    public sealed partial class GeneratedContactCenterInsightsClientSnippets
    {
        /// <summary>Snippet for CreateAnalysisAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task CreateAnalysisResourceNamesAsync()
        {
            // Create client
            ContactCenterInsightsClient contactCenterInsightsClient = await ContactCenterInsightsClient.CreateAsync();
            // Initialize request argument(s)
            ConversationName parent = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]");
            Analysis analysis = new Analysis();
            // Make the request
            Operation<Analysis, CreateAnalysisOperationMetadata> response = await contactCenterInsightsClient.CreateAnalysisAsync(parent, analysis);

            // Poll until the returned long-running operation is complete
            Operation<Analysis, CreateAnalysisOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Analysis result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation<Analysis, CreateAnalysisOperationMetadata> retrievedResponse = await contactCenterInsightsClient.PollOnceCreateAnalysisAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Analysis retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END contactcenterinsights_v1_generated_ContactCenterInsights_CreateAnalysis_async_flattened_resourceNames]
}


text:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { PocketGuard } from './pocket.guard';
import { NewsletterComponent } from './newsletter/newsletter.component';
import { AboutComponent } from "./about/about.component";

const routes: Routes = [
    { path: '',  redirectTo: '/about',  pathMatch: 'full'},
    { path: 'dashboard', component: NewsletterComponent, canActivate: [PocketGuard] },
    { path: 'login', component: LoginComponent },
    { path: 'login/:operation', component: LoginComponent },
    { path: 'about', component: AboutComponent },

];

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true })],
  exports: [RouterModule],
  providers: [PocketGuard]
})
export class PuppyMailRoutingModule { }


text:
<?php

namespace Dlinkgc\Detector;

class MultiuploadDetector implements DetectorInterface
{
    public function getName()
    {
        return 'multiupload';
    }

    public function verify($url)
    {
        if (false !== strpos($url, 'multiupload.com/'))
            return true;
    }

    public function getCrawler()
    {
        return new \Dlinkgc\Crawler\MultiuploadCrawler();
    }
}


text:
namespace Mallos.Input.Dummy
{
    using Mallos.Input.Trackers;

    /// <summary>
    /// Dummy Mouse, does nothing.
    /// </summary>
    public sealed class DummyMouse : IMouse
    {
        /// <inheritdoc />
        public string Name => "Dummy Mouse";

        /// <inheritdoc />
        public IMouseTracker CreateTracker() => new BasicMouseTracker(this);

        /// <inheritdoc />
        public MouseState GetCurrentState() => MouseState.Empty;

        /// <inheritdoc />
        public void GetPosition(out int x, out int y) => y = x = 0;

        /// <inheritdoc />
        public void SetPosition(int x, int y)
        {
        }
    }
}


text:
declare const ResizeMixin: StateMixin<
  {},
  {},
  {},
  {
    contentHeight: number;
    contentWidth: number;
  }
>;

export default ResizeMixin;


text:
package Framework;

import java.util.logging.Level;

/**
 * Created with IntelliJ IDEA.
 * User: Sam
 * Date: 18/10/13
 * Time: 21:19
 */

public final class ReportConfig
{
    public static final int Port = 50505;

    public static final String Host = "localhost";

    public static final Level LogLevel = Level.ALL;

    public static final int TransmissionAttempts = 3;
}


text:
class PagesController < ApplicationController
  def show
    render template: "pages/home"
  end
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejercicio10;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Introducir un numero por teclado que nos diga si es par o impar.
 * @author isaac
 * @version 1.0
 */
public class ejercicio10 {
   public static void main(String[]args) throws IOException {
     System.out.println("Ingrese el numero a calcular : ");
     BufferedReader S = new BufferedReader(new InputStreamReader(System.in));
     int numero = Integer.parseInt(S.readLine());
   if(numero % 2 == 0){
     System.out.println("El numero es par");
   }
   else {
     System.out.println("El numero es impar");
   }
   }
}


text:
Flat-UI colors available in major CSS preprocessor languages

## Available preprocessors
 - [Stylus](http://learnboost.github.io/stylus/)
 - [Sass](http://sass-lang.com) (Including SCSS syntax)
 - [Less](http://lesscss.org)
 - [COD](http://cssondiet.com)

All colors are picked from [flatuicolorpicker.com](http://www.flatuicolorpicker.com) and many thanks to [@vbaimas](https://twitter.com/vbaimas) for creating it.

## Preview

![Color Scheme Preview](http://i.imgur.com/UhUGPTk.png)


text:
from PyQt4.QtGui import QDialog, QVBoxLayout, QDialogButtonBox
from PyQt4.QtCore import QObject, Qt, SIGNAL
from pyduel_gui.widgets import board_select_widget, squad_select_widget
from pyduel_engine.content.engine_states import BoardType

from pyduel_engine.model.engine import Engine

MAX_NUM_PLAYERS = 6

class SetupWidget(QDialog):
    def __init__(self, parent=None):
        super(SetupWidget, self).__init__(parent)
        self.__buildDialog()

    def __buildDialog(self):
        self.boardComboBox = board_select_widget.BoardSelectWidget(BoardType)
        self.squad_selector = squad_select_widget.SquadSelectWidget(
            MAX_NUM_PLAYERS)

        mainVlayout = QVBoxLayout(self)
        mainVlayout.addWidget(self.boardComboBox)
        mainVlayout.addWidget(self.squad_selector)

        # OK and Cancel buttons
        self.buttonBox = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        mainVlayout.addWidget(self.buttonBox)

        QObject.connect(self.buttonBox, SIGNAL("accepted()"), self.accept)
        QObject.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)

    def getEngine(self):
        squads = self.squad_selector.getSquads()
        board = BoardType(self.boardComboBox.getBoard())
        engine = Engine({'squads': squads, 'board_type': board})
        engine.num_players = len(engine.squads)
        return engine

    # static method to create the dialog and return (date, time, accepted)
    def engineSetup(self):
        dialog = SetupWidget(self.parent())
        exec_result = dialog.exec_()
        configured_engine = dialog.getEngine()
        return configured_engine, exec_result == QDialog.Accepted

if __name__ == "__main__":
    import sys
    from PyQt4.QtGui import QApplication
    app = QApplication(sys.argv)
    widget = SetupWidget()
    engine, result = widget.engineSetup()
    print("{} {}".format(engine, result))
    sys.exit(app.exec_())


text:
require 'rails_helper'
describe 'ActiveRecord has_many association queries' do

  context 'joins' do

    it 'can filter a join with a where clause' do
      billable_role = create(:role, billable:true)
      non_billable_role = create(:role, name:'Manager', billable:false)
      @billable_location_1 = create(:location, name:'San Francisco', billable:true)
      @billable_location_2 = create(:location, name:'Chicago', billable:true)

      ['David', 'Kaja', 'Anna'].map {|name| create(:person, name: name, role:billable_role, location: @billable_location_1)}
      ['Devon', 'Danesh', 'Jack'].map {|name| create(:person, name: name, role:non_billable_role, location: @billable_location_2)}

      expect(Location.joins(people: :role).where(roles: { billable:true }).distinct).to match_array(@billable_location_1)

    end

  end
end


text:
<component name="libraryTable">
  <library name="kotlinc.incremental-compilation-impl-tests" type="repository">
    <properties include-transitive-deps="false" maven-id="org.jetbrains.kotlin:incremental-compilation-impl-tests-for-ide:1.8.20-dev-3004" />
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/incremental-compilation-impl-tests-for-ide/1.8.20-dev-3004/incremental-compilation-impl-tests-for-ide-1.8.20-dev-3004.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/incremental-compilation-impl-tests-for-ide/1.8.20-dev-3004/incremental-compilation-impl-tests-for-ide-1.8.20-dev-3004-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
namespace StackExchange.Metrics.Infrastructure
{
    /// <summary>
    /// Well-known names for <see cref="Metadata" />.
    /// </summary>
    public static class MetadataNames
    {
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
        public const string Rate = "rate";
        public const string Unit = "unit";
        public const string Description = "desc";
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
    }
}


text:
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Leave extends StdCommand
{
	public Leave()
	{
	}

	private final String[] access=I(new String[]{"LEAVE"});
	@Override
	public String[] getAccessWords()
	{
		return access;
	}

	@Override
	public boolean execute(final MOB mob, final List<String> commands, final int metaFlags)
		throws java.io.IOException
	{
		final String cmdWord = commands.size()> 0 ? commands.get(0): "";
		final Vector<String> origCmds=new XVector<String>(commands);
		commands.remove(0);
		final Rideable riding=mob.riding();
		if(riding==null)
		{
			if(cmdWord.toUpperCase().startsWith("L"))
			{
				if(commands.size()>0)
				{
					final List<String> subCommands=new XVector<String>(commands);
					final CMObject O = CMLib.english().findCommand(mob, commands);
					if((O instanceof Command)
					&&(CMLib.directions().getDirectionCode(((Command)O).name())>=0))
						return ((Command)O).execute(mob, subCommands, metaFlags);
				}
				else
				{
					final Room R=mob.location();
					if(R!=null)
					{
						int dirToGo=-1;
						for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
						{
							final Room nR=R.getRoomInDir(d);
							final Exit nE=R.getExitInDir(d);
							if((nR!=null)
							&&(nE!=null)
							&&(CMLib.flags().canBeSeenBy(nE, mob))
							&&(nE.isOpen())
							&&((nR.getGridParent() == null) || (nR.getGridParent().roomID().length() > 0)))
							{
								if(dirToGo<0)
									dirToGo=d;
								else
								{
									dirToGo=-1;
									break;
								}
							}
						}
						if(dirToGo>=0)
						{
							final Command C=CMClass.getCommand(CMLib.directions().getDirectionName(dirToGo));
							if(C!=null)
							{
								commands.add(C.getAccessWords()[0]);
								return C.execute(mob, commands, metaFlags);
							}
						}
					}
				}
				CMLib.commands().postCommandFail(mob,origCmds,L("Which way? Try EXITS."));
				return false;
			}
			else
			{
				CMLib.commands().postCommandFail(mob,origCmds,L("But you aren't inside anything?!"));
				return false;
			}
		}
		final Room R=mob.location();
		if(R!=null)
		{
			final CMMsg msg=CMClass.getMsg(mob,riding,null,CMMsg.MSG_DISMOUNT,L("<S-NAME> @x1 <T-NAMESELF>.",riding.dismountString(mob)));
			if(R.okMessage(mob,msg))
				R.send(mob,msg);
		}
		return false;
	}

	@Override
	public double combatActionsCost(final MOB mob, final List<String> cmds)
	{
		return CMProps.getCommandCombatActionCost(ID());
	}

	@Override
	public double actionsCost(final MOB mob, final List<String> cmds)
	{
		return CMProps.getCommandActionCost(ID());
	}

	@Override
	public boolean canBeOrdered()
	{
		return true;
	}

}


text:
#import "GRSCProviderUtils.h"

// Provider error defaults.
static const int kProviderErrorCode = -1;
static NSString *const kGRSCErrorDomain = @"GRSCErrorDomain";

// Provider URL Strings.
static NSString *const kGRSCBaseProviderURLString = @"http://localhost:8080";

// Error descriptions.
NSString *const kGRSCUnexpectedJSONClassTypeErrorDescription =
    @"Unexpected class type for JSON response.";
NSString *const kGRSCInvalidRequestURLDescription = @"Invalid request URL.";

NSError *GRSCError(NSString *description) {
  NSDictionary<NSErrorUserInfoKey, NSString *> *userInfo = @{
    NSLocalizedDescriptionKey : description,
  };
  return [NSError errorWithDomain:kGRSCErrorDomain code:kProviderErrorCode userInfo:userInfo];
}

NSURL *GRSCProviderURLWithPath(NSString *path) {
  NSURL *baseProviderNSURL = [NSURL URLWithString:kGRSCBaseProviderURLString];
  return [NSURL URLWithString:path relativeToURL:baseProviderNSURL];
}

GRSCProviderFieldsDictionary *GRSCGetDictionaryFromJSONData(NSData *data, NSError **error) {
  NSError *JSONParseError;
  id JSONDictionary = [NSJSONSerialization JSONObjectWithData:data
                                                      options:kNilOptions
                                                        error:&JSONParseError];
  NSError *errorToPropagate;
  if (JSONParseError) {
    errorToPropagate = JSONParseError;
  } else if (![JSONDictionary isKindOfClass:[NSDictionary class]]) {
    errorToPropagate = GRSCError(kGRSCUnexpectedJSONClassTypeErrorDescription);
  } else {
    return (GRSCProviderFieldsDictionary *)JSONDictionary;
  }

  if (error) {
    *error = errorToPropagate;
  }
  return nil;
}


text:
.yui-skin-sam .qryTemporalConstraint .yuimenu .bd {
	width:300px;
}

DIV#crcQueryToolBox {
	position: absolute;
	width: 534px;
}

DIV#crcQueryToolBox DIV.tabBox {}
DIV#crcQueryToolBox DIV.tabBox DIV {}

DIV#crcQueryToolBox DIV.tabBox.active {}
DIV#crcQueryToolBox DIV.tabBox.active DIV {}

DIV#crcQueryToolBox DIV.bodyBox {
	background:#BBCCEE none repeat scroll 0%;
	border:1px solid #667788;
	width:auto;
	height:auto;
	padding: 5px 5px 0px;
	white-space:nowrap;
	overflow:hidden;
	position:absolute;
	xtop:-1px;
	top:25px;
	clear: both;
	z-index:0;
}

DIV#crcQueryToolBox DIV.queryNameBar {
	background:#BBCCEE none repeat scroll 0%;
	border-bottom:1px solid #667788;
	overflow:hidden;
	padding: 2px 5px 5px;
	margin: 0px -5px 5px;
	width: auto;
}

DIV#crcQueryToolBox DIV.queryLabel {
	font-size:12px;
	height:15px;
	line-height:15px;
	overflow:hidden;
	float:left;

	xposition:absolute;
	xz-index:99999;
}

DIV#crcQueryToolBox DIV#queryName {
	background-color:#CBD8EF;
	border:1px solid #63758C;
	color:#4C5676;
	font-size:11px;
	height:15px;
	line-height:15px;
	overflow:hidden;
	padding:0pt 5px;
	white-space:nowrap;
	width:auto;
}

DIV#crcQueryToolBox DIV.crcQryToolPanels {
	height:auto;
}

DIV#crcQueryToolBox DIV.qryPanel {
	width:168px;
	float: left;
	margin: 1px;
	padding: 0px 0px 2px 0px;
}

DIV#crcQueryToolBox DIV.qryPanelTitle {
	text-align:center;
	background:#6677AA none repeat scroll 0%;
	border:1px solid #667788;
	color:#FFFFFF;
	font-size:11px;
	font-weight:bold;
	height:13px;
	line-height:12px;
	overflow:hidden;
	width:166px;
	float:left;
}

DIV#crcQueryToolBox DIV.qryPanelClear {
	float:right;
	margin:1px;
}

DIV#crcQueryToolBox DIV.queryPanel {
	background:#FFFFFF;
	border:1px solid #667788;
	padding:3px;
	white-space:nowrap;
	overflow:auto;
	width:160px;
	float: left;
}

DIV#crcQueryToolBox DIV.qryPanelButtonBar {
	float:left;
	margin: 0px 0px -1px 0px;
}
DIV#crcQueryToolBox DIV.qryPanelButtonBar DIV {
	background:#CBD8EF none repeat scroll 0%;
	border:1px solid #667788;
	height:16px;
	line-height:16px;
	text-align:center;
	float:left;
}

DIV#crcQueryToolBox DIV.qryButtonDate 	 {width:38px;}
DIV#crcQueryToolBox DIV.qryButtonOccurs  {width:80px; margin:0px -1px;}
DIV#crcQueryToolBox DIV.qryButtonExclude {width:46px;}
DIV#crcQueryToolBox DIV.qryPanelTiming   {width:166px;text-align:center;}

DIV#crcQueryToolBox DIV.qryPanelTiming .yuimenuitemlabel {width:120px;}

DIV#crcQueryToolBox DIV.qryPanelTiming Button {
line-height:1;
width:160px;
min-height:1em;
}

DIV#crcQueryToolBox DIV.qryTemporalConstraint   {width:300px;text-align:center;}

DIV#crcQueryToolBox DIV.qryTemporalConstraint .yuimenuitemlabel {width:200px;}

DIV#crcQueryToolBox DIV.qryTemporalConstraint Button {
line-height:1;
width:300px;
min-height:1em;
}
DIV#crcQueryToolBox DIV#qryToolFooter {
	border-top:1px solid #667788;
	clear:both;
	margin:0px -5px -2px -5px;
	padding: 5px;
	position:relative;
	width:auto;
	height:20px;
	overflow:hidden;
}

DIV#crcQueryToolBox DIV#newBox,
DIV#crcQueryToolBox DIV#printQueryBox,
DIV#crcQueryToolBox DIV#runBox {
	position:relative;
	xdisplay:none;
	background:#6677AA;
	border:1px solid #667788;
	color:#FFFFFF;
	font-weight:bold;
	font-family:arial,helvetica;
	font-size:11px;
	height:16px;
	line-height:16px;
	text-align:center;
	color:#FFF;
	cursor:pointer;
	float: left;
	margin:0px 5px 0px 0px;
	width:72px;
	xz-index:5;
	overflow:hidden;
}

DIV#crcQueryToolBox DIV#newBox a,
DIV#crcQueryToolBox DIV#printQueryBox a,
DIV#crcQueryToolBox DIV#runBox a {
	color:#FFF;
	display:block;
	text-decoration:none;
}

a.topicButton {
	color:#FFF;
	display:block;
	text-decoration:none;
	display: inline;
	background:#6677AA;
	border:1px solid #667788;
	color:#FFFFFF;
	font-weight:bold;
	font-family:arial,helvetica;
	font-size:11px;
	height:18px;
	line-height:18px;
	text-align:center;
	color:#FFF;
	cursor:pointer;
	padding: 2px 11px;
}
a.topicButton:hover {
	background-color:#7687bf;
}

DIV#crcQueryToolBox DIV#newBox a:hover,
DIV#crcQueryToolBox DIV#printQueryBox a:hover,
DIV#crcQueryToolBox DIV#runBox a:hover {
	background-color:#7687bf;
}

DIV#crcQueryToolBox DIV#groupCount {
	height:16px;
	width:165px;
	line-height:16px;
	position:relative;
	text-align:center;
	float:left;
	overflow:hidden;
}

DIV#crcQueryToolBox DIV#queryBottom {
	position:relative;
	height:20px;
	border-top:1px solid #667788;
	width:100%;
}
DIV#crcQueryToolBox DIV#scrollBox {
	position:relative;
	overflow:hidden;
	float:right;
	z-index:5;
}

DIV#crcQueryToolBox DIV#queryBalloonBox {
	bottom:80px;
	height:30px;
	padding:37px 0px 37px 50px;
	position:absolute;
	width:100%;
	z-index:10;
}
DIV#crcQueryToolBox DIV.queryBalloon {
	background:#FFFF99;
	border:1px solid #667788;
	width:70px;
	height:40px;
	color:#000000;
	font-size:12px;
	font-weight:bold;
	text-align:center;
	line-height:13px;
	float:left;
	display:none;
}
DIV#crcQueryToolBox DIV.queryBalloonAnd {
	background:#6677AA;
	border:1px solid #667788;
	width:45px;
	height:20px;
	color:#FFFFFF;
	font-size:14px;
	font-weight:bold;
	text-align:center;
	line-height:20px;
	float:left;
	margin:10px 27px;
	display:none;
}


text:
<?php

/**
 * Global Configuration Override
 *
 * You can use this file for overriding configuration values from modules, etc.
 * You would place values in here that are agnostic to the environment and not
 * sensitive to security.
 *
 * @NOTE: In practice, this file will typically be INCLUDED in your source
 * control, so do not include passwords or other sensitive information in this
 * file.
 */
return array(
    'mail' => array(
        'name' => 'smtp.google.com',
        'host' => 'smtp.google.com',
        'connection_class' => 'login',
        'connection_config' => array(
            'username' => 'alexcomput@gmail.com',
            'password' => '123',
            'ssl' => 'tls',
            'port' => 465,
            'from' => 'alexcomput@gmail.com'
        )
    )
);


text:
RSpec.describe Person do
  include SearchApiHelpers

  let(:api_data) do
    {
      "base_path" => "/government/people/boris-johnson",
      "links" => {
        "role_appointments" => [
          {
            "links" => {
              "role" => [{
                "title" => "Prime Minister",
              }],
            },
            "details" => {
              "current" => true,
              "person_appointment_order" => 1,
            },
          },
          {
            "links" => {
              "role" => [{
                "title" => "First Lord of the Treasury",
              }],
            },
            "details" => {
              "current" => true,
              "person_appointment_order" => 2,
            },
          },
          {
            "links" => {
              "role" => [
                {
                  "title" => "Secretary of State for Foreign and Commonwealth Affairs",
                },
              ],
            },
            "details" => {
              "current" => false,
              "person_appointment_order" => 3,
              "started_on" => "2016-07-13T00:00:00+01:00",
              "ended_on" => "2018-07-09T00:00:00+01:00",
            },
          },
        ],
      },
    }
  end
  let(:content_item) { ContentItem.new(api_data) }
  let(:person) { described_class.new(content_item) }

  describe "current_roles_title" do
    it "combines the titles into a sentence" do
      expect(person.current_roles_title).to eq("Prime Minister and First Lord of the Treasury")
    end

    it "combines the titles into a sentence for translated content" do
      api_data["locale"] = "ar"
      api_data["links"]["role_appointments"].first["links"]["role"].first["title"] = "المفوض التجاري لصاحب الجلالة لمنطقة الشرق الأوسط"
      api_data["links"]["role_appointments"].second["links"]["role"].first["title"] = "القنصل العام لصاحب الجلالة في دبي"
      # Arabic letter 'و' == 'and'
      expect(person.current_roles_title).to eq("المفوض التجاري لصاحب الجلالة لمنطقة الشرق الأوسط و القنصل العام لصاحب الجلالة في دبي")
    end
  end

  describe "currently_in_a_role?" do
    it "returns true if the person has a current role appointment" do
      expect(person.currently_in_a_role?).to be(true)
    end

    it "returns false if the person doesn't have a current role appointment" do
      api_data["links"]["role_appointments"][0]["details"]["current"] = false
      api_data["links"]["role_appointments"][1]["details"]["current"] = false
      expect(person.currently_in_a_role?).to be(false)
    end
  end

  describe "ordered previous appointments" do
    it "should have previous appointment text" do
      text = person.previous_roles_items.first[:link][:text]

      expect(text).to eq("Secretary of State for Foreign and Commonwealth Affairs")
    end

    it "should have previous appointment duration text" do
      duration = person.previous_roles_items.first[:metadata][:appointment_duration]
      expect(duration).to eq("2016 to 2018")
    end
  end

  describe "announcements" do
    before do
      results = [
        { "title" => "Government announces further support for those affected by flooding",
          "link" => "/government/news/government-announces-further-support-for-those-affected-by-flooding",
          "content_store_document_type" => "press_release",
          "public_timestamp" => "2019-11-12T21:07:00.000+00:00",
          "index" => "government",
          "es_score" => nil,
          "_id" => "/government/news/government-announces-further-support-for-those-affected-by-flooding",
          "elasticsearch_type" => "edition",
          "document_type" => "edition" },
      ]

      body = {
        "results" => results,
        "start" => 0,
        "total" => 1,
      }

      stub_search(body: body)
    end

    it "should have announcements" do
      text = person.announcements.items.first[:link][:text]
      expect(text).to eq("Government announces further support for those affected by flooding")
    end

    it "should have link to news and communications finder" do
      link = person.announcements.links[:link_to_news_and_communications]
      expect(link).to eq("/search/news-and-communications?people=boris-johnson")
    end

    it "should have link to email signup" do
      link = person.announcements.links[:email_signup]
      expect(link).to eq("/email-signup?link=/government/people/boris-johnson")
    end

    it "should have link to subscription atom feed" do
      link = person.announcements.links[:subscribe_to_feed]
      expect(link).to eq("/search/news-and-communications.atom?people=boris-johnson")
    end
  end
end


text:
package org.hillview.targets;

import it.unimi.dsi.fastutil.ints.IntArrayList;
import org.hillview.*;
import org.hillview.dataStructures.*;
import org.hillview.sketches.highorder.ConcurrentPostprocessedSketch;
import org.hillview.sketches.highorder.PostProcessedSketch;
import org.hillview.dataset.api.IDataSet;
import org.hillview.dataset.api.ISketch;
import org.hillview.maps.highorder.IdMap;
import org.hillview.sketches.PrecomputedSketch;
import org.hillview.sketches.results.*;
import org.hillview.storage.jdbc.JdbcConnectionInformation;
import org.hillview.table.ColumnDescription;
import org.hillview.table.PrivacySchema;
import org.hillview.table.SmallTable;
import org.hillview.table.api.ITable;
import org.hillview.table.columns.ColumnQuantization;
import org.hillview.table.filters.RangeFilterArrayDescription;
import org.hillview.table.filters.RangeFilterDescription;
import org.hillview.utils.*;

import java.sql.SQLException;

public class PrivateSimpleDBTarget extends SimpleDBTarget implements IPrivateDataset {
    static final long serialVersionUID = 1;

    // This class inherits columnLimits from SimpleDBTarget and it has another one
    // in the wrapper.  We only use the one in the wrapper.
    private final DPWrapper wrapper;

    PrivateSimpleDBTarget(JdbcConnectionInformation conn, HillviewComputation c,
                          PrivacySchema privacySchema, String schemaFilename) throws SQLException {
        super(conn, c, schemaFilename);
        this.wrapper = new DPWrapper(privacySchema, schemaFilename);
        this.database.connect();
    }

    private PrivateSimpleDBTarget(PrivateSimpleDBTarget other, HillviewComputation computation) throws SQLException {
        super(other.jdbc, computation, other.metadataDirectory);
        this.wrapper = new DPWrapper(other.wrapper);
        this.database.connect();
    }

    private PrivacySchema getPrivacySchema() {
        return this.wrapper.getPrivacySchema();
    }

    @HillviewRpc
    public void changePrivacy(RpcRequest request, RpcRequestContext context) {
        this.wrapper.setPrivacySchema(request.parseArgs(PrivacySchema.class));
        HillviewLogger.instance.info("Updated privacy schema");
        this.returnResult(new JsonInString("{}"), request, context);
    }

    @HillviewRpc
    public void getMetadata(RpcRequest request, RpcRequestContext context) {
        GeoFileInformation[] info = this.getGeoFileInformation();
        TableSummary summary = new TableSummary(this.schema, this.rowCount);
        PostProcessedSketch<ITable, TableSummary, DPWrapper.TableMetadata> post =
            new PrecomputedSketch<ITable, TableSummary>(summary).andThen(
                    s -> new TableMetadata(s, info)).andThen(
                            PrivateSimpleDBTarget.this.wrapper::addPrivateMetadata);
        this.runCompleteSketch(this.table, post, request, context);
    }

    @Override
    public String toString() {
        return "Private local database: " + this.jdbc.toString();
    }

    @HillviewRpc
    public void getDataQuantiles(RpcRequest request, RpcRequestContext context) {
        this.wrapper.getDataQuantiles(request, context, this);
    }

    @HillviewRpc
    public void histogramAndCDF(RpcRequest request, RpcRequestContext context) throws SQLException {
        HistogramRequestInfo info = request.parseArgs(HistogramRequestInfo.class);
        assert info.size() == 2;

        ColumnDescription cd = info.histos[0].cd;  // both args should be on the same column
        ColumnQuantization quantization = this.getPrivacySchema().quantization(cd.name);
        double epsilon = this.getPrivacySchema().epsilon(cd.name);
        if (quantization == null)
            throw new RuntimeException("No quantization information for column " + cd.name);

        IntervalDecomposition d0 = info.getDecomposition(0, quantization);
        IntervalDecomposition d1 = info.getDecomposition(1, quantization);
        JsonGroups<Count> histo = this.database.histogram(
                cd, info.getBuckets(0, quantization), this.wrapper.columnLimits, quantization, this.rowCount);
        JsonGroups<Count> cdf = this.database.histogram(
                cd, info.getBuckets(1, quantization), this.wrapper.columnLimits, quantization, this.rowCount);
        ISketch<ITable, JsonGroups<Count>> preHisto = new PrecomputedSketch<>(histo);
        ISketch<ITable, JsonGroups<Count>> preCdf = new PrecomputedSketch<>(cdf);
        int colIindex = this.wrapper.getColumnIndex(cd.name);
        DPHistogram<JsonGroups<Count>> privateHisto = new DPHistogram<>(preHisto, colIindex, d0, epsilon, false, this.wrapper.laplace);
        DPHistogram<JsonGroups<Count>> privateCdf = new DPHistogram<>(preCdf, colIindex, d1, epsilon, true, this.wrapper.laplace);
        ConcurrentPostprocessedSketch<ITable, JsonGroups<Count>, JsonGroups<Count>, Two<JsonGroups<Count>>, Two<JsonGroups<Count>>> cc =
                new ConcurrentPostprocessedSketch<>(privateHisto, privateCdf);
        this.runCompleteSketch(this.table, cc, request, context);
    }

    @HillviewRpc
    public void filterRanges(RpcRequest request, RpcRequestContext context) {
        RangeFilterArrayDescription filter = request.parseArgs(RangeFilterArrayDescription.class);
        if (filter.complement)
            throw new HillviewException("Only filters on contiguous range are supported");
        IdMap<ITable> map = new IdMap<ITable>();
        this.runMap(this.table, map, (e, c) -> {
            try {
                IPrivateDataset result = new PrivateSimpleDBTarget(this, c);
                for (RangeFilterDescription f: filter.filters)
                     result.getWrapper().filter(f);
                return result;
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        }, request, context);
    }

    @HillviewRpc
    public void hLogLog(RpcRequest request, RpcRequestContext context) {
        DistinctCountRequestInfo col = request.parseArgs(DistinctCountRequestInfo.class);
        int result = this.database.distinctCount(col.columnName, this.wrapper.columnLimits);
        double epsilon = this.wrapper.getPrivacySchema().epsilon(col.columnName);
        Noise noise = DPWrapper.computeCountNoise(this.wrapper.getColumnIndex(col.columnName),
                DPWrapper.SpecialBucket.DistinctCount, epsilon, this.wrapper.laplace);
        CountWithConfidence dc = new CountWithConfidence(result).add(noise);
        this.returnResult(dc, request, context);
    }

    @HillviewRpc
    public void histogram2D(RpcRequest request, RpcRequestContext context) throws SQLException {
        HistogramRequestInfo info = request.parseArgs(HistogramRequestInfo.class);
        assert info.size() == 2;
        JsonGroups<JsonGroups<Count>> heatmap = this.database.histogram2D(
                info.histos[0].cd, info.histos[1].cd,
                info.getBuckets(0), info.getBuckets(1),
                this.wrapper.columnLimits,
                null, null);
        double epsilon = this.getPrivacySchema().epsilon(
                info.histos[0].cd.name, info.histos[1].cd.name);
        ColumnQuantization q0 = this.getPrivacySchema().quantization(info.histos[0].cd.name);
        ColumnQuantization q1 = this.getPrivacySchema().quantization(info.histos[1].cd.name);
        Converters.checkNull(q0);
        Converters.checkNull(q1);
        IntervalDecomposition d0 = info.getDecomposition(0, q0);
        IntervalDecomposition d1 = info.getDecomposition(1, q1);
        ISketch<ITable, JsonGroups<JsonGroups<Count>>> sk = new PrecomputedSketch<>(heatmap);
        DPHeatmapSketch<JsonGroups<Count>, JsonGroups<JsonGroups<Count>>> noisyHeatmap =
                new DPHeatmapSketch<>(
                sk, this.wrapper.getColumnIndex(info.histos[0].cd.name, info.histos[1].cd.name),
                d0, d1, epsilon, this.wrapper.laplace);
        this.runSketch(this.table, noisyHeatmap, request, context);
    }

    @HillviewRpc
    public void getNextK(RpcRequest request, RpcRequestContext context) {
        TableTarget.NextKArgs nextKArgs = request.parseArgs(TableTarget.NextKArgs.class);
        // Only allow this if the sort order is empty
        if (nextKArgs.order.getSize() != 0)
            throw new HillviewException("No column data can be displayed privately");
        NextKList result = new NextKList(new SmallTable(nextKArgs.order.toSchema()),
            null, new IntArrayList(), 0, 0);
        this.returnResult(result, request, context);
    }

    @Override
    public IDataSet<ITable> getDataset() {
        return this.table;
    }

    @Override
    public DPWrapper getWrapper() {
        return this.wrapper;
    }
}


text:
package org.mockito.internal.stubbing.defaultanswers;

import static org.mockito.internal.exceptions.Reporter.smartNullPointerException;
import static org.mockito.internal.util.ObjectMethodsGuru.isToStringMethod;

import java.io.Serializable;
import java.lang.reflect.Modifier;

import org.mockito.Mockito;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.invocation.Location;
import org.mockito.stubbing.Answer;

/**
 * Optional Answer that can be used with
 * {@link Mockito#mock(Class, Answer)}
 *

 * This implementation can be helpful when working with legacy code. Unstubbed
 * methods often return null. If your code uses the object returned by an
 * unstubbed call you get a NullPointerException. This implementation of
 * Answer returns SmartNulls instead of nulls.
 * SmartNull gives nicer exception message than NPE because it points out the
 * line where unstubbed method was called. You just click on the stack trace.
 *

 * ReturnsSmartNulls first tries to return ordinary return values (see
 * {@link ReturnsMoreEmptyValues}) then it tries to return SmartNull. If the
 * return type is not mockable (e.g. final) then ordinary null is returned.
 *

 * ReturnsSmartNulls will be probably the default return values strategy in
 * Mockito 2.1.0
 */
public class ReturnsSmartNulls implements Answer<Object>, Serializable {

    private static final long serialVersionUID = 7618312406617949441L;

    private final Answer<Object> delegate = new ReturnsMoreEmptyValues();

    public Object answer(final InvocationOnMock invocation) throws Throwable {
        Object defaultReturnValue = delegate.answer(invocation);
        if (defaultReturnValue != null) {
            return defaultReturnValue;
        }
        Class<?> type = invocation.getMethod().getReturnType();
        if (!type.isPrimitive() && !Modifier.isFinal(type.getModifiers())) {
            final Location location = new LocationImpl();
            return Mockito.mock(type, new ThrowsSmartNullPointer(invocation, location));
        }
        return null;
    }

    private static class ThrowsSmartNullPointer implements Answer {
        private final InvocationOnMock unstubbedInvocation;
        private final Location location;

        public ThrowsSmartNullPointer(InvocationOnMock unstubbedInvocation, Location location) {
            this.unstubbedInvocation = unstubbedInvocation;
            this.location = location;
        }

        public Object answer(InvocationOnMock currentInvocation) throws Throwable {
            if (isToStringMethod(currentInvocation.getMethod())) {
                return "SmartNull returned by this unstubbed method call on a mock:\n" +
                        unstubbedInvocation.toString();
            }

            throw smartNullPointerException(unstubbedInvocation.toString(), location);
        }
    }
}


text:
package com.accenture.nes.webservices;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
import com.accenture.nes.dto.webservicedto.ivr.GetTaskDetailRequestDTO;
import com.accenture.nes.webservicedto.ivr.GetTaskDetailResponceDTO;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.6 in JDK 6
 * Generated source version: 2.1
 *
 */
@WebService(name = "IIVRTaskManagementService", targetNamespace = "http://webservices.nes.accenture.com/")
@XmlSeeAlso({
    com.accenture.nes.webservices.ObjectFactory.class,
    com.accenture.nes.dto.webservicedto.ivr.ObjectFactory.class,
    com.accenture.nes.util.ObjectFactory.class,
    com.accenture.nes.webservicedto.ivr.ObjectFactory.class
})
public interface IIVRTaskManagementService {

    /**
     *
     * @param getTaskDetailRequestDTO
     * @return
     *     returns com.accenture.nes.webservicedto.ivr.GetTaskDetailResponceDTO
     */
    @WebMethod(operationName = "GetTaskDetails", action = "urn:GetTaskDetails")
    @WebResult(targetNamespace = "")
    @RequestWrapper(localName = "GetTaskDetails", targetNamespace = "http://webservices.nes.accenture.com/", className = "com.accenture.nes.webservices.GetTaskDetails")
    @ResponseWrapper(localName = "GetTaskDetailsResponse", targetNamespace = "http://webservices.nes.accenture.com/", className = "com.accenture.nes.webservices.GetTaskDetailsResponse")
    public GetTaskDetailResponceDTO getTaskDetails(
        @WebParam(name = "getTaskDetailRequestDTO", targetNamespace = "")
        GetTaskDetailRequestDTO getTaskDetailRequestDTO);

}


text:
title: Cookies
layout: page
css-id: cookies
cabezote: /img/cabezote.jpg
---

Para hacer un análisis de los usuarios que visitan este sitio, estamos usando Google Analytics que instala en los dispositivos de los usuarios pequeños ficheros de datos, conocidos como cookies.

### ¿Qué son las cookies?

Una cookie es un pequeño fichero de texto que los sitios web instalan en el ordenador o el dispositivo móvil de los usuarios que los visitan. Las cookies hacen posible que el sitio web recuerde las acciones y preferencias del usuario (identificador de inicio de sesión, idioma, tamaño de letra y otras preferencias de visualización), para que este no tenga que volver a configurarlos cuando regrese al sitio o navegue por sus páginas.

### ¿Cómo utilizamos las cookies?

Utilizamos cookies para:

- Saber si ha visitado este sitio
- Si ha dado o no su consentimiento para que utilicemos cookies en nuestra web.

Aunque las cookies no son imprescindibles para que el sitio web funcione, si las habilita disfrutará de una mejor experiencia de navegación. Puede borrar o bloquear las cookies.

La información asociada a las cookies no se utiliza para identificar personalmente al usuario. Además, mantenemos plenamente bajo nuestro control los datos sobre sus patrones de navegación. Estas cookies se utilizan exclusivamente para los fines aquí indicados.

### Cómo controlar las cookies

Usted puede controlar o borrar las cookies siempre que lo desee: para más información, consulte aboutcookies.org. Además de poder eliminar todas las cookies que ya se encuentran en su ordenador, también puede configurar la mayoría de los navegadores para que dejen de aceptarlas. Pero tenga presente que, si rechaza las cookies, es posible que tenga que volver a configurar manualmente sus preferencias cada vez que visite un sitio y que dejen de funcionar determinados servicios y funcionalidades.


text:
require 'maruku'

class LearningLesson < DomainModel

  belongs_to :learning_module
  belongs_to :learning_section
  acts_as_list :scope => :learning_section_id

  belongs_to :media_file, :class_name => 'DomainFile'
  belongs_to :image_file, :class_name => 'DomainFile'

  serialize :data

  def before_create
    self.position = self.class.maximum(:position, :conditions => { :learning_section_id => self.learning_section_id }).to_i + 1
  end

  def before_save
    generate_content_html
    generate_email_html
  end

  def image_list_arr
    self.image_list.to_s.split(",").select { |elm| !elm.blank? }
  end

  def generate_content_html
     begin ## Throw away
       txt = self.image_substitute(self.content)
      self.content_html = Maruku.new(txt).to_html
    rescue
      self.content_html = 'Invalid Markdown'.t
    end
  end

  def generate_email_html
     begin ## Throw away
      txt = self.image_substitute(self.email_content)
      self.email_content_html = Maruku.new(txt).to_html
    rescue
      self.email_content_html = 'Invalid Markdown'.t
    end
  end

  def image_substitute(content)
    html = content.gsub(/\!\[([^\]]+)\]\(([^"')]+)/) do |mtch|
      alt_text = $1
      full_url = $2
      image_path,size = full_url.strip.split("::")
      if image_path =~ /^http(s|)\:\/\//
        url = full_url
      else
        df = DomainFile.find_by_file_path("/" + image_path)
        url = Configuration.domain_link(df ? df.url(size) : "/images/spacer.gif")
      end
      "![#{alt_text}](#{url}"
    end
  end

  def options
    self.data ||= {}
  end

  def goals
    options[:goals] || []
  end

  def goals=(val)
    options[:goals] = val
  end

end


text:
namespace tupleware {
class Tuple {
public:
    Schema *schema() {
        return m_sch;
    }

    virtual double getDouble(int attrNum) = 0;
    virtual float getFloat(int attrNum) = 0;
    virtual int getInt(int attrNum) = 0;
    virtual char *getString(int attrNum) = 0;
    virtual void setDouble(int attrNum, double val) = 0;
    virtual void setFloat(int attrNum, float val) = 0;
    virtual void setInt(int attrNum, int val) = 0;
    virtual void setString(int attrNum, char *val) = 0;
protected:
    Schema *m_sch;

    Tuple(Schema *sch) {
        m_sch = sch;
    }
};
}
#endif


text:
<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * appProdUrlMatcher
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class appProdUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function match($pathinfo)
    {
        $allow = array();
        $pathinfo = rawurldecode($pathinfo);
        $context = $this->context;
        $request = $this->request;

        // jmpc_pet_friends_protectors_homepage
        if (rtrim($pathinfo, '/') === '') {
            if (substr($pathinfo, -1) !== '/') {
                return $this->redirect($pathinfo.'/', 'jmpc_pet_friends_protectors_homepage');
            }

            return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::indexAction',  '_route' => 'jmpc_pet_friends_protectors_homepage',);
        }

        // jmpc_pet_friends_protectors_new
        if ($pathinfo === '/nuevo') {
            return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::newAction',  '_route' => 'jmpc_pet_friends_protectors_new',);
        }

        // jmpc_pet_friends_protectors_delete
        if (0 === strpos($pathinfo, '/borrar') && preg_match('#^/borrar/(?P<id>\\d+)/(?P<slug>[^/]++)$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'jmpc_pet_friends_protectors_delete')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::deleteAction',));
        }

        // jmpc_pet_friends_protectors_edit
        if (0 === strpos($pathinfo, '/editar') && preg_match('#^/editar/(?P<id>\\d+)/(?P<slug>[^/]++)$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'jmpc_pet_friends_protectors_edit')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::editAction',));
        }

        // jmpc_pet_friends_protectors_about
        if ($pathinfo === '/sobre') {
            return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::aboutAction',  '_route' => 'jmpc_pet_friends_protectors_about',);
        }

        // jmpc_pet_friends_protectors_contact
        if ($pathinfo === '/contacto') {
            return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::contactAction',  '_route' => 'jmpc_pet_friends_protectors_contact',);
        }

        // jmpc_pet_friends_protectors_adopteds
        if ($pathinfo === '/adoptados') {
            return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AnimalsController::adoptedAction',  '_route' => 'jmpc_pet_friends_protectors_adopteds',);
        }

        // jmpc_pet_friends_protectors_list
        if (preg_match('#^/(?P<id>\\d+)/(?P<slug>[^/]++)$#s', $pathinfo, $matches)) {
            if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                $allow = array_merge($allow, array('GET', 'HEAD'));
                goto not_jmpc_pet_friends_protectors_list;
            }

            return $this->mergeDefaults(array_replace($matches, array('_route' => 'jmpc_pet_friends_protectors_list')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::listAction',));
        }
        not_jmpc_pet_friends_protectors_list:

        // jmpc_pet_friends_protectors_comment_create
        if (0 === strpos($pathinfo, '/comentario') && preg_match('#^/comentario/(?P<post_id>\\d+)$#s', $pathinfo, $matches)) {
            if ($this->context->getMethod() != 'POST') {
                $allow[] = 'POST';
                goto not_jmpc_pet_friends_protectors_comment_create;
            }

            return $this->mergeDefaults(array_replace($matches, array('_route' => 'jmpc_pet_friends_protectors_comment_create')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\CommentsController::createAction',));
        }
        not_jmpc_pet_friends_protectors_comment_create:

        if (0 === strpos($pathinfo, '/animales')) {
            // jmpc_pet_friends_protectors_animals_new
            if ($pathinfo === '/animales/nuevo') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AnimalsController::newAction',  '_route' => 'jmpc_pet_friends_protectors_animals_new',);
            }

            // jmpc_pet_friends_protectors_animals_delete
            if (0 === strpos($pathinfo, '/animales/borrar') && preg_match('#^/animales/borrar/(?P<id>\\d+)/(?P<slug>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'jmpc_pet_friends_protectors_animals_delete')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AnimalsController::deleteAction',));
            }

            // jmpc_pet_friends_protectors_animals_edit
            if (0 === strpos($pathinfo, '/animales/editar') && preg_match('#^/animales/editar/(?P<id>\\d+)/(?P<slug>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'jmpc_pet_friends_protectors_animals_edit')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AnimalsController::editAction',));
            }

            // jmpc_pet_friends_protectors_animals_list
            if (preg_match('#^/animales(?:/(?P<tipo>[^/]++))?$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'jmpc_pet_friends_protectors_animals_list')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AnimalsController::listAction',  'tipo' => 'listado',));
            }

            // jmpc_pet_friends_protectors_animals_dogs
            if ($pathinfo === '/animales/perros') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AnimalsController::listAction',  '_route' => 'jmpc_pet_friends_protectors_animals_dogs',);
            }

            // jmpc_pet_friends_protectors_animals_cats
            if ($pathinfo === '/animales/gatos') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AnimalsController::listAction',  '_route' => 'jmpc_pet_friends_protectors_animals_cats',);
            }

            // jmpc_pet_friends_protectors_animals_birds
            if ($pathinfo === '/animales/aves') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AnimalsController::listAction',  '_route' => 'jmpc_pet_friends_protectors_animals_birds',);
            }

            // jmpc_pet_friends_protectors_animals_others
            if ($pathinfo === '/animales/otros') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AnimalsController::listAction',  '_route' => 'jmpc_pet_friends_protectors_animals_others',);
            }

            // jmpc_pet_friends_protectors_animals_view
            if (preg_match('#^/animales/(?P<id>\\d+)/(?P<slug>[^/]++)$#s', $pathinfo, $matches)) {
                if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                    $allow = array_merge($allow, array('GET', 'HEAD'));
                    goto not_jmpc_pet_friends_protectors_animals_view;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'jmpc_pet_friends_protectors_animals_view')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AnimalsController::viewAction',));
            }
            not_jmpc_pet_friends_protectors_animals_view:

        }

        if (0 === strpos($pathinfo, '/mascotas_perdidas')) {
            // jmpc_pet_friends_protectors_lost
            if (rtrim($pathinfo, '/') === '/mascotas_perdidas') {
                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'jmpc_pet_friends_protectors_lost');
                }

                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\LostController::listAction',  '_route' => 'jmpc_pet_friends_protectors_lost',);
            }

            // jmpc_pet_friends_protectors_lost_new
            if ($pathinfo === '/mascotas_perdidas/nuevo') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\LostController::newAction',  '_route' => 'jmpc_pet_friends_protectors_lost_new',);
            }

            // jmpc_pet_friends_protectors_lost_delete
            if (0 === strpos($pathinfo, '/mascotas_perdidas/borrar') && preg_match('#^/mascotas_perdidas/borrar/(?P<id>\\d+)/(?P<slug>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'jmpc_pet_friends_protectors_lost_delete')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\LostController::deleteAction',));
            }

            // jmpc_pet_friends_protectors_lost_edit
            if (0 === strpos($pathinfo, '/mascotas_perdidas/editar') && preg_match('#^/mascotas_perdidas/editar/(?P<id>\\d+)/(?P<slug>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'jmpc_pet_friends_protectors_lost_edit')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\LostController::editAction',));
            }

            // jmpc_pet_friends_protectors_lost_view
            if (preg_match('#^/mascotas_perdidas/(?P<id>\\d+)/(?P<slug>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'jmpc_pet_friends_protectors_lost_view')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\LostController::viewAction',));
            }

        }

        // jmpc_pet_friends_user
        if ($pathinfo === '/login') {
            return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::indexAction',  '_route' => 'jmpc_pet_friends_user',);
        }

        // jmpc_pet_friends_new_user
        if ($pathinfo === '/register') {
            return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::indexAction',  '_route' => 'jmpc_pet_friends_new_user',);
        }

        if (0 === strpos($pathinfo, '/validate')) {
            // jmpc_pet_friends_validate
            if ($pathinfo === '/validate') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::validateAction',  '_route' => 'jmpc_pet_friends_validate',);
            }

            // jmpc_pet_friends_validate_email
            if ($pathinfo === '/validate_email') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::validateEmailAction',  '_route' => 'jmpc_pet_friends_validate_email',);
            }

        }

        if (0 === strpos($pathinfo, '/profile/update')) {
            // jmpc_pet_friends_update_files
            if ($pathinfo === '/profile/update') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\UserController::updateFileAction',  '_route' => 'jmpc_pet_friends_update_files',);
            }

            // jmpc_pet_friends_update_files_pet
            if ($pathinfo === '/profile/update_pet') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\UserController::updateFilePetAction',  '_route' => 'jmpc_pet_friends_update_files_pet',);
            }

        }

        // jmpc_pet_friends_404
        if ($pathinfo === '/error') {
            return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\PageController::errorAction',  '_route' => 'jmpc_pet_friends_404',);
        }

        if (0 === strpos($pathinfo, '/admin')) {
            // jmpc_pet_friends_protectors_admin
            if ($pathinfo === '/admin') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AdminController::adminAction',  '_route' => 'jmpc_pet_friends_protectors_admin',);
            }

            // jmpc_pet_friends_protectors_admin_users
            if ($pathinfo === '/admin/users') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AdminController::usersAction',  '_route' => 'jmpc_pet_friends_protectors_admin_users',);
            }

            // jmpc_pet_friends_protectors_admin_messages
            if ($pathinfo === '/admin/messages') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\AdminController::messagesAction',  '_route' => 'jmpc_pet_friends_protectors_admin_messages',);
            }

        }

        if (0 === strpos($pathinfo, '/log')) {
            if (0 === strpos($pathinfo, '/login')) {
                // fos_user_security_login
                if ($pathinfo === '/login') {
                    return array (  '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::loginAction',  '_route' => 'fos_user_security_login',);
                }

                // fos_user_security_check
                if ($pathinfo === '/login_check') {
                    if ($this->context->getMethod() != 'POST') {
                        $allow[] = 'POST';
                        goto not_fos_user_security_check;
                    }

                    return array (  '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::checkAction',  '_route' => 'fos_user_security_check',);
                }
                not_fos_user_security_check:

            }

            // fos_user_security_logout
            if ($pathinfo === '/logout') {
                return array (  '_controller' => 'FOS\\UserBundle\\Controller\\SecurityController::logoutAction',  '_route' => 'fos_user_security_logout',);
            }

        }

        if (0 === strpos($pathinfo, '/profile')) {
            // fos_user_profile_show
            if (rtrim($pathinfo, '/') === '/profile') {
                if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                    $allow = array_merge($allow, array('GET', 'HEAD'));
                    goto not_fos_user_profile_show;
                }

                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'fos_user_profile_show');
                }

                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\ProfileController::showAction',  '_route' => 'fos_user_profile_show',);
            }
            not_fos_user_profile_show:

            // fos_user_profile_edit
            if ($pathinfo === '/profile/edit') {
                return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\ProfileController::editAction',  '_route' => 'fos_user_profile_edit',);
            }

        }

        if (0 === strpos($pathinfo, '/re')) {
            if (0 === strpos($pathinfo, '/register')) {
                // fos_user_registration_register
                if (rtrim($pathinfo, '/') === '/register') {
                    if (substr($pathinfo, -1) !== '/') {
                        return $this->redirect($pathinfo.'/', 'fos_user_registration_register');
                    }

                    return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\RegistrationController::registerAction',  '_route' => 'fos_user_registration_register',);
                }

                if (0 === strpos($pathinfo, '/register/c')) {
                    // fos_user_registration_check_email
                    if ($pathinfo === '/register/check-email') {
                        if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                            $allow = array_merge($allow, array('GET', 'HEAD'));
                            goto not_fos_user_registration_check_email;
                        }

                        return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\RegistrationController::checkEmailAction',  '_route' => 'fos_user_registration_check_email',);
                    }
                    not_fos_user_registration_check_email:

                    if (0 === strpos($pathinfo, '/register/confirm')) {
                        // fos_user_registration_confirm
                        if (preg_match('#^/register/confirm/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
                            if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                                $allow = array_merge($allow, array('GET', 'HEAD'));
                                goto not_fos_user_registration_confirm;
                            }

                            return $this->mergeDefaults(array_replace($matches, array('_route' => 'fos_user_registration_confirm')), array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\RegistrationController::confirmAction',));
                        }
                        not_fos_user_registration_confirm:

                        // fos_user_registration_confirmed
                        if ($pathinfo === '/register/confirmed') {
                            if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                                $allow = array_merge($allow, array('GET', 'HEAD'));
                                goto not_fos_user_registration_confirmed;
                            }

                            return array (  '_controller' => 'JMPC\\PetFriends\\ProtectorsBundle\\Controller\\RegistrationController::confirmedAction',  '_route' => 'fos_user_registration_confirmed',);
                        }
                        not_fos_user_registration_confirmed:

                    }

                }

            }

            if (0 === strpos($pathinfo, '/resetting')) {
                // fos_user_resetting_request
                if ($pathinfo === '/resetting/request') {
                    if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                        $allow = array_merge($allow, array('GET', 'HEAD'));
                        goto not_fos_user_resetting_request;
                    }

                    return array (  '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::requestAction',  '_route' => 'fos_user_resetting_request',);
                }
                not_fos_user_resetting_request:

                // fos_user_resetting_send_email
                if ($pathinfo === '/resetting/send-email') {
                    if ($this->context->getMethod() != 'POST') {
                        $allow[] = 'POST';
                        goto not_fos_user_resetting_send_email;
                    }

                    return array (  '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::sendEmailAction',  '_route' => 'fos_user_resetting_send_email',);
                }
                not_fos_user_resetting_send_email:

                // fos_user_resetting_check_email
                if ($pathinfo === '/resetting/check-email') {
                    if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                        $allow = array_merge($allow, array('GET', 'HEAD'));
                        goto not_fos_user_resetting_check_email;
                    }

                    return array (  '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::checkEmailAction',  '_route' => 'fos_user_resetting_check_email',);
                }
                not_fos_user_resetting_check_email:

                // fos_user_resetting_reset
                if (0 === strpos($pathinfo, '/resetting/reset') && preg_match('#^/resetting/reset/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
                    if (!in_array($this->context->getMethod(), array('GET', 'POST', 'HEAD'))) {
                        $allow = array_merge($allow, array('GET', 'POST', 'HEAD'));
                        goto not_fos_user_resetting_reset;
                    }

                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'fos_user_resetting_reset')), array (  '_controller' => 'FOS\\UserBundle\\Controller\\ResettingController::resetAction',));
                }
                not_fos_user_resetting_reset:

            }

        }

        // fos_user_change_password
        if ($pathinfo === '/profile/change-password') {
            if (!in_array($this->context->getMethod(), array('GET', 'POST', 'HEAD'))) {
                $allow = array_merge($allow, array('GET', 'POST', 'HEAD'));
                goto not_fos_user_change_password;
            }

            return array (  '_controller' => 'FOS\\UserBundle\\Controller\\ChangePasswordController::changePasswordAction',  '_route' => 'fos_user_change_password',);
        }
        not_fos_user_change_password:

        throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
    }
}


text:
cmake_minimum_required(VERSION 2.8.7)
# simply copy this file anywhere on your system and execute like this:
# ctest -S mymachine_openjpeg.cmake -V
# This will retrieve/compile/run tests/upload to cdash OpenJPEG
# results will be available at: http://my.cdash.org/index.php?project=OPENJPEG

# Begin User inputs:
set( CTEST_SITE             "mymachine" ) # generally the output of hostname
set( CTEST_DASHBOARD_ROOT   "/tmp" ) # writable path
set( CTEST_CMAKE_GENERATOR  "Unix Makefiles" ) # What is your compilation apps ?
set( CTEST_BUILD_CONFIGURATION  Debug) # What type of build do you want ?
set( ENV{CFLAGS} "-Wall" ) # just for fun...

# For testing we need to define the path to J2KP4files
#  wget http://www.crc.ricoh.com/~gormish/jpeg2000conformance/j2kp4files_v1_5.zip
#  unzip j2kp4files_v1_5.zip
set( CACHE_CONTENTS "
BUILD_TESTING:BOOL=TRUE
JPEG2000_CONFORMANCE_DATA_ROOT:PATH=${CTEST_SOURCE_DIRECTORY}/J2KP4files" )
# End User inputs:

# You do not need to change anything after that:
# 1. openjpeg specific:
set( CTEST_PROJECT_NAME         "OPENJPEG" )
set( CTEST_SOURCE_NAME          OpenJPEG)
set( CTEST_BUILD_NAME           "${CMAKE_SYSTEM}-${CTEST_CMAKE_GENERATOR}-${CTEST_BUILD_CONFIGURATION}")
set( CTEST_BINARY_NAME          "${CTEST_SOURCE_NAME}-${CTEST_BUILD_NAME}")

# 2. cdash/openjpeg specific:
# svn checkout http://openjpeg.googlecode.com/svn/trunk/ openjpeg-read-only
set( CTEST_SVN_URL          "http://openjpeg.googlecode.com/svn/")
set( CTEST_UPDATE_COMMAND   "svn")
#set( CTEST_CHECKOUT_COMMAND "${CTEST_UPDATE_COMMAND} co ${CTEST_SVN_URL}/trunk ${CTEST_SOURCE_NAME}")
set( CTEST_CHECKOUT_COMMAND "${CTEST_UPDATE_COMMAND} co ${CTEST_SVN_URL}/branches/v2 ${CTEST_SOURCE_NAME}")

# 3. cmake specific:
set( CTEST_SOURCE_DIRECTORY "${CTEST_DASHBOARD_ROOT}/${CTEST_SOURCE_NAME}")
set( CTEST_BINARY_DIRECTORY "${CTEST_DASHBOARD_ROOT}/${CTEST_BINARY_NAME}")
set( CTEST_NOTES_FILES      "${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}")

ctest_empty_binary_directory( "${CTEST_BINARY_DIRECTORY}" )
file(WRITE "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt" "${CACHE_CONTENTS}")

# Perform the Nightly build
ctest_start(Nightly)
ctest_update(SOURCE "${CTEST_SOURCE_DIRECTORY}")
ctest_configure(BUILD "${CTEST_BINARY_DIRECTORY}")
ctest_build(BUILD "${CTEST_BINARY_DIRECTORY}")
ctest_test(BUILD "${CTEST_BINARY_DIRECTORY}")
ctest_submit()


text:
package tdanford.ideals;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public enum Rationals implements Field<Rational> {

  FIELD ;

  private static Logger LOG = LoggerFactory.getLogger(Rationals.class);
  private static Pattern rationalPattern = Pattern.compile("(-?\\d+)(/(\\d+))?");

  public static Rational parse(final String strValue) {
    final Matcher m = rationalPattern.matcher(strValue);
    if (m.matches()) {
      final Integer numer = Integer.parseInt(m.group(1));

      final String group2 = m.group(2);
      final Integer denom = group2 != null && group2.length() > 0 ? Integer.parseInt(m.group(3)) : 1;
      return new Rational(numer, denom);
    } else {
      throw new IllegalArgumentException(String.format("Can't parse a Rational from \"%s\"", strValue));
    }
  }

  public static Rational liftInteger(final Integer v) {
    return new Rational((long) v, 1L);
  }

  public boolean lessThan(final Rational left, final Rational right) {
    return left.lessThan(right);
  }

  @Override
  public Rational reciprocal(Rational value) {
    return value.inverse();
  }

  @Override
  public Rational[] array(int length) {
    return new Rational[length];
  }

  @Override
  public Rational product(Rational p1, Rational p2) {
    return p1.product(p2);
  }

  @Override
  public Rational sum(Rational a1, Rational a2) {
    return a1.sum(a2);
  }

  @Override
  public Rational negative(Rational value) {
    return value.negative();
  }

  @Override
  public Rational zero() {
    return new Rational(0, 1);
  }

  @Override
  public Rational one() {
    return new Rational(1, 1);
  }

  @Override
  public Rational pow(final Rational r, final int k) { return r.pow(k); }

  public static Rational fromDouble(final Double v) {
    final int places = 6;
    final double numer = Math.pow(10.0, (double) places);
    final long integralPart = v.longValue();
    final double fractionalPart = v - (double) integralPart;
    final long fractionalDenom = fractionalPart != 0.0 ? (long) (numer / fractionalPart) : 1L;

    LOG.debug("fromDouble(integralPart={}, fractionalPart={}, numer={}, fractionalDenom={})",
      integralPart, fractionalPart, numer, fractionalDenom);

    return new Rational(integralPart, 1L).sum(new Rational((long) numer, fractionalDenom));
  }
}