text:
package org.kiji.mapreduce.lib.bulkimport;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.avro.Schema;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.kiji.annotations.ApiAudience;
import org.kiji.annotations.Inheritance;
import org.kiji.hadoop.configurator.HadoopConf;
import org.kiji.hadoop.configurator.HadoopConfigurator;
import org.kiji.mapreduce.KijiTableContext;
import org.kiji.mapreduce.bulkimport.KijiBulkImporter;
import org.kiji.mapreduce.framework.JobHistoryCounters;
import org.kiji.mapreduce.framework.KijiConfKeys;
import org.kiji.schema.Kiji;
import org.kiji.schema.KijiColumnName;
import org.kiji.schema.KijiSchemaTable;
import org.kiji.schema.KijiTable;
import org.kiji.schema.KijiURI;
import org.kiji.schema.avro.AvroSchema;
import org.kiji.schema.avro.CellSchema;
import org.kiji.schema.layout.KijiTableLayout;
import org.kiji.schema.util.ResourceUtils;

/**
 * DescribedInputTextBulkImporter is an abstract class that provides methods to bulk importers for
 * mapping from source fields in the import lines to destination Kiji columns.  These can be used
 * inside of KijiBulkImportJobBuilder via the withBulkImporter method.
 *
 *
Importing from a text file requires specifying a KijiColumnName, and the source field
 * for each element to be inserted into Kiji, in addition to the raw import data.  This information
 * is provided by {@link KijiTableImportDescriptor} which is set via
 * the kiji.import.text.input.descriptor.path parameter in {@link #CONF_FILE}.
 *
 *
Use this Mapper over text files to import data into a Kiji
 * table.  Each line in the file will be treated as data for one row.
 * This line should generate a single EntityId to write to, and any number
 * of writes to add to that entity.  You should override the produce(String, Context)
 * method to generate the entities from the input lines.

 *
 *
Extensions of this class should implement the following methods:
 *

 *
{@link #produce} - actual producer code for the bulk importer should go here

 *
{@link #setupImporter} - (optional) any specific setup for this bulk importer.

 *
{@link #cleanupImporter} - (optional) any specific cleanup for this bulk importer.

 *

 *
 *
Extensions of this class can use the following methods to implement their producers:
 *

 *
{@link #convert} - parses the text into the type associated with the column.

 *
{@link #incomplete} - to log and mark a row that was incomplete.

 *
{@link #reject} - to log and mark a row that could not be processed.

 *
{@link #getDestinationColumns} - to retrieve a collection of destination columns.

 *
{@link #getSource} - to retrieve the source for one of the columns listed above.

 *
{@link #getEntityIdSource()} - to retrieve the source for the entity id for the row.

 *

 */

@ApiAudience.Public
@Inheritance.Extensible
public abstract class DescribedInputTextBulkImporter extends KijiBulkImporter<LongWritable, Text> {
  private static final Logger LOG = LoggerFactory.getLogger(DescribedInputTextBulkImporter.class);

  /**
   * Location of writer layout file.  File names columns and schemas, and implies
   * ordering of columns in delimited read-in file.
   */
  public static final String CONF_FILE = "kiji.import.text.input.descriptor.path";

  public static final String CONF_LOG_RATE = "kiji.import.text.log.rate";

  private static final ImmutableMap<String, Class<?>> KIJI_CELL_TYPE_TO_CLASS_MAP =
      new ImmutableMap.Builder<String, Class<?>>()
          .put("\"boolean\"", Boolean.class)
          .put("\"int\"", Integer.class)
          .put("\"long\"", Long.class)
          .put("\"float\"", Float.class)
          .put("\"double\"", Double.class)
          .put("\"string\"", String.class)
          .build();

  private static final ImmutableMap<Schema.Type, Class<?>> KIJI_AVRO_TYPE_TO_CLASS_MAP =
      new ImmutableMap.Builder<Schema.Type, Class<?>>()
          .put(Schema.Type.BOOLEAN, Boolean.class)
          .put(Schema.Type.INT, Integer.class)
          .put(Schema.Type.LONG, Long.class)
          .put(Schema.Type.FLOAT, Float.class)
          .put(Schema.Type.DOUBLE, Double.class)
          .put(Schema.Type.STRING, String.class)
          .build();

  /** Number of lines to skip between reject/incomplete lines. */
  private Long mLogRate = 1000L;

  /** Current counter of the number of incomplete lines. */
  private Long mIncompleteLineCounter = 0L;

  /** Current counter of the number of rejected lines. */
  private Long mRejectedLineCounter = 0L;

  /** Table layout of the output table. */
  private KijiTableLayout mOutputTableLayout;

  /** Table import descriptor for this bulk load. */
  private KijiTableImportDescriptor mTableImportDescriptor;

  /** KijiColumnName to cell type map. */
  private Map<KijiColumnName, Class> mColumnNameClassMap;

  /**
   * {@inheritDoc}
   *
   *
If you override this method, you must call <tt>super.setConf(conf)</tt>.

   */
  @Override
  public void setConf(Configuration conf) {
    super.setConf(conf);
  }

  /**
   * Performs validation that this table import descriptor can be applied to the output table.
   *
   * This method is final to prevent it from being overridden without being called.
   * Subclasses should override the {@link #setupImporter} method instead of overriding this method.
   *
   * {@inheritDoc}
   */
  @Override
  public final void setup(KijiTableContext context) throws IOException {
    HadoopConfigurator.configure(this);
    final Configuration conf = getConf();
    Preconditions.checkNotNull(mTableImportDescriptor);

    final KijiURI uri = KijiURI.newBuilder(conf.get(KijiConfKeys.KIJI_OUTPUT_TABLE_URI)).build();

    final Kiji kiji = Kiji.Factory.open(uri, conf);
    final KijiSchemaTable schemaTable = kiji.getSchemaTable();
    try {
      final KijiTable table = kiji.openTable(uri.getTable());
      try {
        mOutputTableLayout = table.getLayout();
      } finally {
        table.release();
      }

      Preconditions.checkNotNull(mOutputTableLayout);
      mTableImportDescriptor.validateDestination(mOutputTableLayout);

      // Retrieve the classes for all of the imported columns.
      Map<KijiColumnName, Class> columnNameClassMap = Maps.newHashMap();
      for (KijiColumnName kijiColumnName
          : mTableImportDescriptor.getColumnNameSourceMap().keySet()) {
        CellSchema cellSchema = mOutputTableLayout.getCellSchema(kijiColumnName);
        switch(cellSchema.getType()) {
          case AVRO:
            // Since this is for prepackaged generic bulk importers, we can assume that we want to
            // to use the default reader schema for determining the type to write as.
            Schema.Type schemaType;
            AvroSchema as = cellSchema.getDefaultReader();
            if (as.getUid() != null) {
              Schema schema = schemaTable.getSchema(as.getUid());
              schemaType = schema.getType();
            } else if (as.getJson() != null) {
              Schema schema = new Schema.Parser().parse(as.getJson());
              schemaType = schema.getType();
            } else {
              throw new IOException("Schema is not a UID or JSON type.");
            }
            if (KIJI_AVRO_TYPE_TO_CLASS_MAP.containsKey(schemaType)) {
              columnNameClassMap.put(kijiColumnName,
                KIJI_AVRO_TYPE_TO_CLASS_MAP.get(schemaType));
            } else {
              throw new IOException("Unsupported described output type: " + cellSchema.getValue());
            }
            break;
          case INLINE:
            if (KIJI_CELL_TYPE_TO_CLASS_MAP.containsKey(cellSchema.getValue())) {
              columnNameClassMap.put(kijiColumnName,
                KIJI_CELL_TYPE_TO_CLASS_MAP.get(cellSchema.getValue()));
            } else {
              throw new IOException("Unsupported described output type: " + cellSchema.getValue());
            }
            break;
          case CLASS:
            throw new IOException("Unsupported described output type: " + cellSchema.getType());
          default:
            throw new IOException("Unsupported described output type: " + cellSchema.getType());
        }
      }
      mColumnNameClassMap = ImmutableMap.copyOf(columnNameClassMap);
    } finally {
      ResourceUtils.releaseOrLog(kiji);
    }

    setupImporter(context);
  }

  /**
   * Extensible version of {@link KijiBulkImporter#setup} for subclasses of
   * DescribedInputTextBulkImporter.
   * Does nothing by default.
   *
   * @param context A context you can use to generate EntityIds and commit writes.
   * @throws IOException on I/O error.
   */
  public void setupImporter(KijiTableContext context) throws IOException {}

  /**
   * Converts a line of text to a set of writes to context, and
   * an EntityId for the row.
   *
   * @param line The line to parse.
   * @param context The context to write to.
   * @throws IOException if there is an error.
   */
  public abstract void produce(Text line, KijiTableContext context)
      throws IOException;

  /**
   * Post-processes incomplete lines(Logging, keeping count, etc).
   *
   * @param line the line that was marked incomplete incomplete by the producer.
   * @param context the context in which the incompletion occured.
   * @param reason the reason why this line was incomplete.
   */
  public void incomplete(Text line, KijiTableContext context, String reason) {
    if (mIncompleteLineCounter % mLogRate == 0L) {
      LOG.error("Incomplete line: {} with reason: {}",
          line.toString(), reason);
    }
    mIncompleteLineCounter++;

    //TODO(KIJIMRLIB-9) Abort this bulk importer job early if incomplete records exceed a threshold
    context.incrementCounter(JobHistoryCounters.BULKIMPORTER_RECORDS_INCOMPLETE);

    //TODO(KIJIMRLIB-4) Add a strict mode where we reject incomplete lines
  }

  /**
   * Post-processes rejected lines(Logging, keeping count, etc).
   *
   * @param line the line that was rejected by the producer.
   * @param context the context in which the rejection occured.
   * @param reason the reason why this line was rejected.
   */
  public void reject(Text line, KijiTableContext context, String reason) {
    if (mRejectedLineCounter % mLogRate == 0L) {
      LOG.error("Rejecting line: {} with reason: {}",
          line.toString(), reason);
    }
    mRejectedLineCounter++;

    //TODO(KIJIMRLIB-9) Abort this bulk importer job early if rejected records exceed a threshold
    context.incrementCounter(JobHistoryCounters.BULKIMPORTER_RECORDS_REJECTED);

    //TODO(KIJIMRLIB-4) Allow this to emit to a rejected output so that import can be reattempted.
  }

  /**
   * Converts the value into an object of the type associated with the specified column.
   * @param kijiColumnName the destination column to infer the type from.
   * @param value string representation of the value.
   * @return object containing the parsed representation of the value.
   */
  public Object convert(KijiColumnName kijiColumnName, String value) {
    Class<?> clazz = mColumnNameClassMap.get(kijiColumnName);
    if (clazz == Boolean.class) {
      return Boolean.valueOf(value);
    } else if (clazz == Integer.class) {
      return Integer.valueOf(value);
    } else if (clazz == Long.class) {
      return Long.valueOf(value);
    } else if (clazz == Float.class) {
      return Float.valueOf(value);
    } else if (clazz == Double.class) {
      return Double.valueOf(value);
    } else if (clazz == String.class) {
      return value;
    }
    return value;
  }

  /**
   * Subclasses should implement the produce(Text line, KijiTableContext context) method instead.
   * {@inheritDoc}
   */
  @Override
  public final void produce(LongWritable fileOffset, Text line, KijiTableContext context)
      throws IOException {
    produce(line, context);
  }

  /** @return an unmodifiable collection of the columns for this bulk importer. */
  protected final Collection<KijiColumnName> getDestinationColumns() {
    Set<KijiColumnName> columns = mTableImportDescriptor.getColumnNameSourceMap().keySet();
    return Collections.unmodifiableSet(columns);
  }

  /**
   * Returns the source for the specified column, or null if the specified column is not a
   * destination column for this importer.
   *
   * @param kijiColumnName the requested Kiji column
   * @return the source for the requested column
   */
  protected final String getSource(KijiColumnName kijiColumnName) {
    return mTableImportDescriptor.getColumnNameSourceMap().get(kijiColumnName);
  }

  /** @return the source for the EntityId. */
  protected final String getEntityIdSource() {
    return mTableImportDescriptor.getEntityIdSource();
  }

  /** @return whether to override the timestamp from system time. */
  protected final boolean isOverrideTimestamp() {
    return null != mTableImportDescriptor.getOverrideTimestampSource();
  }

  /** @return the source for timestamp. */
  protected final String getTimestampSource() {
    return mTableImportDescriptor.getOverrideTimestampSource();
  }

  /**
   * Subclasses should implement the {@link #cleanupImporter(KijiTableContext)} method instead.
   * {@inheritDoc}
   */
  @Override
  public final void cleanup(KijiTableContext context) throws IOException {
    cleanupImporter(context);
  }

  /**
   * Extensible version of {@link KijiBulkImporter#cleanup} for subclasses of
   * DescribedInputTextBulkImporter.
   * Does nothing by default.
   *
   * @param context A context you can use to generate EntityIds and commit writes.
   * @throws IOException on I/O error.
   */
  public void cleanupImporter(KijiTableContext context) throws IOException {}

  /**
   * Sets the log rate - the number of lines between log statements for incomplete/rejected lines.
   *
   * @param logRateString The logging rate as a string.
   */
  @HadoopConf(key=CONF_LOG_RATE, usage="The number of lines to skip between log statements")
  protected final void setLogRate(String logRateString) {
    if (logRateString != null) {
      try {
        Long logRate = Long.parseLong(logRateString);
        mLogRate = logRate;
      } catch (NumberFormatException ne) {
        LOG.warn("Unable to parse log rate: " + logRateString);
      }
    }
  }

  /**
   * Sets the path to the text input descriptor file and parses it.
   *
   * @param inputDescriptorFile The input descriptor path.
   * @throws RuntimeException if there's an error reading or parsing the input descriptor.
   */
  @HadoopConf(key=CONF_FILE, usage="The input descriptor file.")
  protected final void setInputDescriptorPath(String inputDescriptorFile) {

    if (null == inputDescriptorFile || inputDescriptorFile.isEmpty()) {
      // Remind the user to specify this path.
      LOG.error("No input-descriptor path specified.");
      throw new RuntimeException("No input descriptor file specified on the Configuration."
          + "  Did you specify the " + CONF_FILE + " variable?");
    }

    Path descriptorPath = new Path(inputDescriptorFile);
    try {
      LOG.info("Parsing input-descriptor file: " + descriptorPath.toString());
      FileSystem fs = descriptorPath.getFileSystem(getConf());
      FSDataInputStream inputStream = fs.open(descriptorPath);
      mTableImportDescriptor =
          KijiTableImportDescriptor.createFromEffectiveJson(inputStream);

    } catch (IOException ioe) {
      LOG.error("Could not read input-descriptor file: " + descriptorPath.toString());
      throw new RuntimeException("Could not read file: " + descriptorPath.toString(), ioe);
    }
  }
}


text:
require_dependency 'application_helper'

module ApplicationHelper
  alias_method :pagination_links_full_without_bootstrap, :pagination_links_full
  alias_method :per_page_links_without_bootstrap, :per_page_links
  alias_method :progress_bar_without_bootstrap, :progress_bar
  alias_method :render_project_jump_box_without_bootstrap, :render_project_jump_box

  def pagination_links_full(paginator, count=nil, options={})
    page_param = options.delete(:page_param) || :page
    per_page_links = options.delete(:per_page_links)
    options[:link_to_current_page] = true
    url_param = params.dup

    html = '

'
    if paginator.current.previous
      html << "
#{link_to_content_update(l(:label_previous), url_param.merge(page_param => paginator.current.previous))}
"
    end

    html << (pagination_links_each(paginator, options) do |n|
      "
#{link_to_content_update(n.to_s, url_param.merge(page_param => n))}
"
    end || '')

    if paginator.current.next
      html << "
#{link_to_content_update(l(:label_next), url_param.merge(page_param => paginator.current.next))}
"
    end

    unless count.nil?
      html << "
(#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})
"
      if per_page_links != false && links = per_page_links(paginator.items_per_page, count)
        html << "#{links}"
      end
    end
    html << "

"
    html.html_safe
  end

  def per_page_links(selected=10, item_count=nil)
    values = Setting.per_page_options_array
    if item_count && values.any?
      if item_count > values.first
        max = values.detect {|value| value >= item_count} || item_count
      else
        max = item_count
      end
      values = values.select {|value| value <= max || value == selected}
    end
    if values.empty? || (values.size == 1 && values.first == selected)
      return nil
    end
    links = values.collect do |n|
      n == selected ? "
#{n}
" : "
#{link_to_content_update(n, params.merge(:per_page => n))}
"
    end
    "
#{l(:label_display_per_page, links.join(''))}
"

  end

  def progress_bar(pcts, options={})
    html = ""
    pcts = [pcts, pcts] unless pcts.is_a?(Array)
    pcts = pcts.collect(&:round)
    pcts[1] = pcts[1] - pcts[0]
    pcts << (100 - pcts[1] - pcts[0])
    legend = options[:legend] || ''
    html << "
"
    html << "

"
    html << "

"
    html << "

"
    html << "
"
    html.html_safe
  end

  def render_project_nested_lists(projects)
    s = ''
    if projects.any?
      ancestors = []
      original_project = @project
      projects.sort_by(&:lft).each do |project|
        # set the project environment to please macros.
        @project = project
        if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
          s << "
\n"
        else
          ancestors.pop
          s << "
"
          while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
            ancestors.pop
            s << "

\n"
          end
        end
        classes = (ancestors.empty? ? 'root' : 'child')
        s << "

"
        s << h(block_given? ? yield(project) : project.name)
        s << "
\n"
        ancestors << project
      end
      s << ("

\n" * ancestors.size)
      @project = original_project
    end
    s.html_safe
  end

      # modified from redmine_favourite_projects plugin
    def render_project_jump_box
      return unless User.current.logged?
      projects = User.current.memberships.collect(&:project).compact.uniq
      if projects.any?
        s = '
'
        s+= ''
        s+= l(:label_jump_to_a_project)
        s+= ''
        s+= ''
        s+= '
'
        projects.each do |project|
          s+= '
' + link_to(project.name, :controller => 'projects', :action => 'show', :id => project.id) + '
'
        end
        s+= '
'
        s+= '
'
        s.html_safe
      end
    end

end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ws.security;

import javax.xml.namespace.QName;

/**
 * SOAP 1.2 constants
 *
 * @author Glen Daniels (gdaniels@apache.org)
 * @author Andras Avar (andras.avar@nokia.com)
 */
public class SOAP12Constants implements SOAPConstants {
    private static QName headerQName = new QName(WSConstants.URI_SOAP12_ENV,
            WSConstants.ELEM_HEADER);
    private static QName bodyQName = new QName(WSConstants.URI_SOAP12_ENV,
            WSConstants.ELEM_BODY);
    private static QName roleQName = new QName(WSConstants.URI_SOAP12_ENV,
            WSConstants.ATTR_ROLE);

    // Public constants for SOAP 1.2

    /**
     * MessageContext property name for webmethod
     */
    public static final String PROP_WEBMETHOD = "soap12.webmethod";

    public String getEnvelopeURI() {
        return WSConstants.URI_SOAP12_ENV;
    }

    public QName getHeaderQName() {
        return headerQName;
    }

    public QName getBodyQName() {
        return bodyQName;
    }

    /**
     * Obtain the QName for the role attribute (actor/role)
     */
    public QName getRoleAttributeQName() {
        return roleQName;
    }

    /**
     * Obtain the "next" role/actor URI
     */
    public String getNextRoleURI() {
        return WSConstants.URI_SOAP12_NEXT_ROLE;
    }

    /**
     * Obtain the MustUnderstand string
     */
    public String getMustUnderstand() {
        return "true";
    }

    /**
     * Obtain the MustUnderstand string
     * @deprecated use getMustUnderstand() instead
     */
    public String getMustunderstand() {
        return getMustUnderstand();
    }

}


text:
@import UIKit;

@interface YXViewController : UIViewController

@end


text:
namespace ash {

// A self-owned object to handle the cancel and the finish of current partial
// screenshot session.
class PartialScreenshotView::OverlayDelegate
    : public internal::OverlayEventFilter::Delegate,
      public views::WidgetObserver {
 public:
  OverlayDelegate() {
    Shell::GetInstance()->overlay_filter()->Activate(this);
  }

  void RegisterWidget(views::Widget* widget) {
    widgets_.push_back(widget);
    widget->AddObserver(this);
  }

  // Overridden from OverlayEventFilter::Delegate:
  virtual void Cancel() OVERRIDE {
    // Make sure the mouse_warp_mode allows warping. It can be stopped by a
    // partial screenshot view.
    internal::MouseCursorEventFilter* mouse_cursor_filter =
        Shell::GetInstance()->mouse_cursor_filter();
    mouse_cursor_filter->set_mouse_warp_mode(
        internal::MouseCursorEventFilter::WARP_ALWAYS);
    for (size_t i = 0; i < widgets_.size(); ++i)
      widgets_[i]->Close();
  }

  virtual bool IsCancelingKeyEvent(ui::KeyEvent* event) OVERRIDE {
    return event->key_code() == ui::VKEY_ESCAPE;
  }

  virtual aura::Window* GetWindow() OVERRIDE {
    // Just returns NULL because this class does not handle key events in
    // OverlayEventFilter, except for cancel keys.
    return NULL;
  }

  // Overridden from views::WidgetObserver:
  virtual void OnWidgetDestroying(views::Widget* widget) OVERRIDE {
    widget->RemoveObserver(this);
    widgets_.erase(std::remove(widgets_.begin(), widgets_.end(), widget));
    if (widgets_.empty())
      delete this;
  }

 private:
  virtual ~OverlayDelegate() {
    Shell::GetInstance()->overlay_filter()->Deactivate();
  }

  std::vector<views::Widget*> widgets_;

  DISALLOW_COPY_AND_ASSIGN(OverlayDelegate);
};

// static
std::vector<PartialScreenshotView*>
PartialScreenshotView::StartPartialScreenshot(
    ScreenshotDelegate* screenshot_delegate) {
  std::vector<PartialScreenshotView*> views;
  OverlayDelegate* overlay_delegate = new OverlayDelegate();
  aura::Window::Windows root_windows = Shell::GetAllRootWindows();
  for (aura::Window::Windows::iterator it = root_windows.begin();
       it != root_windows.end(); ++it) {
    PartialScreenshotView* new_view = new PartialScreenshotView(
        overlay_delegate, screenshot_delegate);
    new_view->Init(*it);
    views.push_back(new_view);
  }
  return views;
}

PartialScreenshotView::PartialScreenshotView(
    PartialScreenshotView::OverlayDelegate* overlay_delegate,
    ScreenshotDelegate* screenshot_delegate)
    : is_dragging_(false),
      overlay_delegate_(overlay_delegate),
      screenshot_delegate_(screenshot_delegate) {
}

PartialScreenshotView::~PartialScreenshotView() {
  overlay_delegate_ = NULL;
  screenshot_delegate_ = NULL;
}

void PartialScreenshotView::Init(aura::Window* root_window) {
  views::Widget* widget = new views::Widget;
  views::Widget::InitParams params(
      views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
  params.delegate = this;
  // The partial screenshot rectangle has to be at the real top of
  // the screen.
  params.parent = Shell::GetContainer(
      root_window,
      internal::kShellWindowId_OverlayContainer);

  widget->Init(params);
  widget->SetContentsView(this);
  widget->SetBounds(root_window->GetBoundsInScreen());
  widget->GetNativeView()->SetName("PartialScreenshotView");
  widget->StackAtTop();
  widget->Show();
  // Releases the mouse capture to let mouse events come to the view. This
  // will close the context menu.
  aura::client::CaptureClient* capture_client =
      aura::client::GetCaptureClient(root_window);
  if (capture_client->GetCaptureWindow())
    capture_client->ReleaseCapture(capture_client->GetCaptureWindow());

  overlay_delegate_->RegisterWidget(widget);
}

gfx::Rect PartialScreenshotView::GetScreenshotRect() const {
  int left = std::min(start_position_.x(), current_position_.x());
  int top = std::min(start_position_.y(), current_position_.y());
  int width = ::abs(start_position_.x() - current_position_.x());
  int height = ::abs(start_position_.y() - current_position_.y());
  return gfx::Rect(left, top, width, height);
}

void PartialScreenshotView::OnSelectionStarted(const gfx::Point& position) {
  start_position_ = position;
}

void PartialScreenshotView::OnSelectionChanged(const gfx::Point& position) {
  if (is_dragging_ && current_position_ == position)
    return;
  current_position_ = position;
  SchedulePaint();
  is_dragging_ = true;
}

void PartialScreenshotView::OnSelectionFinished() {
  overlay_delegate_->Cancel();
  if (!is_dragging_)
    return;

  is_dragging_ = false;
  if (screenshot_delegate_) {
    aura::Window*root_window =
        GetWidget()->GetNativeWindow()->GetRootWindow();
    screenshot_delegate_->HandleTakePartialScreenshot(
        root_window,
        gfx::IntersectRects(root_window->bounds(), GetScreenshotRect()));
  }
}

gfx::NativeCursor PartialScreenshotView::GetCursor(
    const ui::MouseEvent& event) {
  // Always use "crosshair" cursor.
  return ui::kCursorCross;
}

void PartialScreenshotView::OnPaint(gfx::Canvas* canvas) {
  if (is_dragging_) {
    // Screenshot area representation: black rectangle with white
    // rectangle inside.  To avoid capturing these rectangles when mouse
    // release, they should be outside of the actual capturing area.
    gfx::Rect screenshot_rect = GetScreenshotRect();
    screenshot_rect.Inset(-1, -1, -1, -1);
    canvas->DrawRect(screenshot_rect, SK_ColorWHITE);
    screenshot_rect.Inset(-1, -1, -1, -1);
    canvas->DrawRect(screenshot_rect, SK_ColorBLACK);
  }
}

bool PartialScreenshotView::OnMousePressed(const ui::MouseEvent& event) {
  // Prevent moving across displays during drag. Capturing a screenshot across
  // the displays is not supported yet.
  // TODO(mukai): remove this restriction.
  internal::MouseCursorEventFilter* mouse_cursor_filter =
      Shell::GetInstance()->mouse_cursor_filter();
  mouse_cursor_filter->set_mouse_warp_mode(
      internal::MouseCursorEventFilter::WARP_NONE);
  OnSelectionStarted(event.location());
  return true;
}

bool PartialScreenshotView::OnMouseDragged(const ui::MouseEvent& event) {
  OnSelectionChanged(event.location());
  return true;
}

bool PartialScreenshotView::OnMouseWheel(const ui::MouseWheelEvent& event) {
  // Do nothing but do not propagate events futhermore.
  return true;
}

void PartialScreenshotView::OnMouseReleased(const ui::MouseEvent& event) {
  OnSelectionFinished();
}

void PartialScreenshotView::OnMouseCaptureLost() {
  is_dragging_ = false;
  OnSelectionFinished();
}

void PartialScreenshotView::OnGestureEvent(ui::GestureEvent* event) {
  switch(event->type()) {
    case ui::ET_GESTURE_TAP_DOWN:
      OnSelectionStarted(event->location());
      break;
    case ui::ET_GESTURE_SCROLL_UPDATE:
      OnSelectionChanged(event->location());
      break;
    case ui::ET_GESTURE_SCROLL_END:
    case ui::ET_SCROLL_FLING_START:
      OnSelectionFinished();
      break;
    default:
      break;
  }

  event->SetHandled();
}

}  // namespace ash


text:
package us.kbase.kbasenetworks.core;

public enum NetworkType {

	REGULATORY_NETWORK ("kb|nettype.1", "Regulatory network", "some description"),
	PROT_PROT_INTERACTION("kb|nettype.2", "Protein-protein interaction", "Physical interactions between proteins"),
	METABOLIC_SUBSYSTEM ("kb|nettype.3", "Metabolic subsystems", "Genes encoding enzymes in a metabolic subsystem"),
	FUNCTIONAL_ASSOCIATION ("kb|nettype.4", "Functional association", "Data of various types are integrated"),
	CO_FITNESS ("kb|nettype.5", "Map of co-fitness modules", "Network of overlapping co-fitness modules based on module overlap"),
	CO_EXPRESSION ("kb|nettype.6", "Map of co-expression modules", "Network of overlapping co-expression modules based on module overlap"),
	FUNCTIONAL_ABUNDANCE("kb|nettype.7", "Functional Abundance", "Correlated abundance of functions in multiple species"),
	PHYLOTYPE_ABUNDANCE("kb|nettype.8", "Phylotype Abundance", "Correlated abundance of species, OTUs, or other phylotypes");

	private String id;
	private String name;
	private String description;

	private NetworkType(String id, String name, String description){
		this.id = id;
		this.name = name;
		this.description = description;
	}

	public String getId(){
		return id;
	}

	public String getName()
	{
		return name;
	}

	public String getDesccription()
	{
		return description;
	}
}


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

import java.util.List;
import java.util.Map;

import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.common.engine.impl.interceptor.CommandExecutor;
import org.flowable.common.engine.impl.query.AbstractNativeQuery;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.service.TaskServiceConfiguration;
import org.flowable.task.service.history.NativeHistoricTaskInstanceQuery;

public class NativeHistoricTaskInstanceQueryImpl extends AbstractNativeQuery<NativeHistoricTaskInstanceQuery, HistoricTaskInstance> implements NativeHistoricTaskInstanceQuery {

    private static final long serialVersionUID = 1L;

    protected TaskServiceConfiguration taskServiceConfiguration;

    public NativeHistoricTaskInstanceQueryImpl(CommandContext commandContext, TaskServiceConfiguration taskServiceConfiguration) {
        super(commandContext);
        this.taskServiceConfiguration = taskServiceConfiguration;
    }

    public NativeHistoricTaskInstanceQueryImpl(CommandExecutor commandExecutor, TaskServiceConfiguration taskServiceConfiguration) {
        super(commandExecutor);
        this.taskServiceConfiguration = taskServiceConfiguration;
    }

    // results ////////////////////////////////////////////////////////////////

    @Override
    public List<HistoricTaskInstance> executeList(CommandContext commandContext, Map<String, Object> parameterMap) {
        return taskServiceConfiguration.getHistoricTaskInstanceEntityManager().findHistoricTaskInstancesByNativeQuery(parameterMap);
    }

    @Override
    public long executeCount(CommandContext commandContext, Map<String, Object> parameterMap) {
        return taskServiceConfiguration.getHistoricTaskInstanceEntityManager().findHistoricTaskInstanceCountByNativeQuery(parameterMap);
    }

}


text:
package org.apache.pulsar.compaction;

import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class CompactorMXBeanImpl implements CompactorMXBean {

    private final ConcurrentHashMap<String, CompactionRecord> compactionRecordOps = new ConcurrentHashMap<>();

    public void addCompactionRemovedEvent(String topic) {
        compactionRecordOps.computeIfAbsent(topic, k -> new CompactionRecord()).addCompactionRemovedEvent();
    }

    public void addCompactionStartOp(String topic) {
        compactionRecordOps.computeIfAbsent(topic, k -> new CompactionRecord()).addCompactionStartOp();
    }

    public void addCompactionEndOp(String topic, boolean succeed) {
        compactionRecordOps.computeIfAbsent(topic, k -> new CompactionRecord()).addCompactionEndOp(succeed);
    }

    @Override
    public void removeTopic(String topic) {
        compactionRecordOps.remove(topic);
    }

    @Override
    public Optional<CompactionRecord> getCompactionRecordForTopic(String topic) {
        return Optional.ofNullable(compactionRecordOps.get(topic));
    }

    public Set<String> getTopics() {
        return compactionRecordOps.keySet();
    }

    public void reset() {
        compactionRecordOps.values().forEach(CompactionRecord::reset);
    }

    public void addCompactionReadOp(String topic, long readableBytes) {
        compactionRecordOps.computeIfAbsent(topic, k -> new CompactionRecord()).addCompactionReadOp(readableBytes);
    }

    public void addCompactionWriteOp(String topic, long writeableBytes) {
        compactionRecordOps.computeIfAbsent(topic, k -> new CompactionRecord()).addCompactionWriteOp(writeableBytes);
    }

    public void addCompactionLatencyOp(String topic, long latency, TimeUnit unit) {
        compactionRecordOps.computeIfAbsent(topic, k -> new CompactionRecord()).addCompactionLatencyOp(latency, unit);
    }
}


text:
package gueei.binding.viewAttributes.view;

public class KeyEventResult {
	public boolean eventConsumed = false;
}


text:
<!DOCTYPE html>

    <meta charset=utf-8>
    <title>jQuery Toaster Unit Tests</title>
    <link rel=stylesheet href="http://code.jquery.com/qunit/git/qunit.css" />
    <link rel=stylesheet href="../../jquery.toaster.css" />

jQuery Test Suite


text:
$(document).ready(function() {
	var active1 = false;
	var active2 = false;
	var active3 = false;
	var active4 = false;
	var active5 = false;
	var active6 = false;
	var active7 = false;
	var active8 = false;
	var active9 = false;
	var active10 = false;

	$('.frameformenu').on('click', function() {

		if (!active1) $(this).find('.circlelink1').css({'opacity': '1','background-color': '#403A3A','transform': 'translate(0px,-125px)'});
		else $(this).find('.circlelink1').css({'opacity': '0', 'transform': 'none'});
		if (!active2) $(this).find('.circlelink2').css({'opacity': '1','background-color': '#403A3A', 'transform': 'translate(60px,-105px)'});
		else $(this).find('.circlelink2').css({'opacity': '0', 'transform': 'none'});
		if (!active3) $(this).find('.circlelink3').css({'opacity': '1','background-color': '#403A3A', 'transform': 'translate(105px,-60px)'});
		else $(this).find('.circlelink3').css({'opacity': '0', 'transform': 'none'});
		if (!active4) $(this).find('.circlelink4').css({'opacity': '1','background-color': '#403A3A', 'transform': 'translate(125px,0px)'});
		else $(this).find('.circlelink4').css({'opacity': '0', 'transform': 'none'});
		/*facebook*/
		if (!active5) $(this).find('.circlelink5').css({'opacity': '1','background-color': '#3b5998', 'transform': 'translate(225px,0px)'});
		else $(this).find('.circlelink5').css({'opacity': '0', 'transform': 'none'});
		/*twitter*/
		if (!active6) $(this).find('.circlelink6').css({'opacity': '1','background-color': '#00aced', 'transform': 'translate(210px, -65px)'});
		else $(this).find('.circlelink6').css({'opacity': '0', 'transform': 'none'});
		/*instagram*/
		if (!active7) $(this).find('.circlelink7').css({'opacity': '1','background-color': '#517fa4', 'transform': 'translate(175px, -125px)'});
		else $(this).find('.circlelink7').css({'opacity': '0', 'transform': 'none'});
		/*google-plus*/
		if (!active8) $(this).find('.circlelink8').css({'opacity': '1','background-color': '#dd4b39', 'transform': 'translate(125px, -170px)'});
		else $(this).find('.circlelink8').css({'opacity': '0', 'transform': 'none'});
		/*github*/
		if (!active9) $(this).find('.circlelink9').css({'opacity': '1','background-color': '#333', 'transform': 'translate(65px, -200px)'});
		else $(this).find('.circlelink9').css({'opacity': '0', 'transform': 'none'});
		/*linkedin*/
		if (!active10) $(this).find('.circlelink10').css({'opacity': '1','background-color': '#007bb6', 'transform': 'translate(0px,-215px)'});
		else $(this).find('.circlelink10').css({'opacity': '0', 'transform': 'none'});

		active1 = !active1;
		active2 = !active2;
		active3 = !active3;
		active4 = !active4;
		active5 = !active5;
		active6 = !active6;
		active7 = !active7;
		active8 = !active8;
		active9 = !active9;
		active10 = !active10;

	});
});


text:
using System;

namespace TNT.Presentation.Serializers
{
    public class SerializationRule
    {
        private readonly Predicate<Type> _rule;
        private readonly Func<Type, SerializerFactory, ISerializer> _serializerLocator;

        public SerializationRule(Predicate<Type> rule, Func<Type, SerializerFactory, ISerializer> serializerLocator)
        {
            _rule = rule;
            _serializerLocator = serializerLocator;
        }

        public SerializationRule(Predicate<Type> rule, Func<Type, ISerializer> serializerLocator)
        {
            _rule = rule;
            _serializerLocator = (t,f)=> serializerLocator(t);
        }

        public static SerializationRule Create<T>(ISerializer<T> serializer)
        {
            return new SerializationRule((t)=> t == typeof(T),(t)=>serializer);
        }

        public Predicate<Type> Rule
        {
            get { return _rule; }
        }

        public ISerializer GetSerializer(Type type, SerializerFactory factory)
        {
            return _serializerLocator(type, factory);
        }
    }
}


text:
package org.polaris.framework.hadoop.mapreduce;

import java.io.IOException;

import org.apache.hadoop.mapreduce.Job;

/**
 * Job的设置
 *
 * @author wang.sheng
 *
 */
public interface MapReduceJobSetter
{
	/**
	 * 设置Job启动前的各项属性
	 *
	 * @param job
	 * @throws IOException
	 */
	void set(Job job) throws IOException;
}


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

import {DeleteResourceController} from 'common/resource/deleteresource_controller';
import resourceModule from 'common/resource/resource_module';

describe('Delete resource controller', () => {
  /** @type !{!common/resource/deleteresource_controller.DeleteResourceController} */
  let ctrl;
  /** @type {!md.$dialog} */
  let mdDialog;
  /** @type {!angular.$httpBackend} */
  let httpBackend;

  beforeEach(() => angular.mock.module(resourceModule.name));

  beforeEach(angular.mock.inject(($controller, $mdDialog, $httpBackend) => {
    ctrl = $controller(DeleteResourceController, {
      resourceKindName: 'My Resource',
      objectMeta: {name: 'Foo', namespace: 'Bar'},
      typeMeta: {kind: 'qux'},
    });
    mdDialog = $mdDialog;
    httpBackend = $httpBackend;
  }));

  it('should delete resource', () => {
    spyOn(mdDialog, 'hide');
    ctrl.remove();
    httpBackend.expectDELETE('api/v1/qux/namespace/Bar/name/Foo').respond(200, {ok: 'ok'});
    httpBackend.flush();
    expect(mdDialog.hide).toHaveBeenCalled();
  });

  it('should propagate errors on delete', () => {
    spyOn(mdDialog, 'cancel');
    ctrl.remove();
    httpBackend.expectDELETE('api/v1/qux/namespace/Bar/name/Foo').respond(500, {err: 'err'});
    httpBackend.flush();
    expect(mdDialog.cancel).toHaveBeenCalled();
  });

  it('should cancel', () => {
    spyOn(mdDialog, 'cancel');
    ctrl.cancel();
    expect(mdDialog.cancel).toHaveBeenCalled();
  });
});


text:
using namespace sf;
using namespace std;

namespace hg
{
	class StyleData
	{
		private:
			string id;
			float hueMin;
			float hueMax;
			bool huePingPong;
			float hueIncrement;
			bool huePulse;
			bool mainDynamic;
			float mainDynamicDarkness;
			Color mainStatic;
			bool aDynamic;
			float aDynamicDarkness;
			Color aStatic;
			bool bDynamic;
			bool bDynamicOffset;
			float bDynamicDarkness;
			Color bStatic;

			float currentHue;
			float currentSwapTime;
			Color currentMain;
			Color currentA;
			Color currentB;

			float pulseFactor{1.00f};
			float pulseFactorMin{0.77f};
			float pulseFactorMax{1.10f};
			float pulseFactorIncrement{0.018f};

		public:
			StyleData() = default;
			StyleData(string mId, float mHueMin, float mHueMax, bool mHuePingPong, float mHueIncrement, bool mHuePulse, bool mMainDynamic,
						float mMainDynamicDarkness, Color mMainStatic, bool mADynamic, float mADynamicDarkness, Color mAStatic,
						bool mBDynamic, bool mBDynamicOffset, float mBDynamicDarkness, Color mBStatic);

			void update(float mFrameTime);

			string getId();
			float getHueMin();
			float getHueMax();
			bool getHuePingPong();
			float getHueIncrement();
			bool getHuePulse();
			bool getMainDynamic();
			float getMainDynamicDarkness();
			Color getMainStatic();
			bool getADynamic();
			float getADynamicDarkness();
			Color getAStatic();
			bool getBDynamic();
			bool getBDynamicOffset();
			float getBDynamicDarkness();
			Color getBStatic();

			float getCurrentHue();
			float getCurrentSwapTime();
			Color getCurrentMain();
			Color getCurrentA();
			Color getCurrentB();
	};
}

#endif // STYLEDATA_H_


text:
<?php use yii\bootstrap\Alert; ?>

<?php if (\Yii::$app->user->isGuest): ?>

	        <?php echo $this->render('forms/RegisterForm', [ 'model' => $model ]); ?>

<?php else: ?>
	<?php echo Alert::widget([
		'options' => [
			'class' => 'alert alert-info'
		],
		'body' => 'You are already logged in. To register a new user, logout first'
	]); ?>
<?php endif; ?>


text:
<#
.Synopsis
   Downloads a file from a specified URL on the Internet.
.DESCRIPTION
   Function will download a single file from the Internet.  This cmdlet requires that an explicit URI is entered and that the destination file name and location is specified as well
.PARAMETER URL
	Target location to download a specified file from a remote location.
.PARAMETER LocalFile
	Local destination to store targeted file.
.EXAMPLE
   Get-WebFile -URL http://www.contoso.com/targetfile.txt -LocalFile .\destinationfile.txt

   Downloads targetfile.txt and saves it to the current working directory as destinationfile.txt
.EXAMPLE
   Get-WebFile http://www.contoso.com/install.exe C:\Downloads\install.exe

   Downloads install.exe from contoso.com and save it with an absolute path of C:\Downloads
.LINK
   https://www.github.com/darkoperator/Posh-SecMod/
#>
 Function Get-WebFile
 {
     Param(
        [Parameter(Mandatory = $true)]
        [uri]$URL,

        [Parameter(Mandatory = $true)]
        $LocalFile
     )

    Begin
    {
        $WebClient = New-Object System.Net.WebClient
    }

    Process
    {
        try
        {
            Register-ObjectEvent $WebClient DownloadProgressChanged -action {

                Write-Progress -Activity "Downloading" -Status `
                    ("{0} of {1}" -f $eventargs.BytesReceived, $eventargs.TotalBytesToReceive) `
                    -PercentComplete $eventargs.ProgressPercentage
            }

            Register-ObjectEvent $client DownloadFileCompleted -SourceIdentifier Finished
            $WebClient.DownloadFileAsync($URL, $LocalFile)

            # optionally wait, but you can break out and it will still write progress
            Wait-Event -SourceIdentifier Finished

        }
        finally
        {
            $WebClient.dispose()
        }
    }
    End{}
}

function New-Zip
{
	[CmdletBinding()]
    Param
    (
	[Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
	$ZipFile
	)
	set-content $ZipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
	(dir $ZipFile).IsReadOnly = $false
}

function Add-Zip
{
	[CmdletBinding()]
    Param
    (
	[Parameter(Mandatory=$true)]
		$ZipFile,

		[Parameter(Mandatory=$true,
        ValueFromPipelineByPropertyName=$true,
        Position=1)]
        [ValidateScript({Test-Path $_})]
        [Alias("Name", "FullName")]
		$File

	)

    Begin
    {
	    if(-not (test-path($ZipFile)))
	    {
		    set-content $ZipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
		    (dir $ZipFile).IsReadOnly = $false
	    }
    }
    Process
    {
	    Write-Verbose $File
	    $shellApplication = new-object -com shell.application
	    $zipPackage = (new-object -com shell.application).NameSpace(((get-item $ZipFile).fullname))
	    $zipPackage.CopyHere((get-item $File).FullName)
    }
}

function Get-ZipChildItems_Recurse
{
    [CmdletBinding()]
	param(
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [object]$items
    )

    foreach($si in $items)
    {
        if($si.getfolder -ne $null)
        {
            Get-ZipChildItems_Recurse $si.getfolder.items()
        }
      $si | select path
      }
}

function Get-Zip
{
	[CmdletBinding()]
    Param
    (
	    [Parameter(Mandatory=$true,
        ValueFromPipelineByPropertyName=$true,
        Position=0)]
        [ValidateScript({Test-Path $_})]
		$ZipFile,
		$Recurse = $true
	)

	$shellApplication = new-object -com shell.application
	$zipPackage = $shellApplication.NameSpace(((get-item $ZipFile).fullname))
	if ($Recurse -eq $false)
	{
		$zipPackage.Items() | select path
	}
	else
	{
		Get-ZipChildItems_Recurse $zipPackage.Items()
	}
}

function Expand-Zip
{
	[CmdletBinding()]
    Param
    (
	    [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [ValidateScript({Test-Path $_})]
		$ZipFile,

	    [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
		$Destination
	)

	if (Test-Path -PathType Container $Destination)
	{
		$destinationFolder = $shellApplication.NameSpace(((get-item $Destination).fullname))
	}
	else
	{
		New-Item -ItemType container -Path $Destination | Out-Null
		$destinationFolder = $shellApplication.NameSpace(((get-item $Destination).fullname))
	}

	$shellApplication = new-object -com shell.application
	$zipPackage = $shellApplication.NameSpace(((get-item $ZipFile).fullname))
	$destinationFolder = $shellApplication.NameSpace(((get-item $Destination).fullname))
	$destinationFolder.CopyHere($zipPackage.Items())
}

<#
	.SYNOPSIS
		cmdlet for calculatingt the hash of a given file.

	.DESCRIPTION
		Calculates either the MD5, SHA1, SHA256, SHA384 or SHA512 checksum of a given file.

	.PARAMETER  File
		File to hash.

	.PARAMETER  HashAlgorithm
		Algorithum to use for hashing.  MD5, SHA1, SHA256, SHA384 or SHA512

	.EXAMPLE
		Get-ChildItem *.dll | Get-FileHash

#>
function Get-FileHash
{
	[CmdletBinding()]
	[OutputType([string])]
	param(
		[Parameter(Mandatory=$true,
        ValueFromPipelineByPropertyName=$true,
        Position=0)]
        [Alias("Name","FileName","FullName")]
        [ValidateScript({Test-Path $_})]
        $File,

		[ValidateSet("MD5", "SHA1", "SHA256", "SHA384", "SHA512")]
    	$HashAlgorithm = "MD5"
	)
	 Begin
    {

	}

	Process
	{

        if (Test-Path (resolve-path $File).Path -PathType Leaf)
        {
            Write-Verbose "Hashing $((resolve-path $File).Path)"
            $hashType = [Type] "System.Security.Cryptography.$HashAlgorithm"
		    $hasher = $hashType::Create()
		    $inputStream = New-Object IO.StreamReader ((resolve-path $File).Path)
    	    $hashBytes = $hasher.ComputeHash($inputStream.BaseStream)
    	    $inputStream.Close()

   		     # Convert the result to hexadecimal
    	    $builder = New-Object System.Text.StringBuilder
    	    $hashBytes | Foreach-Object -Process { [void] $builder.Append($_.ToString("X2")) }
		    # Create Object
    	    $output = New-Object PsObject -Property @{
        		    Path = (resolve-path $file).path;
        		    HashAlgorithm = $hashAlgorithm;
        		    HashValue = $builder.ToString()
	   		    }
            $output
        }
	}
	End
	{

	}
}

<#
.Synopsis
   Updateds to the latest version the Sysinternals Tool Suite
.DESCRIPTION
   Updates to the latest version the Sysinternals Tool Suite the files
   located in a given path using WebDav to connect to the Microsoft Servers.
   If the Path does not exists it will create the folder and download
   the tools if the force parameter is used.
.EXAMPLE
   PS C:\> Update-SysinternalsTools -Path C:\SysinternalsSuite -Verbose

   Updates the to the latest version the tools in a given path

.EXAMPLE
   PS C:\> Update-SysinternalsTools -Path C:\SysinternalsSuite -Verbose -Force

   Updates the to the latest version the tools in a given path and if the path
   does not exists it will create it.
#>
function Update-SysinternalsTools
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Path to where update the tools
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$Path,

        # Creates the directory for the tools if it does not exist.
        [Parameter(Mandatory=$false)]
        [switch]$Force

    )

    Begin
    {
        $WebPath = "\\live.sysinternals.com\Tools"
        # Check if the folder exists and if we should create it before starting.
        if ((Test-Path $Path) -eq $false)
        {
            if ($Force -eq $true)
            {
                Write-Verbose "Creating folder $($Path)"
                New-Item $Path -type directory | out-null
            }
            else
            {
                Write-Error "Path $($Path) does not exist."
                return
            }
        }
        $files = Get-ChildItem -Path $WebPath -File
    }
    Process
    {
        if (Test-Path $Path)
        {
            Write-Verbose "Folder exists, collecting information of files on host."
            $filesonhost = @{}
            foreach ($tool in (Get-ChildItem -Path $Path -File))
            {
                $filesonhost += @{$tool.name = $tool.CreationTime}
            }

            foreach ($file in $files)
            {
                if ($file.CreationTime -gt $filesonhost[$file.Name])
                {
                    Write-Verbose "$($file.Name) is newer."
                    Write-Verbose "Downloading $($file.Name)"
                    Copy-Item -Path $file.FullName -Destination "$($Path)\$($file.Name)"
                }
                else
                {
                    write-verbose "$($file.name) is up to date."
                }
            }
        }
        else
        {

            foreach ($file in $files)
            {
                Write-Verbose "Downloading $($file.Name)"
                Copy-Item -Path $file.FullName -Destination  "$($Path)\$($file.Name)"
            }

        }
    }
    End
    {
    }
}

<#
.Synopsis
   Gets a list of the COM Objects Available on the local system.
.DESCRIPTION
   Gets a list of the COM Objects Available on the local system.
.NOTES
    http://www.powershellmagazine.com/2013/06/27/pstip-get-a-list-of-all-com-objects-available/
#>

function Get-ComObject {

    param(
        [Parameter(Position=0)]
        [string]$Filter = "*"
    )

    $ListofObjects = Get-ChildItem HKLM:\Software\Classes -ErrorAction SilentlyContinue | Where-Object {
        $_.PSChildName -match '^\w+\.\w+$' -and (Test-Path -Path "$($_.PSPath)\CLSID")
    } | Select-Object -ExpandProperty PSChildName

    $ListofObjects | Where-Object {$_ -like $Filter}
}

 <#
 .Synopsis
    Gets the current installed version and the latest version of Posh-SecMod.
 .DESCRIPTION
    Gets the current installed version and the latest version of Posh-SecMod.
 .EXAMPLE
     Get-PoshSecModVersion

InstalledVersion                                                                                CurrentVersion
----------------                                                                                --------------
1.1                                                                                1.1

 #>
 function Get-PoshSecModVersion
 {
     [CmdletBinding()]
     [OutputType([pscustomobject])]
     Param
     ()

     Begin
     {
        $currentversion = ""
        $installed = Get-Module -Name "posh-secmod" -ListAvailable
     }
     Process
     {
        $webClient = New-Object System.Net.WebClient
        Try
        {
            $current = Invoke-Expression  $webClient.DownloadString('https://raw.github.com/darkoperator/Posh-SecMod/master/Posh-SecMod.psd1')
            $currentversion = $current.moduleversion
        }
        Catch
        {
            Write-Warning "Could not retrieve the current version."
        }
        $majorver,$minorver = $currentversion.split(".")

        if ($majorver -gt $installed.Version.Major)
        {
            Write-Warning "You are running an outdated version of the module."
        }
        elseif ($minorver -gt $installed.Version.Minor)
        {
            Write-Warning "You are running an outdated version of the module."
        }

        $props = @{
            InstalledVersion = $installed.Version.ToString()
            CurrentVersion   = $currentversion
        }
        New-Object -TypeName psobject -Property $props
     }
     End
     {

     }
 }


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Lagenidium papillosum Cocc., 1894

### Remarks
null


text:
#include "misc.hpp"
#include "../addr.hpp"
namespace libm2 {

    int get_global_time() {
        return ((int(*)(void))Addr::misc::get_global_time)();
    }

    const char* locale_find(const char* data) {
        return ((const char* (*)(const char*))Addr::misc::locale_find)(data);
    }

    const char* two_arguments(const char * src, char * one, size_t size_one, char * two, size_t size_two) {
        return ((const char *(*)(const char *, char *, size_t, char *, size_t))Addr::misc::two_arguments)(src, one, size_one, two, size_two);
    }

    DWORD thecore_random() {
        return ((DWORD(*)(void))Addr::misc::thecore_random)();
    }

    int number_ex(int from, int to, const char* file, int line) {
        return ((int(*)(int, int, const char*, int))Addr::misc::number_ex)(from, to, file, line);
    }

    void sys_err(const char *func, int line, const char *format, ...) {
        va_list args;
        va_start(args, format);
        char buffer[1024];
        vsnprintf(buffer, 1024, format, args);
        ((void(*)(const char*, int, const char*))Addr::misc::sys_err)(func, line, buffer);
        va_end(args);
    }

    void sys_log(unsigned int bit, char const* format, ...) {
        va_list args;
        va_start(args, format);
        char buffer[1024];
        vsnprintf(buffer, 1024, format, args);
        ((void(*)(unsigned int, char const*))Addr::misc::sys_log)(bit, buffer);
        va_end(args);
    }

    long long MIN(long long val, long long val2) {
        if (val > val2) {
            return val2;
        }
        return val;
    }

    long long MINMAX(long long min, long long val, long long max) {
        if (val < min) {
            return min;
        }
        if (val > max) {
            return max;
        }
        return val;
    }

    long long MAX(long long val, long long val2) {
        if (val > val2) {
            return val;
        }
        return val2;
    }

    void TransformRefineItem(LPITEM pkOldItem, LPITEM pkNewItem) {
        ((void(*)(CItem *, CItem *))Addr::misc::TransformRefineItem)(pkOldItem, pkNewItem);
    }

    void BroadcastNotice(const char * format, ...) {
        va_list args;
        va_start(args, format);
        char buffer[1024];
        vsnprintf(buffer, 1024, format, args);
        ((void(*)(const char*))Addr::misc::BroadcastNotice)(buffer);
        va_end(args);
    }

    void SendNotice(const char * format, ...) {
        va_list args;
        va_start(args, format);
        char buffer[1024];
        vsnprintf(buffer, 1024, format, args);
        ((void(*)(const char*))Addr::misc::SendNotice)(buffer);
        va_end(args);
    }

    bool IS_SUMMONABLE_ZONE(int map_index) {
        return ((bool(*)(int))Addr::misc::IS_SUMMONABLE_ZONE)(map_index);
    }
}


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using MatterHackers.Agg;
using MatterHackers.Agg.Platform;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.PrinterCommunication;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.MatterControl.SettingsManagement;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.VectorMath;
using Newtonsoft.Json;

namespace MatterHackers.MatterControl
{
	public class RootSystemWindow : SystemWindow
	{
		public static bool UseGl { get; set; } = true;
		private static Vector2 minSize { get; set; } = new Vector2(600, 480);

		private Stopwatch totalDrawTime = new Stopwatch();

		private AverageMillisecondTimer millisecondTimer = new AverageMillisecondTimer();

		public static bool ShowMemoryUsed = false;

		private int drawCount = 0;

		private bool exitDialogOpen = false;

		public RootSystemWindow(double width, double height)
			: base(width, height)
		{
			this.Name = "MatterControl";
			this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off
			this.AnchorAll();

			GuiWidget.DefaultEnforceIntegerBounds = true;

			// TODO: Needs review - doesn't seem like we want to scale on Touchscreen, rather we want device specific, configuration based scaling. Suggest remove
			if (UserSettings.Instance.IsTouchScreen)
			{
				// TODO: This steps on user scaling
				GuiWidget.DeviceScale = 1.3;
				SystemWindow.ShareSingleOsWindow = true;
			}

			string textSizeMode = UserSettings.Instance.get(UserSettingsKey.ApplicationTextSize);
			if (!string.IsNullOrEmpty(textSizeMode))
			{
				double textSize = 1.0;
				if (double.TryParse(textSizeMode, out textSize))
				{
					GuiWidget.DeviceScale = textSize;
				}
			}

			UseOpenGL = UseGl;

			this.SetStartupTraits();
		}

		public void SetStartupTraits()
		{
			string version = "2.0";

			this.MinimumSize = minSize;

			this.Title = $"MatterHackers: MatterControl {version}";
			if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0)
			{
				this.Title += $" - {OemSettings.Instance.WindowTitleExtra}";
			}

			this.Title += string.Format(" - {0}Bit", IntPtr.Size == 4 ? 32 : 64);

			string desktopPosition = ApplicationSettings.Instance.get(ApplicationSettingsKey.DesktopPosition);
			if (!string.IsNullOrEmpty(desktopPosition))
			{
				string[] sizes = desktopPosition.Split(',');

				//If the desktop position is less than -10,-10, override
				int xpos = Math.Max(int.Parse(sizes[0]), -10);
				int ypos = Math.Max(int.Parse(sizes[1]), -10);

				this.DesktopPosition = new Point2D(xpos, ypos);
			}
			else
			{
				this.DesktopPosition = new Point2D(-1, -1);
			}

			this.Maximized = ApplicationSettings.Instance.get(ApplicationSettingsKey.MainWindowMaximized) == "true";
		}

		public static (int width, int height) GetStartupBounds(int overrideWidth = -1, int overrideHeight = -1)
		{
			int width = 0;
			int height = 0;
			if (UserSettings.Instance.IsTouchScreen)
			{
				minSize = new Vector2(800, 480);
			}

			// check if the app has a size already set
			string windowSize = ApplicationSettings.Instance.get(ApplicationSettingsKey.WindowSize);
			if (windowSize != null && windowSize != "")
			{
				// try and open our window matching the last size that we had for it.
				string[] sizes = windowSize.Split(',');

				width = Math.Max(int.Parse(sizes[0]), (int)minSize.X + 1);
				height = Math.Max(int.Parse(sizes[1]), (int)minSize.Y + 1);
			}
			else // try to set it to a big size or the min size
			{
				Point2D desktopSize = AggContext.DesktopSize;

				if (overrideWidth != -1)
				{
					width = overrideWidth;
				}
				else // try to set it to a good size
				{
					if (width < desktopSize.x)
					{
						width = 1280;
					}
				}

				if (overrideHeight != -1)
				{
					// Height should be constrained to actual
					height = Math.Min(overrideHeight, desktopSize.y);
				}
				else
				{
					if (height < desktopSize.y)
					{
						height = 720;
					}
				}
			}

			return (width, height);
		}

		public override void OnDraw(Graphics2D graphics2D)
		{
			totalDrawTime.Restart();
			GuiWidget.DrawCount = 0;
			using (new PerformanceTimer("Draw Timer", "MC Draw"))
			{
				base.OnDraw(graphics2D);
			}
			totalDrawTime.Stop();

			millisecondTimer.Update((int)totalDrawTime.ElapsedMilliseconds);

			if (ShowMemoryUsed)
			{
				long memory = GC.GetTotalMemory(false);
				this.Title = $"Allocated = {memory:n0} : {millisecondTimer.GetAverage()}ms, d{drawCount++} Size = {this.Width}x{this.Height}, onIdle = {UiThread.CountExpired}:{UiThread.Count}, widgetsDrawn = {GuiWidget.DrawCount}";
			}

			//msGraph.AddData("ms", totalDrawTime.ElapsedMilliseconds);
			//msGraph.Draw(MatterHackers.Agg.Transform.Affine.NewIdentity(), graphics2D);
		}

		public override void OnClosing(ClosingEventArgs eventArgs)
		{
			if (this.HasBeenClosed)
			{
				return;
			}

			// save the last size of the window so we can restore it next time.
			ApplicationSettings.Instance.set(ApplicationSettingsKey.MainWindowMaximized, this.Maximized.ToString().ToLower());

			if (!this.Maximized)
			{
				ApplicationSettings.Instance.set(ApplicationSettingsKey.WindowSize, string.Format("{0},{1}", Width, Height));
				ApplicationSettings.Instance.set(ApplicationSettingsKey.DesktopPosition, string.Format("{0},{1}", DesktopPosition.x, DesktopPosition.y));
			}

			//Save a snapshot of the prints in queue
			QueueData.Instance.SaveDefaultQueue();

			// If we are waiting for a response and get another request, just cancel the close until we get a response.
			if (exitDialogOpen)
			{
				eventArgs.Cancel = true;
			}

			string caption = null;
			string message = null;

			if (!ApplicationController.Instance.ApplicationExiting
				&& !exitDialogOpen)
			{
				int printingCount = 0;
				int sdPrinting = 0;
				foreach (var printer in ApplicationController.Instance.ActivePrinters)
				{
					if (printer.Connection.Printing)
					{
						if (printer.Connection.CommunicationState == CommunicationStates.PrintingFromSd)
						{
							sdPrinting++;
						}
						printingCount++;
					}
				}

				if (sdPrinting > 0)
				{
					caption = "Exit while printing".Localize();
					message = "Are you sure you want to exit while a print is running from SD Card?\n\nNote: If you exit, it is recommended you wait until the print is completed before running MatterControl again.".Localize();
				}
				else if (printingCount > 0)
				{
					caption = "Abort Print".Localize();
					message = "Are you sure you want to abort the current print and close MatterControl?".Localize();
				}
			}

			if (caption != null)
			{
				// Record that we are waiting for a response to the request to close
				exitDialogOpen = true;

				// We need to show an interactive dialog to determine if the original Close request should be honored, thus cancel the current Close request
				eventArgs.Cancel = true;

				UiThread.RunOnIdle(() =>
				{
					StyledMessageBox.ShowMessageBox(
						(exitConfirmed) =>
						{
							// Record that the exitDialog has closed
							exitDialogOpen = false;

							// Continue with the original shutdown request if exit confirmed by user
							if (exitConfirmed)
							{
								ApplicationController.Instance.ApplicationExiting = true;
								ApplicationController.Instance.Shutdown();

								foreach (var printer in ApplicationController.Instance.ActivePrinters)
								{
									// the will shutdown any active (and non-sd) prints that are running
									printer.Connection.Disable();
								}

								this.CloseOnIdle();
							}
						},
						message,
						caption,
						StyledMessageBox.MessageType.YES_NO_WITHOUT_HIGHLIGHT);
				});
			}
			else if (!ApplicationController.Instance.ApplicationExiting)
			{
				// cancel the close so that we can save all our active work spaces
				eventArgs.Cancel = true;

				UiThread.RunOnIdle(async () =>
				{
					var application = ApplicationController.Instance;

					await application.PersistUserTabs();

					application.ApplicationExiting = true;

					// Make sure we tell the Application Controller to shut down. This will release the slicing thread if running.
					application.Shutdown();

					this.CloseOnIdle();
				});
			}
		}

		public override void OnClosed(EventArgs e)
		{
			UserSettings.Instance.Fields.StartCountDurringExit = UserSettings.Instance.Fields.StartCount;

			foreach (var printer in ApplicationController.Instance.ActivePrinters)
			{
				printer.Connection.Disable();
				//Close connection to the local datastore
				printer.Connection.HaltConnectionThread();
			}

			ApplicationController.Instance.OnApplicationClosed();

			Datastore.Instance.Exit();

			base.OnClosed(e);
		}

		public override void OnMouseMove(MouseEventArgs mouseEvent)
		{
			// run this first to make sure a child has the chance to take the drag drop event
			base.OnMouseMove(mouseEvent);

			if (!mouseEvent.AcceptDrop && mouseEvent.DragFiles != null)
			{
				// no child has accepted the drop
				foreach (string file in mouseEvent.DragFiles)
				{
					string extension = Path.GetExtension(file).ToUpper();
					if ((extension != "" && ApplicationSettings.ValidFileExtensions.Contains(extension))
						|| extension == ".GCODE"
						|| extension == ".ZIP")
					{
						//mouseEvent.AcceptDrop = true;
					}
				}
			}

			if (GuiWidget.DebugBoundsUnderMouse)
			{
				Invalidate();
			}
		}
	}
}


text:
package com.mursaat.zelda.tiles;

import com.badlogic.gdx.graphics.g2d.Animation;

import java.util.HashMap;

/**
 * @author Mursaat
 * La liste des tiles enregistrés et initialisés au lancement du jeu
 */
public class Tiles
{
    private static int currentId = 0;

    public static Tile herbe;
    public static Tile hautes_herbes;
    public static Tile terre;
    public static Tile buisson;
    public static Tile arbrisseau;
    public static Tile cailloux;
    public static Tile graviers;
    public static Tile fleurs;

    //  Maison
    public static Tile maisonFenetre;
    public static Tile maisonPorte;
    public static Tile toitBleuInfDroit;
    public static Tile toitBleuInfMid;
    public static Tile toitBleuInfGauche;
    public static Tile toitBleuSupDroit;
    public static Tile toitBleuSupMid;
    public static Tile toitBleuSupGauche;

    private static HashMap<Integer, Tile> tiles = new HashMap<Integer, Tile>();

    public static void registerTiles()
    {
        herbe = new Tile("herbe", currentId++);
        hautes_herbes = new Tile("hautes_herbes", currentId++);
        terre = new Tile("terre", currentId++);
        buisson = new Tile("buisson", currentId++);
        arbrisseau = new Tile("arbrisseau", currentId++);
        cailloux = new Tile("cailloux", currentId++);
        graviers = new Tile("graviers", currentId++);
        fleurs = new AnimatedTile("fleurs", currentId++, 0.25f, Animation.PlayMode.LOOP);

        tiles.put(herbe.getId(), herbe);
        tiles.put(hautes_herbes.getId(), hautes_herbes);
        tiles.put(terre.getId(), terre);
        tiles.put(buisson.getId(), buisson);
        tiles.put(arbrisseau.getId(), arbrisseau);
        tiles.put(cailloux.getId(), cailloux);
        tiles.put(graviers.getId(), graviers);
        tiles.put(fleurs.getId(), fleurs);
    }

    public static Tile getTile(int id)
    {
        return tiles.get(id);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace com.andymark.crosslink
{
    /// <summary>
    /// Represents a relay output on the CANipede Robot Control Module.
    /// </summary>
    public class Relay
    {
        private Canipede canipede;
        private int channel;

        /// <summary>
        /// Initializes a new instance of the Relay class for the specified CANipede and relay channel.
        /// </summary>
        /// <param name="canipede">A reference to a Canipede instance</param>
        /// <param name="channel">The relay channel used (1-4).</param>
        public Relay(Canipede canipede, int channel)
        {
            this.canipede = canipede;
            this.channel = channel;
        }

        /// <summary>
        /// The state of the relay output.
        /// </summary>
        public RelayState State
        {
            set
            {
                canipede.SetRelayValue(channel, value);
            }
        }
    }

    /// <summary>
    /// Represents the state of a relay output.
    /// </summary>
    public enum RelayState
    {
        /// <summary>
        /// The relay is OFF, or braked.  Both the A and B outputs are LOW.
        /// </summary>
        Neutral,
        /// <summary>
        /// Runs a connected motor "forward."  The A output is HIGH and the B output is LOW.
        /// </summary>
        Forward,
        /// <summary>
        /// Runs a connected motor "backward."  The A output is LOW and the B output is HIGH.
        /// </summary>
        Reverse
    }
}


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var TF;
(function (TF) {
    var Backend;
    (function (Backend) {
        /**
         * Manages many fetch requests. Launches up to nSimultaneousRequests
         * simultaneously, and maintains a LIFO queue of requests to process when
         * more urls are requested than can be handled at once. The queue can be
         * cleared.
         *
         * When a request is made, a Promise is returned which resolves with the
         * parsed JSON result from the request.
         */
        var RequestCancellationError = (function (_super) {
            __extends(RequestCancellationError, _super);
            function RequestCancellationError() {
                var _this = _super !== null && _super.apply(this, arguments) || this;
                _this.name = 'RequestCancellationError';
                return _this;
            }
            return RequestCancellationError;
        }(Error));
        Backend.RequestCancellationError = RequestCancellationError;
        var RequestNetworkError = (function (_super) {
            __extends(RequestNetworkError, _super);
            function RequestNetworkError(req, url) {
                var _this = _super.call(this) || this;
                _this.message = "RequestNetworkError: " + req.status + " at " + url;
                _this.name = 'RequestNetworkError';
                _this.req = req;
                _this.url = url;
                return _this;
            }
            return RequestNetworkError;
        }(Error));
        Backend.RequestNetworkError = RequestNetworkError;
        var RequestManager = (function () {
            function RequestManager(nSimultaneousRequests, maxRetries) {
                if (nSimultaneousRequests === void 0) { nSimultaneousRequests = 10; }
                if (maxRetries === void 0) { maxRetries = 3; }
                this._queue = [];
                this._nActiveRequests = 0;
                this._nSimultaneousRequests = nSimultaneousRequests;
                this._maxRetries = maxRetries;
            }
            /**
             * Gives a promise that loads assets from given url (respects queuing). If
             * postData is provided, this request will use POST, not GET. This is an
             * object mapping POST keys to string values.
             */
            RequestManager.prototype.request = function (url, postData) {
                var _this = this;
                var promise = new Promise(function (resolve, reject) {
                    var resolver = { resolve: resolve, reject: reject };
                    _this._queue.push(resolver);
                    _this.launchRequests();
                })
                    .then(function () {
                    return _this.promiseWithRetries(url, _this._maxRetries, postData);
                })
                    .then(function (response) {
                    // Success - Let's free space for another active
                    // reqest, and launch it
                    _this._nActiveRequests--;
                    _this.launchRequests();
                    return response;
                }, function (rejection) {
                    if (rejection.name === 'RequestNetworkError') {
                        // If we failed due to network error, we should
                        // decrement
                        // _nActiveRequests because this request was
                        // active
                        _this._nActiveRequests--;
                        _this.launchRequests();
                    }
                    return Promise.reject(rejection);
                });
                return promise;
            };
            RequestManager.prototype.clearQueue = function () {
                while (this._queue.length > 0) {
                    this._queue.pop().reject(new RequestCancellationError('Request cancelled by clearQueue'));
                }
            };
            /* Return number of currently pending requests */
            RequestManager.prototype.activeRequests = function () {
                return this._nActiveRequests;
            };
            /* Return total number of outstanding requests (includes queue) */
            RequestManager.prototype.outstandingRequests = function () {
                return this._nActiveRequests + this._queue.length;
            };
            RequestManager.prototype.launchRequests = function () {
                while (this._nActiveRequests < this._nSimultaneousRequests &&
                    this._queue.length > 0) {
                    this._nActiveRequests++;
                    this._queue.pop().resolve();
                }
            };
            /**
             * Try to request a given URL using overwritable _promiseFromUrl method.
             * If the request fails for any reason, we will retry up to maxRetries
             * times. In practice, this will help us paper over transient network issues
             * like '502 Bad Gateway'.
             * By default, Chrome displays network errors in console, so
             * the user will be able to tell when the requests are failing. I think this
             * is a feature, if the request failures and retries are causing any
             * pain to users, they can see it and file issues.
             */
            RequestManager.prototype.promiseWithRetries = function (url, maxRetries, postData) {
                var _this = this;
                var success = function (x) { return x; };
                var failure = function (x) {
                    if (maxRetries > 0) {
                        return _this.promiseWithRetries(url, maxRetries - 1, postData);
                    }
                    else {
                        return Promise.reject(x);
                    }
                };
                return this._promiseFromUrl(url, postData).then(success, failure);
            };
            /* Actually get promise from url using XMLHttpRequest */
            RequestManager.prototype._promiseFromUrl = function (url, postData) {
                return new Promise(function (resolve, reject) {
                    var req = new XMLHttpRequest();
                    req.open(postData ? 'POST' : 'GET', url);
                    var formData;
                    if (postData) {
                        // We are to make a POST request.
                        formData = new FormData();
                        for (var postKey in postData) {
                            if (postKey) {
                                // The linter requires 'for in' loops to be filtered by an if
                                // condition.
                                formData.append(postKey, postData[postKey]);
                            }
                        }
                    }
                    req.onload = function () {
                        if (req.status === 200) {
                            resolve(JSON.parse(req.responseText));
                        }
                        else {
                            reject(new RequestNetworkError(req, url));
                        }
                    };
                    req.onerror = function () {
                        reject(new RequestNetworkError(req, url));
                    };
                    req.send(formData);
                });
            };
            return RequestManager;
        }());
        Backend.RequestManager = RequestManager;
    })(Backend = TF.Backend || (TF.Backend = {}));
})(TF || (TF = {}));


text:
package moe.feng.bilinyan.util;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import static moe.feng.bilinyan.BuildConfig.DEBUG;

public abstract class AsyncTask<Params, Progress, Result>
{
	private static final String TAG = AsyncTask.class.getSimpleName();

	private static class AsyncResult<Data> {
		public AsyncTask task;
		public Data[] data;

		public AsyncResult(AsyncTask task, Data... data) {
			this.task = task;
			this.data = data;
		}
	}

	private static final int MSG_FINISH = 1000;
	private static final int MSG_PROGRESS = 1001;

	private static Handler sInternalHandler = new Handler() {
		@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
		@Override
		public void handleMessage(Message msg) {
			AsyncResult result = (AsyncResult) msg.obj;
			switch (msg.what) {
				case MSG_FINISH:
					result.task.onPostExecute(result.data[0]);
					break;
				case MSG_PROGRESS:
					result.task.onProgressUpdate(result.data);
					break;
			}
		}
	};

	private Params[] mParams;

	private Thread mThread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO: CrashHandler.register();

				try {
					Result result = doInBackground(mParams);
					sInternalHandler.sendMessage(sInternalHandler.obtainMessage(MSG_FINISH, new AsyncResult<Result>(AsyncTask.this, result)));
				} catch (Exception e) {
					// Don't crash the whole app
					if (DEBUG) {
						Log.d(TAG, e.getClass().getSimpleName() + " caught when running background task. Printing stack trace.");
						Log.d(TAG, Log.getStackTraceString(e));
					}
				}

				Thread.currentThread().interrupt();
			}
		});

	protected void onPostExecute(Result result) {}

	protected abstract Result doInBackground(Params... params);

	protected void onPreExecute() {}

	protected void onProgressUpdate(Progress... progress) {}

	protected void publishProgress(Progress... progress) {
		sInternalHandler.sendMessage(sInternalHandler.obtainMessage(MSG_PROGRESS, new AsyncResult<Progress>(this, progress)));
	}

	public void execute(Params... params) {
		onPreExecute();
		mParams = params;
		mThread.start();
	}
}


text:
using System;
using System.Collections.ObjectModel;
using System.Linq;
using TestCommon.Mocks;
using Xunit;

namespace GenFx.Tests
{
    /// <summary>
    ///This is a test class for GenFx.GeneticEntityCollection and is intended
    ///to contain all GenFx.GeneticEntityCollection Unit Tests
    ///</summary>
    public class EntityCollectionTest
    {
        /// <summary>
        /// Tests that the SortByFitness method works correctly.
        /// </summary>
        [Fact]
        public void EntityCollection_SortByFitness()
        {
            ObservableCollection<GeneticEntity> geneticEntities = new ObservableCollection<GeneticEntity>();
            MockGeneticAlgorithm algorithm = new MockGeneticAlgorithm
            {
                SelectionOperator = new MockSelectionOperator(),
                FitnessEvaluator = new MockFitnessEvaluator(),
                PopulationSeed = new MockPopulation(),
                GeneticEntitySeed = new MockEntity()
            };

            for (int i = 9; i >= 0; i--)
            {
                MockEntity entity = new MockEntity();
                entity.Initialize(algorithm);
                entity.ScaledFitnessValue = Convert.ToDouble(i);
                geneticEntities.Add(entity);
            }

            GeneticEntity[] sortedEntities = geneticEntities.GetEntitiesSortedByFitness(FitnessType.Scaled, FitnessEvaluationMode.Maximize).ToArray();
            for (int i = 0; i < 10; i++)
            {
                Assert.Equal(Convert.ToDouble(i), sortedEntities[i].ScaledFitnessValue);
            }

            sortedEntities = geneticEntities.GetEntitiesSortedByFitness(FitnessType.Scaled, FitnessEvaluationMode.Minimize).ToArray();
            int entityIndex = 0;
            for (int i = 9; i >= 0; i--)
            {
                Assert.Equal(Convert.ToDouble(i), sortedEntities[entityIndex].ScaledFitnessValue);
                entityIndex++;
            }
        }
    }
}


text:
Mybatis Generator 自动生成 mapper 的 xml 和接口实体.

# 2.Support

- MySQL

# 3.Getting started

1、配置 resources/config.properties 中的数据库相关配置项

2、配置 resources/generatorConfig.xml 中的表信息

```xml
<!-- 指定数据库表 shema:数据库名 tableName:表名 -->
<table schema="" tableName="mall_content"/>
<table schema="" tableName="mall_content_category"/>
```

3、使用 mvn mybatis-generator:generate 命令生成代码


text:
'use strict';

angular.module('core').controller('HomeController',
['$scope', '$location', '$controller', '$timeout', '$q', 'Personals', 'ApptTypes', 'prsnlService',
  function ($scope, $location, $controller, $timeout, $q, Personals, ApptTypes, prsnlService) {

    $scope.go = function ( path ) {
        $location.path( path );
    };

    $scope.nextPage = function ( ) {

        prsnlService.addDentist(prsnl.selectedPrsnl);
        prsnlService.addTreatment(appt.selectedAppt);

        if(prsnl.selectedPrsnl && appt.selectedAppt){
            $location.path('/booklast');
             }else{
              alert('Please select both Treatment & Doctor');
            }
    };

    $scope.data = {
      selectedIndex: 0,
      bottom: false
    };

    /**
     * Search for personals... use $timeout to simulate
     * remote dataservice call.
     */
    function queryPrsnlSearch (query) {
      var results = query ? prsnl.personals.filter( createFilterFor(query) ) : prsnl.personals;
      var deferred = $q.defer();
      $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
      return deferred.promise;
    }

    /**
     * Create filter function for a query string
     */
    function createFilterFor(query) {
      var lowercaseQuery = angular.lowercase(query);
      return function filterFn(personal) {
        return (angular.lowercase(personal.fName).indexOf(lowercaseQuery) === 0);
      };
    }

    function selectedPrsnlChange(item) {

      if (item){
          appt.apptTypes = item.treatments;
      }
      else
        appt.apptTypes = ApptTypes.query();
    }

    var prsnl = this;

    prsnl.personals     = Personals.query();
    prsnl.personalsAll = prsnl.personals;
    prsnl.selectedPrsnl  = null;
    prsnl.searchPrsnl    = null;
    prsnl.simulateQuery = false;
    prsnl.isDisabled    = false;
    prsnl.queryPrsnlSearch   = queryPrsnlSearch;
    prsnl.selectedPrsnlChange = selectedPrsnlChange;

    /**
     * Search for Appts... use $timeout to simulate
     * remote dataservice call.
     */
    function queryApptSearch (query) {
      var results = query ? appt.apptTypes.filter( createFilterForAppt(query) ) : appt.apptTypes;
      var deferred = $q.defer();
      $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
      return deferred.promise;
    }

    /**
     * Create filter function for a query string
     */
    function createFilterForAppt(query) {
      var lowercaseQuery = angular.lowercase(query);
      return function filterFn(apptType) {
        return (angular.lowercase(apptType.description).indexOf(lowercaseQuery) === 0);
      };
    }

    function selectedApptChange(item) {

      if(item)
        prsnl.personals = queryPrsnlSearchBy (item.description);
      else
        prsnl.personals = Personals.query();

    }

    /**
     * Search for personals... use $timeout to simulate
     * remote dataservice call.
     */
    function queryPrsnlSearchBy (query) {
      var results = query ? prsnl.personalsAll.filter( createFilterByTreatment(query) ) : prsnl.personalsAll;
      var deferred = $q.defer();
      $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
      return deferred.promise;
    }

    /**
     * Create filter function for a query string
     */
    function createFilterByTreatment (query) {

      return function filterFn(personal) {
          if(personal)
          {
              var result = false;
              angular.forEach(personal.treatments, function(value, key){
                 if (value.description.indexOf(query) === 0)
                 {
                     result = true;
                 }
              });
              return result;
          }
      };
    }

    var appt = this;
    // list of `state` value/display objects
    appt.apptTypes     = ApptTypes.query();
    appt.selectedAppt  = null;
    appt.searchAppt    = null;
    appt.queryApptSearch   = queryApptSearch;
    appt.selectedApptChange = selectedApptChange;

  }
]);


text:
package androidx.test.runner.suites;

import static androidx.test.internal.runner.ClassPathScanner.getDefaultClasspaths;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;

import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;
import androidx.test.internal.runner.ClassPathScanner;
import androidx.test.internal.runner.ErrorReportingRunner;
import androidx.test.internal.runner.TestLoader;
import androidx.test.runner.suites.AndroidClasspathSuite.RunnerSuite;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.runner.RunWith;
import org.junit.runner.Runner;
import org.junit.runners.Suite;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerBuilder;

/**
 * Test suite that finds all JUnit3 and JUnit4 test classes in the instrumentation context apk.
 *
 * <p>This is intended to replicate the legacy AndroidJUnitRunner behavior of discovering and
 * running all tests when no '-e class' option is specified. e.g. the following AJUR invocations are
 * equivalent
 *
 * <p>'adb shell am instrument mypkg/androidx.test.runner.AndroidJUnitRunner' 'adb shell am
 * instrument -e class androidx.test.runner.suites.AndroidClasspathSuite
 * mypkg/androidx.test.runner.AndroidJUnitRunner'
 */
@RunWith(RunnerSuite.class)
public final class AndroidClasspathSuite {

  /**
   * Only called reflectively. Do not use programmatically.
   *
   * @hide
   */
  @RestrictTo(Scope.LIBRARY)
  public AndroidClasspathSuite() {}

  /**
   * Internal suite class that performs the work of class path scanning.
   *
   * @hide
   */
  @RestrictTo(Scope.LIBRARY)
  public static class RunnerSuite extends Suite {

    /**
     * Only called reflectively. Do not use programmatically.
     *
     * @hide
     */
    @RestrictTo(Scope.LIBRARY)
    public RunnerSuite(Class<?> klass, RunnerBuilder builder) throws InitializationError {
      super(klass, getRunnersForClasses(builder));
    }

    private static List<Runner> getRunnersForClasses(RunnerBuilder builder) {
      try {
        Collection<String> classNames =
            new ClassPathScanner(getDefaultClasspaths(getInstrumentation())).getClassPathEntries();
        return TestLoader.Factory.create(null, builder, true).getRunnersFor(classNames);
      } catch (IOException e) {
        return Arrays.asList(
            new ErrorReportingRunner(
                getInstrumentation().getContext().getPackageName(),
                new RuntimeException(
                    "Failed to perform classpath scanning to determine tests to run", e)));
      }
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NearForums.DataAccess;
using NearForums.Dto;
using NearForums.Configuration;

namespace NearForums.Services
{
	public class SearchIndexBatchService : ISearchIndexBatchService
	{
		/// <summary>
		/// Topics repository
		/// </summary>
		private readonly IForumsService _forumsService;
		/// <summary>
		/// Forums repository
		/// </summary>
		private readonly ITopicsService _topicsService;
		/// <summary>
		/// Represents the service that performs the index of documents
		/// </summary>
		private readonly ISearchService _searchService;

		public SearchIndexBatchService(IForumsService forumsService, ISearchService searchService, ITopicsService topicsService)
		{
			_searchService = searchService;
			_topicsService = topicsService;
			_forumsService = forumsService;
		}

		public List<ForumDto> GetForums()
		{
			var categories = _forumsService.GetList(null);
			var forums = categories.SelectMany<ForumCategory, Forum>(category => category.Forums).ToList();
			return forums.Select<Forum, ForumDto>(f => new ForumDto(f)).ToList();
		}

		public int IndexBatch(int forumId, int index)
		{
			var config = SiteConfiguration.Current.Search;
			var topics = _topicsService.GetByForum(forumId, index, config.IndexBatchSize, null);
			var topicsAndMessages = new List<Topic>();
			foreach (var t in topics)
			{
				//Get the complete topic information: topic fields and messages
				var completeTopic = _topicsService.GetWithMessages(t.Id, 0, config.MaxMessages);
				topicsAndMessages.Add(completeTopic);
			}
			_searchService.Add(topicsAndMessages);
			//Return the number of topics indexed
			return topicsAndMessages.Count;
		}
	}
}


text:
package org.apache.ignite.internal.processors.cache.multijvm;

import org.apache.ignite.internal.processors.cache.distributed.replicated.*;

/**
 * Multi-JVM tests.
 */
public class GridCacheReplicatedOffHeapTieredMultiJvmFullApiSelfTest
    extends GridCacheReplicatedOffHeapTieredMultiNodeFullApiSelfTest {
    /** {@inheritDoc} */
    protected boolean isMultiJvm() {
        return true;
    }

    /** {@inheritDoc} */
    @Override public void testLocalClearKeys() throws Exception {
        fail("https://issues.apache.org/jira/browse/IGNITE-1107");
    }
}


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

import com.facebook.presto.Session;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.ConnectorTableMetadata;
import com.facebook.presto.spi.InMemoryRecordSet;
import com.facebook.presto.spi.InMemoryRecordSet.Builder;
import com.facebook.presto.spi.RecordCursor;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.TupleDomain;

import javax.inject.Inject;

import java.util.Optional;

import static com.facebook.presto.connector.system.jdbc.FilterUtil.filter;
import static com.facebook.presto.connector.system.jdbc.FilterUtil.toSession;
import static com.facebook.presto.metadata.MetadataUtil.TableMetadataBuilder.tableMetadataBuilder;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static java.util.Objects.requireNonNull;

public class SchemaJdbcTable
        extends JdbcTable
{
    public static final SchemaTableName NAME = new SchemaTableName("jdbc", "schemas");

    public static final ConnectorTableMetadata METADATA = tableMetadataBuilder(NAME)
            .column("table_schem", VARCHAR)
            .column("table_catalog", VARCHAR)
            .build();

    private final Metadata metadata;

    @Inject
    public SchemaJdbcTable(Metadata metadata)
    {
        this.metadata = requireNonNull(metadata);
    }

    @Override
    public ConnectorTableMetadata getTableMetadata()
    {
        return METADATA;
    }

    @Override
    public RecordCursor cursor(ConnectorSession connectorSession, TupleDomain<Integer> constraint)
    {
        Session session = toSession(connectorSession);
        Optional<String> catalogFilter = FilterUtil.stringFilter(constraint, 1);

        Builder table = InMemoryRecordSet.builder(METADATA);
        for (String catalog : filter(metadata.getCatalogNames().keySet(), catalogFilter)) {
            for (String schema : metadata.listSchemaNames(session, catalog)) {
                table.addRow(schema, catalog);
            }
        }
        return table.build().cursor();
    }
}


text:
a hegemonic system for algorithmic improvements to user-input language as text. often the domain of corporate entities who control the software algorithm.

enforces grammar and capitalization

orthography

linkz
-----

<https://en.wikipedia.org/wiki/Phonological_awareness>


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="../../../resources/js-test.js"></script>
</head>
<body>
<script>
description('Test setting the port attribute of the URL in HTMLAnchorElement.');

var a = document.createElement('a');

debug("Default port as number");
a.href = "https://www.mydomain.com:8080/path/testurl.html?key=value";
a.port = 443;
shouldBe("a.href", "'https://www.mydomain.com/path/testurl.html?key=value'");

debug("Default port as string");
a.href = "https://www.mydomain.com:8080/path/testurl.html?key=value";
a.port = "443";
shouldBe("a.href", "'https://www.mydomain.com/path/testurl.html?key=value'");

debug("Set port to 0");
a.href = "https://www.mydomain.com:8080/path/testurl.html?key=value";
a.port = "0";
shouldBe("a.href", "'https://www.mydomain.com:0/path/testurl.html?key=value'");

// Firefox 3.5.2 does not accept the port if any character is not a digit.
debug("Set port to non-number");
a.href = "https://www.mydomain.com:8080/path/testurl.html?key=value";
a.port = "4a";
shouldBe("a.href", "'https://www.mydomain.com:4/path/testurl.html?key=value'");

// Firefox 3.5.2 does not accept the port if it is null.
debug("Set port to null");
a.href = "https://www.mydomain.com:8080/path/testurl.html?key=value";
a.port = null;
shouldBe("a.href", "'https://www.mydomain.com:8080/path/testurl.html?key=value'");

// Firefox 3.5.2 does not accept the port if it is null.
debug("Set port to empty string");
a.href = "https://www.mydomain.com:8080/path/testurl.html?key=value";
a.port = "";
shouldBe("a.href", "'https://www.mydomain.com/path/testurl.html?key=value'");

debug("Set port to undefined");
a.href = "https://www.mydomain.com:8080/path/testurl.html?key=value";
a.port = undefined;
shouldBe("a.href", "'https://www.mydomain.com:8080/path/testurl.html?key=value'");

// Firefox 3.5.2 does not allow setting the port on a URL with protocol foo: .
debug("Set port to URL with foo: protocol");
a.href = "foo://bar/";
a.port = 50;
shouldBe("a.href", "'foo://bar:50/'");
</script>
</body>
</html>