text:
// Copyright 2017 The Bazel Authors. 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.

package com.google.devtools.build.lib.rules.platform;

import com.google.common.base.Preconditions;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.platform.ConstraintSettingInfo;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.NoSuchTargetException;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.skyframe.PackageValue;
import com.google.devtools.build.skyframe.SkyFunction;
import javax.annotation.Nullable;

/**
 * Defines a category of constraint that can be fulfilled by a constraint_value rule in a platform
 * definition.
 */
public class ConstraintSetting implements RuleConfiguredTargetFactory {

  @Override
  public ConfiguredTarget create(RuleContext ruleContext)
      throws InterruptedException, RuleErrorException, ActionConflictException {

    Label constraintSetting = ruleContext.getLabel();
    Label defaultConstraintValue =
        ruleContext
            .attributes()
            .get(ConstraintSettingRule.DEFAULT_CONSTRAINT_VALUE_ATTR, BuildType.NODEP_LABEL);

    validateDefaultConstraintValue(ruleContext, constraintSetting, defaultConstraintValue);

    return new RuleConfiguredTargetBuilder(ruleContext)
        .addProvider(RunfilesProvider.class, RunfilesProvider.EMPTY)
        .addProvider(FileProvider.class, FileProvider.EMPTY)
        .addProvider(FilesToRunProvider.class, FilesToRunProvider.EMPTY)
        .addNativeDeclaredProvider(
            ConstraintSettingInfo.create(constraintSetting, defaultConstraintValue))
        .build();
  }

  private void validateDefaultConstraintValue(
      RuleContext ruleContext, Label constraintSetting, @Nullable Label defaultConstraintValue)
      throws RuleErrorException, InterruptedException {
    if (defaultConstraintValue == null) {
      return;
    }

    // Make sure the default value is in the same package.
    if (!constraintSetting
        .getPackageIdentifier()
        .equals(defaultConstraintValue.getPackageIdentifier())) {
      throw ruleContext.throwWithAttributeError(
          ConstraintSettingRule.DEFAULT_CONSTRAINT_VALUE_ATTR,
          "The default constraint value must be defined in the same package "
              + "as the constraint setting itself.");
    }

    // Verify that the target actually exists, even though we cannot have a direct dependency
    // because it will cause a cycle.
    SkyFunction.Environment env = ruleContext.getAnalysisEnvironment().getSkyframeEnv();
    PackageValue packageNode =
        (PackageValue) env.getValue(PackageValue.key(constraintSetting.getPackageIdentifier()));
    Preconditions.checkNotNull(
        packageNode,
        "Package '%s' is the package for the current target, and so must have already been loaded.",
        defaultConstraintValue.getPackageIdentifier());
    Package pkg = packageNode.getPackage();
    try {
      pkg.getTarget(defaultConstraintValue.getName());
    } catch (NoSuchTargetException e) {
      throw ruleContext.throwWithAttributeError(
          ConstraintSettingRule.DEFAULT_CONSTRAINT_VALUE_ATTR,
          "The default constraint value '" + defaultConstraintValue + "' does not exist");
    }
  }
}


text:
package git4idea.ui;

import com.intellij.dvcs.DvcsUtil;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.committed.CommittedChangesTreeBrowser;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.table.TableView;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Consumer;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ListTableModel;
import com.intellij.util.ui.UIUtil;
import com.intellij.vcs.log.util.VcsUserUtil;
import git4idea.GitCommit;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * A table with the list of commits.
 *
 * @author Kirill Likhodedov
 */
public class GitCommitListPanel extends JPanel implements TypeSafeDataProvider {

  private final List<GitCommit> myCommits;
  private final TableView<GitCommit> myTable;

  public GitCommitListPanel(@NotNull List<GitCommit> commits, @Nullable String emptyText) {
    myCommits = commits;

    myTable = new TableView<GitCommit>();
    updateModel();
    myTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    myTable.setStriped(true);
    if (emptyText != null) {
      myTable.getEmptyText().setText(emptyText);
    }

    setLayout(new BorderLayout());
    add(ScrollPaneFactory.createScrollPane(myTable));
  }

  /**
   * Adds a listener that would be called once user selects a commit in the table.
   */
  public void addListSelectionListener(final @NotNull Consumer<GitCommit> listener) {
    myTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(final ListSelectionEvent e) {
        ListSelectionModel lsm = (ListSelectionModel)e.getSource();
        int i = lsm.getMaxSelectionIndex();
        int j = lsm.getMinSelectionIndex();
        if (i >= 0 && i == j) {
          listener.consume(myCommits.get(i));
        }
      }
    });
  }

  public void addListMultipleSelectionListener(final @NotNull Consumer<List<Change>> listener) {
    myTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(final ListSelectionEvent e) {
        List<GitCommit> commits = myTable.getSelectedObjects();

        final List<Change> changes = new ArrayList<Change>();
        // We need changes in asc order for zipChanges, and they are in desc order in Table
        ListIterator<GitCommit> iterator = commits.listIterator(commits.size());
        while (iterator.hasPrevious()) {
          changes.addAll(iterator.previous().getChanges());
        }

        listener.consume(CommittedChangesTreeBrowser.zipChanges(changes));
      }
    });
  }

  /**
   * Registers the diff action which will be called when the diff shortcut is pressed in the table.
   */
  public void registerDiffAction(@NotNull AnAction diffAction) {
    diffAction.registerCustomShortcutSet(diffAction.getShortcutSet(), myTable);
  }

  // Make changes available for diff action
  @Override
  public void calcData(DataKey key, DataSink sink) {
    if (VcsDataKeys.CHANGES.equals(key)) {
      int[] rows = myTable.getSelectedRows();
      if (rows.length != 1) return;
      int row = rows[0];

      GitCommit gitCommit = myCommits.get(row);
      // suppressing: inherited API
      //noinspection unchecked
      sink.put(key, ArrayUtil.toObjectArray(gitCommit.getChanges(), Change.class));
    }
  }

  @NotNull
  public JComponent getPreferredFocusComponent() {
    return myTable;
  }

  public void clearSelection() {
    myTable.clearSelection();
  }

  public void setCommits(@NotNull List<GitCommit> commits) {
    myCommits.clear();
    myCommits.addAll(commits);
    updateModel();
    myTable.repaint();
  }

  private void updateModel() {
    myTable.setModelAndUpdateColumns(new ListTableModel<GitCommit>(generateColumnsInfo(myCommits), myCommits, 0));
  }

  @NotNull
  private ColumnInfo[] generateColumnsInfo(@NotNull List<GitCommit> commits) {
    ItemAndWidth hash = new ItemAndWidth("", 0);
    ItemAndWidth author = new ItemAndWidth("", 0);
    ItemAndWidth time = new ItemAndWidth("", 0);
    for (GitCommit commit : commits) {
      hash = getMax(hash, getHash(commit));
      author = getMax(author, getAuthor(commit));
      time = getMax(time, getTime(commit));
    }

    return new ColumnInfo[] {
    new GitCommitColumnInfo("Hash", hash.myItem) {
      @Override
      public String valueOf(GitCommit commit) {
        return getHash(commit);
      }
    },
    new ColumnInfo<GitCommit, String>("Subject") {
      @Override
      public String valueOf(GitCommit commit) {
        return commit.getSubject();
      }
    },
    new GitCommitColumnInfo("Author", author.myItem) {
      @Override
      public String valueOf(GitCommit commit) {
        return getAuthor(commit);
      }
    },
    new GitCommitColumnInfo("Author time", time.myItem) {
      @Override
      public String valueOf(GitCommit commit) {
        return getTime(commit);
      }
    }
    };
  }

  private ItemAndWidth getMax(ItemAndWidth current, String candidate) {
    int width = myTable.getFontMetrics(myTable.getFont()).stringWidth(candidate);
    if (width > current.myWidth) {
      return new ItemAndWidth(candidate, width);
    }
    return current;
  }

  private static class ItemAndWidth {
    private final String myItem;
    private final int myWidth;

    private ItemAndWidth(String item, int width) {
      myItem = item;
      myWidth = width;
    }
  }

  private static String getHash(GitCommit commit) {
    return DvcsUtil.getShortHash(commit.getId().toString());
  }

  private static String getAuthor(GitCommit commit) {
    return VcsUserUtil.getShortPresentation(commit.getAuthor());
  }

  private static String getTime(GitCommit commit) {
    return DateFormatUtil.formatPrettyDateTime(commit.getAuthorTime());
  }

  private abstract static class GitCommitColumnInfo extends ColumnInfo<GitCommit, String> {

    @NotNull private final String myMaxString;

    public GitCommitColumnInfo(@NotNull String name, @NotNull String maxString) {
      super(name);
      myMaxString = maxString;
    }

    @Override
    public String getMaxStringValue() {
      return myMaxString;
    }

    @Override
    public int getAdditionalWidth() {
      return UIUtil.DEFAULT_HGAP;
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
import { TrackingEvents, IBaseTrackingEvent } from '@datahub/shared/types/tracking/event-tracking';

/**
 * UI Tracking event types possible in DataHub
 */
export enum CoreUITrackingEventName {
  // PageViewEvent (PVE) is an event used to signal that a certain UI element has been shown
  PageViewEvent = 'PageViewEvent',
  // Tracks when a user interacts with a control, where a control is any physical element of the app. For instance, a control can be a button, link, or dropdown.
  ControlInteractionEvent = 'ControlInteractionEvent',
  // Tracks that the user navigated from one page/screen to another page/screen
  NavigationEvent = 'NavigationEvent'
}

/**
 * Types of page that are valid for a PageViewEvent
 * @exports
 * @enum{string}
 */
export enum PageType {
  Full = 'full',
  Ajax = 'ajax',
  Iframe = 'iframe',
  Redirect = 'redirect',
  Api = 'api',
  Form = 'form',
  Router = 'router',
  Error = 'error'
}
/**
 * String values for categories that can be tracked with the application
 * @export
 * @enum {string}
 */
export enum TrackingEventCategory {
  DatasetCompliance = 'DATASET_COMPLIANCE',
  Search = 'SEARCH',
  Entity = 'ENTITY',
  ControlInteraction = 'CONTROL_INTERACTION'
}

/**
 * List of EventNames across the app that will be tracked via one or more tracking frameworks.
 */
export enum CustomTrackingEventName {
  BrowseAction = 'DataHubBrowseActionEvent',
  SearchAction = 'DataHubSearchActionEvent',
  SearchImpression = 'DataHubSearchImpressionEvent',
  ControlInteractionEvent = 'ControlInteractionEvent'
}

/**
 * Custom identifier for the current page being viewed
 * @export
 */
export enum PageKey {
  // Identifier for the browse  category page which contains the top level browse targets i.e. data entities within  the application
  browseCategory = 'd_browse_category',
  searchCategory = 'd_search_category'
}

/**
 * List of the SearchActionEventCategories that fall under the  `DataHubSearchActionEvent` namespace.
 * The semantic type of ui event action that was performed by the user e.g. SEARCHCLICK, SEARCHSATCLICK
 *
 * @export
 * @enum {string}
 */
export enum SearchActionEventCategory {
  // Click event generated by clicking a search result
  SearchClick = 'SEARCHCLICK',
  // Satisfied Search Click event was generated i.e. search clicks excluding entity views followed by quick-backs. We infer search satisfaction based on action category and time spent on viewing the entity page (DWELL TIME). See more: http://go/datahub/unifiedmetrics
  SearchSatClick = 'SEARCHSATCLICK',
  // Search facet click event was generated by toggling a facet to active
  FacetClick = 'FACETCLICK'
}

/**
 * Enumerates the available tracking goals
 * @export
 * @enum {number}
 */
export enum TrackingGoal {
  // Satisfied Search Clicks goal tracking
  SatClick = 1
}

// Convenience alias for insertTrackingEventsCategoryFor return type
type InsertTrackingEventsCategoryForReturn = Record<string, IBaseTrackingEvent | Partial<IBaseTrackingEvent>>;

/**
 * Augments a tracking event partial with category information
 * @param {TrackingEvents} events the events mapping
 * @param {[string, Partial<IBaseTrackingEvent>]} [eventName, trackingEvent]
 */
export const insertTrackingEventsCategoryFor = (
  category: TrackingEventCategory
): ((
  events: TrackingEvents,
  eventNameAndEvent: [string, Partial<IBaseTrackingEvent>]
) => InsertTrackingEventsCategoryForReturn) => (
  events: TrackingEvents,
  [eventName, trackingEvent]: [string, Partial<IBaseTrackingEvent>]
): InsertTrackingEventsCategoryForReturn => ({
  ...events,
  [eventName]: { ...trackingEvent, category }
});


text:
require 'chef/mixin/shell_out'
require 'rexml/document'

include Chef::Mixin::ShellOut

use_inline_resources

action :create do
  if @current_resource.exists && (!(task_need_update? || @new_resource.force))
    Chef::Log.info "#{@new_resource} task already exists - nothing to do"
  else
    validate_user_and_password
    validate_interactive_setting
    validate_create_frequency_modifier
    validate_create_day
    validate_create_months

    schedule = @new_resource.frequency == :on_logon ? 'ONLOGON' : @new_resource.frequency
    frequency_modifier_allowed = [:minute, :hourly, :daily, :weekly, :monthly]
    options = {}
    options['F'] = '' if @new_resource.force || task_need_update?
    options['SC'] = schedule
    options['MO'] = @new_resource.frequency_modifier if frequency_modifier_allowed.include?(@new_resource.frequency)
    options['SD'] = @new_resource.start_day unless @new_resource.start_day.nil?
    options['ST'] = @new_resource.start_time unless @new_resource.start_time.nil?
    options['TR'] = @new_resource.command
    options['RU'] = @new_resource.user
    options['RP'] = @new_resource.password if use_password?
    options['RL'] = 'HIGHEST' if @new_resource.run_level == :highest
    options['IT'] = '' if @new_resource.interactive_enabled
    options['D'] = @new_resource.day if @new_resource.day
    options['M'] = @new_resource.months unless @new_resource.months.nil?

    run_schtasks 'CREATE', options
    set_cwd(new_resource.cwd) if new_resource.cwd
    new_resource.updated_by_last_action true
    Chef::Log.info "#{@new_resource} task created"
  end
end

action :run do
  if @current_resource.exists
    if @current_resource.status == :running
      Chef::Log.info "#{@new_resource} task is currently running, skipping run"
    else
      run_schtasks 'RUN'
      new_resource.updated_by_last_action true
      Chef::Log.info "#{@new_resource} task ran"
    end
  else
    Chef::Log.debug "#{@new_resource} task doesn't exists - nothing to do"
  end
end

action :change do
  if @current_resource.exists
    validate_user_and_password
    validate_interactive_setting

    options = {}
    options['TR'] = @new_resource.command if @new_resource.command
    options['RU'] = @new_resource.user if @new_resource.user
    options['RP'] = @new_resource.password if @new_resource.password
    options['SD'] = @new_resource.start_day unless @new_resource.start_day.nil?
    options['ST'] = @new_resource.start_time unless @new_resource.start_time.nil?
    options['IT'] = '' if @new_resource.interactive_enabled

    run_schtasks 'CHANGE', options
    set_cwd(new_resource.cwd) if new_resource.cwd != @current_resource.cwd
    new_resource.updated_by_last_action true
    Chef::Log.info "Change #{@new_resource} task ran"
  else
    Chef::Log.debug "#{@new_resource} task doesn't exists - nothing to do"
  end
end

action :delete do
  if @current_resource.exists
    # always need to force deletion
    run_schtasks 'DELETE', 'F' => ''
    new_resource.updated_by_last_action true
    Chef::Log.info "#{@new_resource} task deleted"
  else
    Chef::Log.debug "#{@new_resource} task doesn't exists - nothing to do"
  end
end

action :end do
  if @current_resource.exists
    if @current_resource.status != :running
      Chef::Log.debug "#{@new_resource} is not running - nothing to do"
    else
      run_schtasks 'END'
      @new_resource.updated_by_last_action true
      Chef::Log.info "#{@new_resource} task ended"
    end
  else
    Chef::Log.fatal "#{@new_resource} task doesn't exist - nothing to do"
    fail Errno::ENOENT, "#{@new_resource}: task does not exist, cannot end"
  end
end

action :enable do
  if @current_resource.exists
    if @current_resource.enabled
      Chef::Log.debug "#{@new_resource} already enabled - nothing to do"
    else
      run_schtasks 'CHANGE', 'ENABLE' => ''
      @new_resource.updated_by_last_action true
      Chef::Log.info "#{@new_resource} task enabled"
    end
  else
    Chef::Log.fatal "#{@new_resource} task doesn't exist - nothing to do"
    fail Errno::ENOENT, "#{@new_resource}: task does not exist, cannot enable"
  end
end

action :disable do
  if @current_resource.exists
    if @current_resource.enabled
      run_schtasks 'CHANGE', 'DISABLE' => ''
      @new_resource.updated_by_last_action true
      Chef::Log.info "#{@new_resource} task disabled"
    else
      Chef::Log.debug "#{@new_resource} already disabled - nothing to do"
    end
  else
    Chef::Log.debug "#{@new_resource} task doesn't exist - nothing to do"
  end
end

def load_current_resource
  @current_resource = Chef::Resource::WindowsTask.new(@new_resource.name)
  @current_resource.task_name(@new_resource.task_name)

  pathed_task_name = @new_resource.task_name[0, 1] == '\\' ? @new_resource.task_name : @new_resource.task_name.prepend('\\')
  task_hash = load_task_hash(@current_resource.task_name)
  if task_hash[:TaskName] == pathed_task_name
    @current_resource.exists = true
    @current_resource.status = :running if task_hash[:Status] == 'Running'
    if task_hash[:ScheduledTaskState] == 'Enabled'
      @current_resource.enabled = true
    end
    @current_resource.cwd(task_hash[:StartIn]) unless task_hash[:StartIn] == 'N/A'
    @current_resource.command(task_hash[:TaskToRun])
    @current_resource.user(task_hash[:RunAsUser])
  end if task_hash.respond_to? :[]
end

private

def run_schtasks(task_action, options = {})
  cmd = "schtasks /#{task_action} /TN \"#{@new_resource.task_name}\" "
  options.keys.each do |option|
    cmd += "/#{option} "
    cmd += "\"#{options[option]}\" " unless options[option] == ''
  end
  Chef::Log.debug('running: ')
  Chef::Log.debug("    #{cmd}")
  shell_out!(cmd, returns: [0])
end

def task_need_update?
  # gsub needed as schtasks converts single quotes to double quotes on creation
  @current_resource.command != @new_resource.command.tr("'", "\"") ||
    @current_resource.user != @new_resource.user
end

def set_cwd(folder)
  Chef::Log.debug 'looking for existing tasks'

  # we use shell_out here instead of shell_out! because a failure implies that the task does not exist
  xml_cmd = shell_out("schtasks /Query /TN \"#{@new_resource.task_name}\" /XML")

  return if xml_cmd.exitstatus != 0

  doc = REXML::Document.new(xml_cmd.stdout)

  Chef::Log.debug 'Removing former CWD if any'
  doc.root.elements.delete('Actions/Exec/WorkingDirectory')

  unless folder.nil?
    Chef::Log.debug 'Setting CWD as #folder'
    cwd_element = REXML::Element.new('WorkingDirectory')
    cwd_element.add_text(folder)
    exec_element = doc.root.elements['Actions/Exec']
    exec_element.add_element(cwd_element)
  end

  temp_task_file = ::File.join(ENV['TEMP'], 'windows_task.xml')
  begin
    ::File.open(temp_task_file, 'w:UTF-16LE') do |f|
      doc.write(f)
    end

    options = {}
    options['RU'] = @new_resource.user if @new_resource.user
    options['RP'] = @new_resource.password if @new_resource.password
    options['IT'] = '' if @new_resource.interactive_enabled
    options['XML'] = temp_task_file

    run_schtasks('DELETE', 'F' => '')
    run_schtasks('CREATE', options)
  ensure
    ::File.delete(temp_task_file)
  end
end

def load_task_hash(task_name)
  Chef::Log.debug 'Looking for existing tasks'

  # we use shell_out here instead of shell_out! because a failure implies that the task does not exist
  output = shell_out("schtasks /Query /FO LIST /V /TN \"#{task_name}\"").stdout
  if output.empty?
    task = false
  else
    task = {}

    output.split("\n").map! do |line|
      line.split(':', 2).map!(&:strip)
    end.each do |field|
      if field.is_a?(Array) && field[0].respond_to?(:to_sym)
        task[field[0].gsub(/\s+/, '').to_sym] = field[1]
      end
    end
  end

  task
end

SYSTEM_USERS = ['NT AUTHORITY\SYSTEM', 'SYSTEM', 'NT AUTHORITY\LOCALSERVICE', 'NT AUTHORITY\NETWORKSERVICE']

def validate_user_and_password
  if @new_resource.user && use_password?
    if @new_resource.password.nil?
      Chef::Log.fatal "#{@new_resource.task_name}: Can't specify a non-system user without a password!"
    end
  end
end

def validate_interactive_setting
  if @new_resource.interactive_enabled && @new_resource.password.nil?
    Chef::Log.fatal "#{new_resource} did not provide a password when attempting to set interactive/non-interactive."
  end
end

def validate_create_day
  return unless @new_resource.day
  unless [:weekly, :monthly].include?(@new_resource.frequency)
    fail 'day attribute is only valid for tasks that run weekly or monthly'
  end
  if @new_resource.day.is_a? String
    days = @new_resource.day.split(',')
    days.each do |day|
      unless ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun', '*'].include?(day.strip.downcase)
        fail 'day attribute invalid.  Only valid values are: MON, TUE, WED, THU, FRI, SAT, SUN and *.  Multiple values must be separated by a comma.'
      end
    end
  end
end

def validate_create_months
  return unless @new_resource.months
  unless [:monthly].include?(@new_resource.frequency)
    fail 'months attribute is only valid for tasks that run monthly'
  end
  if @new_resource.months.is_a? String
    months = @new_resource.months.split(',')
    months.each do |month|
      unless ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC', '*'].include?(month.strip.upcase)
        fail 'months attribute invalid. Only valid values are: JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC and *. Multiple values must be separated by a comma.'
      end
    end
  end
end

def validate_create_frequency_modifier
  # Currently is handled in create action 'frequency_modifier_allowed' line. Does not allow for frequency_modifier for once,onstart,onlogon,onidle
  # Note that 'OnEvent' is not a supported frequency.
  unless @new_resource.frequency.nil? || @new_resource.frequency_modifier.nil?
    case @new_resource.frequency
    when :minute
      unless @new_resource.frequency_modifier.to_i > 0 && @new_resource.frequency_modifier.to_i <= 1439
        fail "frequency_modifier value #{@new_resource.frequency_modifier} is invalid.  Valid values for :minute frequency are 1 - 1439."
      end
    when :hourly
      unless @new_resource.frequency_modifier.to_i > 0 && @new_resource.frequency_modifier.to_i <= 23
        fail "frequency_modifier value #{@new_resource.frequency_modifier} is invalid.  Valid values for :hourly frequency are 1 - 23."
      end
    when :daily
      unless @new_resource.frequency_modifier.to_i > 0 && @new_resource.frequency_modifier.to_i <= 365
        fail "frequency_modifier value #{@new_resource.frequency_modifier} is invalid.  Valid values for :daily frequency are 1 - 365."
      end
    when :weekly
      unless @new_resource.frequency_modifier.to_i > 0 && @new_resource.frequency_modifier.to_i <= 52
        fail "frequency_modifier value #{@new_resource.frequency_modifier} is invalid.  Valid values for :weekly frequency are 1 - 52."
      end
    when :monthly
      unless ('1'..'12').to_a.push('FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST', 'LASTDAY').include?(@new_resource.frequency_modifier.to_s.upcase)
        fail "frequency_modifier value #{@new_resource.frequency_modifier} is invalid.  Valid values for :monthly frequency are 1 - 12, 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST', 'LASTDAY'."
      end
    end
  end
end

def use_password?
  @use_password ||= !SYSTEM_USERS.include?(@new_resource.user.upcase)
end


text:
(function () {
	angular.module('apps')
		.controller('index', index);

	index.$inject = ['$window', '$timeout', 'assetApi', 'membersApi', 'systemApi'];
	function index($window, $timeout, $assetApi, $membersApi, $systemApi) {
		var _Site = $window['$base_url'];
		var _Login = _Site + 'WebPortal/Login';
		var self = this;
		var goLogin = function () {
			$window.location.href = _Login;
		};

		self.Initialize = function () {
			self.JsonModel = $window['IndexJson'];
			self.JsonModel.Link.Title = _Site + self.JsonModel.Link.Title;
			self.CurrentLang = $window['$CurrentLang'];
			self.Preference = $window['Preference'];
			self.Nav = self.GetNav(self.JsonModel.SideBarMenu);
			self.ImgPath = '/assets/images/WebPortal/';
		};

		self.Refresh = function () {
			$assetApi.Refresh({
				success: function () {
				}
			});
		};

		self.CloseIframe = function () {
			self.iframePath = '';
		};

		self.ChangeIframePath = function (item) {
			if (item.Link) {
				angular.element('html,body').animate({ scrollTop: '0px' }, 800);
				self.iframePath = _Site + item.Link;
			} else if (item.Func) {
				self[item.Func]();
			}

			return false;
		};

		self.SignOut = function () {
			$membersApi.Logout({
				success: function () {
					$('#modal-success').modal('show');
					$timeout(goLogin, 1500);
				}
			});
		};

		self.ChangeLang = function () {
			$systemApi.SavePreference({
				params: { language: self.CurrentLang },
				success: function (data) {
					$window.location.reload();
				}
			});
		};

		self.GetNav = function (SideBar) {
			var result = [];

			SideBar.forEach(function (element) {
				element.Button.forEach(function (ele) {
					result.push(ele);
				});
			});

			return result;
		};

		self.Initialize();
	}
})();


text:
package de.tudarmstadt.ukp.clarin.webanno.support.lambda;

import java.io.Serializable;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.feedback.IFeedback;
import org.apache.wicket.markup.html.form.Form;
import org.slf4j.LoggerFactory;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class LambdaAjaxSubmitLink<T extends Serializable>
    extends AjaxSubmitLink
{
    private static final long serialVersionUID = 3946442967075930557L;

    private AjaxFormCallback action;
    private AjaxExceptionHandler exceptionHandler;

    public LambdaAjaxSubmitLink(String aId, AjaxFormCallback<T> aAction)
    {
        this(aId, aAction, null);
    }

    public LambdaAjaxSubmitLink(String aId, AjaxFormCallback<T> aAction,
            AjaxExceptionHandler aExceptionHandler)
    {
        super(aId);
        action = aAction;
        exceptionHandler = aExceptionHandler;
    }

    public LambdaAjaxSubmitLink(String aId, Form aForm, AjaxFormCallback<T> aAction)
    {
        this(aId, aForm, aAction, null);
    }

    public LambdaAjaxSubmitLink(String aId, Form aForm, AjaxFormCallback<T> aAction,
            AjaxExceptionHandler aExceptionHandler)
    {
        super(aId, aForm);
        action = aAction;
        exceptionHandler = aExceptionHandler;
    }

    @Override
    protected void onSubmit(AjaxRequestTarget aTarget)
    {
        try {
            action.accept(aTarget, getForm());
        }
        catch (Exception e) {
            if (exceptionHandler != null) {
                exceptionHandler.accept(aTarget, e);
            }
            else {
                LoggerFactory.getLogger(getPage().getClass()).error("Error: " + e.getMessage(), e);
                error("Error: " + e.getMessage());
                aTarget.addChildren(getPage(), IFeedback.class);
            }
        }
    }

    @Override
    protected void onError(AjaxRequestTarget aTarget)
    {
        aTarget.addChildren(getPage(), IFeedback.class);
    }
}


text:
"""
INFINIDAT InfiniBox Volume Driver
"""

from contextlib import contextmanager

import mock
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import units
import requests
import six

from cinder import exception
from cinder.i18n import _
from cinder import interface
from cinder import utils
from cinder.volume.drivers.san import san
from cinder.volume import utils as vol_utils
from cinder.zonemanager import utils as fczm_utils

LOG = logging.getLogger(__name__)

VENDOR_NAME = 'INFINIDAT'
DELETE_URI = 'volumes/%s?approved=true'

infinidat_opts = [
    cfg.StrOpt('infinidat_pool_name',
               help='Name of the pool from which volumes are allocated'),
]

CONF = cfg.CONF
CONF.register_opts(infinidat_opts)

@interface.volumedriver
class InfiniboxVolumeDriver(san.SanDriver):
    VERSION = '1.0'

    # ThirdPartySystems wiki page
    CI_WIKI_NAME = "INFINIDAT_Cinder_CI"

    def __init__(self, *args, **kwargs):
        super(InfiniboxVolumeDriver, self).__init__(*args, **kwargs)
        self.configuration.append_config_values(infinidat_opts)
        self._lookup_service = fczm_utils.create_lookup_service()

    def do_setup(self, context):
        """Driver initialization"""
        self._session = requests.Session()
        self._session.auth = (self.configuration.san_login,
                              self.configuration.san_password)
        management_address = self.configuration.san_ip
        self._base_url = 'http://%s/api/rest/' % management_address
        backend_name = self.configuration.safe_get('volume_backend_name')
        self._backend_name = backend_name or self.__class__.__name__
        self._volume_stats = None
        LOG.debug('setup complete. base url: %s', self._base_url)

    def _request(self, action, uri, data=None):
        LOG.debug('--> %(action)s %(uri)s %(data)r',
                  {'action': action, 'uri': uri, 'data': data})
        response = self._session.request(action,
                                         self._base_url + uri,
                                         json=data)
        LOG.debug('<-- %(status_code)s %(response_json)r',
                  {'status_code': response.status_code,
                   'response_json': response.json()})
        try:
            response.raise_for_status()
        except requests.HTTPError as ex:
            # text_type(ex) includes http code and url
            msg = _('InfiniBox storage array returned %(exception)s\n'
                    'Data: %(data)s\n'
                    'Response: %(response_json)s') % {
                        'exception': six.text_type(ex),
                        'data': repr(data),
                        'response_json': repr(response.json())}
            LOG.exception(msg)
            if response.status_code == 404:
                raise exception.NotFound()
            else:
                raise exception.VolumeBackendAPIException(data=msg)
        return response.json()['result']

    def _get(self, uri):
        return self._request('GET', uri)

    def _post(self, uri, data):
        return self._request('POST', uri, data)

    def _delete(self, uri):
        return self._request('DELETE', uri)

    def _put(self, uri, data):
        return self._request('PUT', uri, data)

    def _cleanup_wwpn(self, wwpn):
        return wwpn.replace(':', '')

    def _make_volume_name(self, cinder_volume):
        return 'openstack-vol-%s' % cinder_volume.id

    def _make_snapshot_name(self, cinder_snapshot):
        return 'openstack-snap-%s' % cinder_snapshot.id

    def _make_host_name(self, wwpn):
        wwn_for_name = self._cleanup_wwpn(wwpn)
        return 'openstack-host-%s' % wwn_for_name

    def _get_infinidat_volume_by_name(self, name):
        volumes = self._get('volumes?name=%s' % name)
        if len(volumes) != 1:
            msg = _('Volume "%s" not found') % name
            LOG.error(msg)
            raise exception.InvalidVolume(reason=msg)
        return volumes[0]

    def _get_infinidat_snapshot_by_name(self, name):
        snapshots = self._get('volumes?name=%s' % name)
        if len(snapshots) != 1:
            msg = _('Snapshot "%s" not found') % name
            LOG.error(msg)
            raise exception.InvalidSnapshot(reason=msg)
        return snapshots[0]

    def _get_infinidat_volume_id(self, cinder_volume):
        volume_name = self._make_volume_name(cinder_volume)
        return self._get_infinidat_volume_by_name(volume_name)['id']

    def _get_infinidat_snapshot_id(self, cinder_snapshot):
        snap_name = self._make_snapshot_name(cinder_snapshot)
        return self._get_infinidat_snapshot_by_name(snap_name)['id']

    def _get_infinidat_pool(self):
        pool_name = self.configuration.infinidat_pool_name
        pools = self._get('pools?name=%s' % pool_name)
        if len(pools) != 1:
            msg = _('Pool "%s" not found') % pool_name
            LOG.error(msg)
            raise exception.VolumeDriverException(message=msg)
        return pools[0]

    def _get_host(self, wwpn):
        host_name = self._make_host_name(wwpn)
        infinidat_hosts = self._get('hosts?name=%s' % host_name)
        if len(infinidat_hosts) == 1:
            return infinidat_hosts[0]

    def _get_or_create_host(self, wwpn):
        host_name = self._make_host_name(wwpn)
        infinidat_host = self._get_host(wwpn)
        if infinidat_host is None:
            # create host
            infinidat_host = self._post('hosts', dict(name=host_name))
            # add port to host
            self._post('hosts/%s/ports' % infinidat_host['id'],
                       dict(type='FC', address=self._cleanup_wwpn(wwpn)))
        return infinidat_host

    def _get_mapping(self, host_id, volume_id):
        existing_mapping = self._get("hosts/%s/luns" % host_id)
        for mapping in existing_mapping:
            if mapping['volume_id'] == volume_id:
                return mapping

    def _get_or_create_mapping(self, host_id, volume_id):
        mapping = self._get_mapping(host_id, volume_id)
        if mapping:
            return mapping
        # volume not mapped. map it
        uri = 'hosts/%s/luns?approved=true' % host_id
        return self._post(uri, dict(volume_id=volume_id))

    def _get_online_fc_ports(self):
        nodes = self._get('components/nodes?fields=fc_ports')
        for node in nodes:
            for port in node['fc_ports']:
                if (port['link_state'].lower() == 'up'
                   and port['state'] == 'OK'):
                    yield self._cleanup_wwpn(port['wwpn'])

    @fczm_utils.add_fc_zone
    def initialize_connection(self, volume, connector):
        """Map an InfiniBox volume to the host"""
        volume_name = self._make_volume_name(volume)
        infinidat_volume = self._get_infinidat_volume_by_name(volume_name)
        for wwpn in connector['wwpns']:
            infinidat_host = self._get_or_create_host(wwpn)
            mapping = self._get_or_create_mapping(infinidat_host['id'],
                                                  infinidat_volume['id'])
            lun = mapping['lun']

        # Create initiator-target mapping.
        target_wwpns = list(self._get_online_fc_ports())
        target_wwpns, init_target_map = self._build_initiator_target_map(
            connector, target_wwpns)
        return dict(driver_volume_type='fibre_channel',
                    data=dict(target_discovered=False,
                              target_wwn=target_wwpns,
                              target_lun=lun,
                              initiator_target_map=init_target_map))

    @fczm_utils.remove_fc_zone
    def terminate_connection(self, volume, connector, **kwargs):
        """Unmap an InfiniBox volume from the host"""
        volume_id = self._get_infinidat_volume_id(volume)
        result_data = dict()
        for wwpn in connector['wwpns']:
            host_name = self._make_host_name(wwpn)
            infinidat_hosts = self._get('hosts?name=%s' % host_name)
            if len(infinidat_hosts) != 1:
                # not found. ignore.
                continue
            host_id = infinidat_hosts[0]['id']
            # unmap
            uri = ('hosts/%s/luns/volume_id/%s' % (host_id, volume_id) +
                   '?approved=true')
            try:
                self._delete(uri)
            except (exception.NotFound):
                continue      # volume mapping not found
        # check if the host now doesn't have mappings, to delete host_entry
        # if needed
        infinidat_hosts = self._get('hosts?name=%s' % host_name)
        if len(infinidat_hosts) == 1 and len(infinidat_hosts[0]['luns']) == 0:
            # Create initiator-target mapping.
            target_wwpns = list(self._get_online_fc_ports())
            target_wwpns, init_target_map = self._build_initiator_target_map(
                connector, target_wwpns)
            result_data = dict(target_wwn=target_wwpns,
                               initiator_target_map=init_target_map)
        return dict(driver_volume_type='fibre_channel',
                    data=result_data)

    def get_volume_stats(self, refresh=False):
        if self._volume_stats is None or refresh:
            pool = self._get_infinidat_pool()
            free_capacity_gb = float(pool['free_physical_space']) / units.Gi
            total_capacity_gb = float(pool['physical_capacity']) / units.Gi
            self._volume_stats = dict(volume_backend_name=self._backend_name,
                                      vendor_name=VENDOR_NAME,
                                      driver_version=self.VERSION,
                                      storage_protocol='FC',
                                      consistencygroup_support='False',
                                      total_capacity_gb=total_capacity_gb,
                                      free_capacity_gb=free_capacity_gb)
        return self._volume_stats

    def _create_volume(self, volume):
        # get pool id from name
        pool = self._get_infinidat_pool()
        # create volume
        volume_name = self._make_volume_name(volume)
        provtype = "THIN" if self.configuration.san_thin_provision else "THICK"
        data = dict(pool_id=pool['id'],
                    provtype=provtype,
                    name=volume_name,
                    size=volume.size * units.Gi)
        return self._post('volumes', data)

    def create_volume(self, volume):
        """Create a new volume on the backend."""
        # this is the same as _create_volume but without the return statement
        self._create_volume(volume)

    def delete_volume(self, volume):
        """Delete a volume from the backend."""
        try:
            volume_name = self._make_volume_name(volume)
            volume = self._get_infinidat_volume_by_name(volume_name)
            if volume['has_children']:
                # can't delete a volume that has a live snapshot
                raise exception.VolumeIsBusy(volume_name=volume_name)
            self._delete(DELETE_URI % volume['id'])
        except (exception.InvalidVolume, exception.NotFound):
            return      # volume not found

    def extend_volume(self, volume, new_size):
        """Extend the size of a volume."""
        volume_id = self._get_infinidat_volume_id(volume)
        self._put('volumes/%s?approved=true' % volume_id,
                  dict(size=new_size * units.Gi))

    def create_snapshot(self, snapshot):
        """Creates a snapshot."""
        volume_id = self._get_infinidat_volume_id(snapshot.volume)
        name = self._make_snapshot_name(snapshot)
        self._post('volumes', dict(parent_id=volume_id, name=name))

    @contextmanager
    def _device_connect_context(self, volume):
        connector = utils.brick_get_connector_properties()
        connection = self.initialize_connection(volume, connector)
        try:
            yield self._connect_device(connection)
        finally:
            self.terminate_connection(volume, connector)

    def create_volume_from_snapshot(self, volume, snapshot):
        """Create volume from snapshot.

        InfiniBox does not yet support detached clone so use dd to copy data.
        This could be a lengthy operation.

        - create a clone from snapshot and map it
        - create a volume and map it
        - copy data from clone to volume
        - unmap volume and clone and delete the clone
        """
        snapshot_id = self._get_infinidat_snapshot_id(snapshot)
        clone_name = self._make_volume_name(volume) + '-internal'
        infinidat_clone = self._post('volumes', dict(parent_id=snapshot_id,
                                                     name=clone_name))
        # we need a cinder-volume-like object to map the clone by name
        # (which is derived from the cinder id) but the clone is internal
        # so there is no such object. mock one
        clone = mock.Mock(id=str(volume.id) + '-internal')
        try:
            infinidat_volume = self._create_volume(volume)
            try:
                src_ctx = self._device_connect_context(clone)
                dst_ctx = self._device_connect_context(volume)
                with src_ctx as src_dev, dst_ctx as dst_dev:
                    dd_block_size = self.configuration.volume_dd_blocksize
                    vol_utils.copy_volume(src_dev['device']['path'],
                                          dst_dev['device']['path'],
                                          snapshot.volume.size * units.Ki,
                                          dd_block_size,
                                          sparse=True)
            except Exception:
                self._delete(DELETE_URI % infinidat_volume['id'])
                raise
        finally:
            self._delete(DELETE_URI % infinidat_clone['id'])

    def delete_snapshot(self, snapshot):
        """Deletes a snapshot."""
        try:
            snapshot_name = self._make_snapshot_name(snapshot)
            snapshot = self._get_infinidat_snapshot_by_name(snapshot_name)
            self._delete(DELETE_URI % snapshot['id'])
        except (exception.InvalidSnapshot, exception.NotFound):
            return      # snapshot not found

    def _asssert_volume_not_mapped(self, volume):
        # copy is not atomic so we can't clone while the volume is mapped
        volume_name = self._make_volume_name(volume)
        infinidat_volume = self._get_infinidat_volume_by_name(volume_name)
        mappings = self._get("volumes/%s/luns" % infinidat_volume['id'])
        if len(mappings) == 0:
            return

        # volume has mappings
        msg = _("INFINIDAT Cinder driver does not support clone of an "
                "attached volume. "
                "To get this done, create a snapshot from the attached "
                "volume and then create a volume from the snapshot.")
        LOG.error(msg)
        raise exception.VolumeBackendAPIException(data=msg)

    def create_cloned_volume(self, volume, src_vref):
        """Create a clone from source volume.

        InfiniBox does not yet support detached clone so use dd to copy data.
        This could be a lengthy operation.

        * map source volume
        * create and map new volume
        * copy data from source to new volume
        * unmap both volumes
        """
        self._asssert_volume_not_mapped(src_vref)
        infinidat_volume = self._create_volume(volume)
        try:
            src_ctx = self._device_connect_context(src_vref)
            dst_ctx = self._device_connect_context(volume)
            with src_ctx as src_dev, dst_ctx as dst_dev:
                dd_block_size = self.configuration.volume_dd_blocksize
                vol_utils.copy_volume(src_dev['device']['path'],
                                      dst_dev['device']['path'],
                                      src_vref.size * units.Ki,
                                      dd_block_size,
                                      sparse=True)
        except Exception:
            self._delete(DELETE_URI % infinidat_volume['id'])
            raise

    def _build_initiator_target_map(self, connector, all_target_wwns):
        """Build the target_wwns and the initiator target map."""
        target_wwns = []
        init_targ_map = {}

        if self._lookup_service is not None:
            # use FC san lookup.
            dev_map = self._lookup_service.get_device_mapping_from_network(
                connector.get('wwpns'),
                all_target_wwns)

            for fabric_name in dev_map:
                fabric = dev_map[fabric_name]
                target_wwns += fabric['target_port_wwn_list']
                for initiator in fabric['initiator_port_wwn_list']:
                    if initiator not in init_targ_map:
                        init_targ_map[initiator] = []
                    init_targ_map[initiator] += fabric['target_port_wwn_list']
                    init_targ_map[initiator] = list(set(
                        init_targ_map[initiator]))
            target_wwns = list(set(target_wwns))
        else:
            initiator_wwns = connector.get('wwpns', [])
            target_wwns = all_target_wwns

            for initiator in initiator_wwns:
                init_targ_map[initiator] = target_wwns

        return target_wwns, init_targ_map


text:
<?php

namespace Hitmeister\Component\Api\Transfers;

/**
 * This class was auto generated. Please, do not modify it!
 *
 * @codeCoverageIgnore
 *
 * @property int $id_unit
 * @property int $id_item
 * @property string $condition
 * @property string $location
 * @property string $warehouse
 * @property int $amount
 * @property int $price
 * @property string $delivery_time
 * @property int $delivery_time_min
 * @property int $delivery_time_max
 * @property string $shipping_group
 * @property string $note
 * @property int $reference_price
 * @property SellerTransfer $seller
 * @property int $shipping_rate
 * @property string $date_inserted
 * @property string $date_lastchange
 *
 * @property ItemTransfer $item
 * @property int $listing_price
 * @property int $minimum_price
 * @property string $id_offer
 *
 */
class UnitWithEmbeddedTransfer extends AbstractTransfer
{
    /**
     * @return array
     */
    public function getProperties()
    {
        static $properties = array (
  'id_unit' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'id_item' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'condition' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'location' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'warehouse' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'amount' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'price' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'delivery_time' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'delivery_time_min' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'delivery_time_max' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'shipping_group' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'note' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'reference_price' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'seller' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
    'type' => 'Hitmeister\\Component\\Api\\Transfers\\SellerTransfer',
  ),
  'shipping_rate' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'date_inserted' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'date_lastchange' =>
  array (
    'embedded' => false,
    'is_multiple' => false,
  ),
  'item' =>
  array (
    'embedded' => true,
    'is_multiple' => false,
    'type' => 'Hitmeister\\Component\\Api\\Transfers\\ItemTransfer',
  ),
  'listing_price' =>
  array (
    'embedded' => true,
    'is_multiple' => false,
  ),
  'minimum_price' =>
  array (
    'embedded' => true,
    'is_multiple' => false,
  ),
  'id_offer' =>
  array (
    'embedded' => true,
    'is_multiple' => false,
  ),
);
        return $properties;
    }

    /**
     * @param array $data
     *
     * @return UnitWithEmbeddedTransfer
     */
    public static function make(array $data)
    {
        return AbstractTransfer::makeTransfer('Hitmeister\Component\Api\Transfers\UnitWithEmbeddedTransfer', $data);
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ip::basic_resolver::async_resolve (3 of 6 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../async_resolve.html" title="ip::basic_resolver::async_resolve">
<link rel="prev" href="overload2.html" title="ip::basic_resolver::async_resolve (2 of 6 overloads)">
<link rel="next" href="overload4.html" title="ip::basic_resolver::async_resolve (4 of 6 overloads)">

Home
Libraries
People
FAQ
More

ip::basic_resolver::async_resolve
          (3 of 6 overloads)

            Asynchronously perform forward resolution of a query to a list of entries.

template<
    typename ResolveHandler = DEFAULT>
DEDUCED async_resolve(
    string_view host,
    string_view service,
    resolver_base::flags resolve_flags,
    ResolveHandler && handler = DEFAULT);

            This function is used to resolve host and service names into a list of
            endpoint entries.

            Parameters

host

                  A string identifying a location. May be a descriptive name or a
                  numeric address string. If an empty string and the passive flag
                  has been specified, the resolved endpoints are suitable for local
                  service binding. If an empty string and passive is not specified,
                  the resolved endpoints will use the loopback address.

service

                  A string identifying the requested service. This may be a descriptive
                  name or a numeric string corresponding to a port number. May be
                  an empty string, in which case all resolved endpoints will have
                  a port number of 0.

resolve_flags

                  A set of flags that determine how name resolution should be performed.
                  The default flags are suitable for communication with remote hosts.
                  See the ip::resolver_base
                  documentation for the set of available flags.

handler

                  The handler to be called when the resolve operation completes.
                  Copies will be made of the handler as required. The function signature
                  of the handler must be:

void handler(
  const boost::system::error_code& error, // Result of operation.
  resolver::results_type results // Resolved endpoints as a range.
);

                  Regardless of whether the asynchronous operation completes immediately
                  or not, the handler will not be invoked from within this function.
                  On immediate completion, invocation of the handler will be performed
                  in a manner equivalent to using post.

            A successful resolve operation is guaranteed to pass a non-empty range
            to the handler.

            Remarks

            On POSIX systems, host names may be locally defined in the file /etc/hosts.
            On Windows, host names may be defined in the file c:\windows\system32\drivers\etc\hosts.
            Remote host name resolution is performed using DNS. Operating systems
            may use additional locations when resolving host names (such as NETBIOS
            names on Windows).

            On POSIX systems, service names are typically defined in the file /etc/services.
            On Windows, service names may be found in the file c:\windows\system32\drivers\etc\services.
            Operating systems may use additional locations when resolving service
            names.

Copyright © 2003-2021 Christopher
      M. Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package me.jfenn.colorpickerdialog.adapters;

import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import me.jfenn.colorpickerdialog.views.HeightableViewPager;

public abstract class HeightablePagerAdapter extends PagerAdapter implements HeightableViewPager.Heightable {

    private int position = -1;

    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        super.setPrimaryItem(container, position, object);

        if (position != this.position) {
            this.position = position;
            container.requestLayout();
        }
    }
}


text:
<!DOCTYPE html>

	<title>Init from object</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = normalizeEmail;

var _isEmail = require('./isEmail');

var _isEmail2 = _interopRequireDefault(_isEmail);

var _merge = require('./util/merge');

var _merge2 = _interopRequireDefault(_merge);

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {default: obj};
}

var default_normalize_email_options = {
  lowercase: true,
  remove_dots: true,
  remove_extension: true
};

function normalizeEmail(email, options) {
  options = (0, _merge2.default)(options, default_normalize_email_options);
  if (!(0, _isEmail2.default)(email)) {
    return false;
  }
  var parts = email.split('@', 2);
  parts[1] = parts[1].toLowerCase();
  if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') {
    if (options.remove_extension) {
      parts[0] = parts[0].split('+')[0];
    }
    if (options.remove_dots) {
      parts[0] = parts[0].replace(/\./g, '');
    }
    if (!parts[0].length) {
      return false;
    }
    parts[0] = parts[0].toLowerCase();
    parts[1] = 'gmail.com';
  } else if (options.lowercase) {
    parts[0] = parts[0].toLowerCase();
  }
  return parts.join('@');
}
module.exports = exports['default'];


text:
// Package serviceaccount provides a Registry interface and a strategy
// implementation for storing ServiceAccount API objects.
package serviceaccount


text:
const QString TEST_CARDNUMBER = "1234_testcard";

void CardReaderTest::initTestCase()
{
	widget.installEventFilter(&cardReader);
}

void CardReaderTest::simulateRFIDReader()
{
	QSignalSpy spy(&cardReader, SIGNAL(newCardNumber(QString)));
	QVERIFY(spy.isValid());

	QTest::keyClicks(&widget, TEST_CARDNUMBER);
	QTest::keyClick(&widget, Qt::Key_Return);

	QCOMPARE(spy.count(), 1);

	QList<QVariant> arguments = spy.takeFirst();
	QCOMPARE(arguments.at(0).toString(), TEST_CARDNUMBER);
}

void CardReaderTest::simulateKeyboardInput()
{
	QSignalSpy spy(&cardReader, SIGNAL(newCardNumber(QString)));
	QVERIFY(spy.isValid());

	int keyTypingTime = 50;
	QTest::keyClicks(&widget, TEST_CARDNUMBER, Qt::NoModifier, keyTypingTime);
	QTest::keyClick(&widget, Qt::Key_Return);

	QCOMPARE(spy.count(), 0);
}

void CardReaderTest::simulateSecondRFIDReader()
{
	simulateRFIDReader();
}

QTEST_MAIN(CardReaderTest)


text:
<?php

namespace app\models;

use Yii;

class PostImageTrl extends PostImageTrlDB
{
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        $baseLabels = parent::attributeLabels();
        foreach($baseLabels as $attribute => $label){
            $baseLabels[$attribute] = Yii::t('admin',$label);
        }
        return $baseLabels;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $baseRules = parent::rules();
        return $baseRules;
    }
}


text:
"""
IAMService
"""
import time

import xml.sax.saxutils as saxutils

# post xml soap message

import sys, httplib

from lxml import etree
from cStringIO import StringIO

#import static

import toml

class IAMClient(object):

    def __init__(self):

        conf_fn = "config.toml"

        with open(conf_fn) as conf_fh:

            self.conf = toml.loads(conf_fh.read())

        print(self.conf)

    def searchAll(self, startPage, pageSize ):

        #config = static.ERP_CONFIG #'SL 8.0'

        query = {"username":self.conf["Admin"],"password":self.conf["Admin_Password"], "nonce":self.conf["Nonce"], "startPage":startPage, "pageSize": pageSize}

        SM_TEMPLATE = r"""<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sear="http://search.service.iam.foton.com/">
       <soapenv:Header>

      <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">

         <wsse:UsernameToken wsu:Id="UsernameToken-1" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">

            <wsse:Username>%(username)s</wsse:Username>

            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">%(password)s</wsse:Password>

            <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">%(nonce)s</wsse:Nonce>

            <wsu:Created>2012-07-06T01:49:02.953Z</wsu:Created>

         </wsse:UsernameToken>

      </wsse:Security>

   </soapenv:Header>
   <soapenv:Body>
      <sear:searchAll>
         <arg0>%(startPage)s</arg0>
         <arg1>%(pageSize)s</arg1>
         <!--Optional:-->
         <arg2>ou</arg2>
         <arg3>true</arg3>
      </sear:searchAll>
   </soapenv:Body>
</soapenv:Envelope>"""  % query

        SoapMessage = SM_TEMPLATE

        #print SoapMessage
        #construct and send the header

        host =self.conf["HOST"]
        print(host)
        webservice = httplib.HTTP(host)

        service = self.conf["Service2"]

        url = "/IAMService/services/soap/%s" %(service)

        webservice.putrequest("POST", url)
        webservice.putheader("Host", host)
        webservice.putheader("User-Agent", "Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.2;+SV1;+.NET+CLR+1.1.4322)")
        webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
        webservice.putheader("Accept-Language", "en-us")
        webservice.putheader("Content-length", "%d" % len(SoapMessage))
        #webservice.putheader("SOAPAction", "authenticate")
        webservice.endheaders()
        webservice.send(SoapMessage)

        # get the response

        statuscode, statusmessage, header = webservice.getreply()
        print "Response: ", statuscode, statusmessage, startPage
        #print "headers: ", header
        #print dir(webservice)
        res = webservice.getfile().read()

        fn = "%d.xml" %(time.time())
        #print res
        #with open(fn, 'w') as fh:
        #    fh.write(res)

        return  res #self.parseSessionToken(res)

    def getResponse(self, xmlstr):

        string_file = StringIO(xmlstr.replace('soap:',''))

        #root = etree.fromstring(xml)
        tree = etree.parse(string_file)

        resp = None

        for element in tree.xpath('/Envelope/Body'):
            resp = element[0][1].text

        return resp

    def getResult(self, xmlstr):

        resp = self.getResponse(xmlstr)

        string_file = StringIO(resp)

        #root = etree.fromstring(xml)
        tree = etree.parse(string_file)

        result = None

        v = tree.xpath('/Parameters')[0]

        l = len(v)

        result = v[l-1].text

        if result.count('successful') >0:
            return "S"
        else:
            return "F"

def get_element_text(element, node):

    v = element.xpath(node)

    if len(v)>0:
        #print v[0].text.encode("utf8")
        return v[0].text.encode("utf8")
    else:
        return ""

def main():

    cm = IAMClient()

    fh = open("id3.csv","w")

    for i in range(1, 20):

        xmlstr = cm.searchAll(i,10)

        string_file = StringIO(xmlstr.replace('soap:','').replace("ns2:",""))

        #root = etree.fromstring(xml)
        tree = etree.parse(string_file)

        resp = None

        for element in tree.xpath('/Envelope/Body/searchAllResponse/return/userData'):
            #resp = element[0][1].text
            #print "\n"
            v1 = get_element_text(element, "cn")

            v2 = get_element_text(element, "mail")

            v3 = get_element_text(element, "fotonAppAtt37")

            v4 = get_element_text(element, "mobile")

            v5 = get_element_text(element, "telephoneNumber")

            v6 = get_element_text(element, "uid")

            v7 = get_element_text(element, "ou")
            #print userPassword[0].text,

            x = "%s,%s,%s,%s,%s,%s,%s\n" % (v1, v2, v3, v4, v5, v6, v7)

            fh.write(x)

        time.sleep(0.5)

    fh.close()

    """

    token = cm.parseSessionToken(xmlstr)

    rtn = cm.callMethod(token, "")

    print cm.getResult(rtn)

    """

if __name__ == '__main__':
    main()


text:
package org.apache.directory.server.core.api.schema;

import java.text.ParseException;

import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.Value;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException;
import org.apache.directory.api.ldap.model.exception.LdapUnwillingToPerformException;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.api.ldap.model.schema.DitContentRule;
import org.apache.directory.api.ldap.model.schema.DitStructureRule;
import org.apache.directory.api.ldap.model.schema.LdapSyntax;
import org.apache.directory.api.ldap.model.schema.MatchingRule;
import org.apache.directory.api.ldap.model.schema.MatchingRuleUse;
import org.apache.directory.api.ldap.model.schema.NameForm;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.apache.directory.api.ldap.model.schema.SchemaManager;
import org.apache.directory.api.ldap.model.schema.parsers.AttributeTypeDescriptionSchemaParser;
import org.apache.directory.api.ldap.model.schema.parsers.DitContentRuleDescriptionSchemaParser;
import org.apache.directory.api.ldap.model.schema.parsers.DitStructureRuleDescriptionSchemaParser;
import org.apache.directory.api.ldap.model.schema.parsers.LdapComparatorDescription;
import org.apache.directory.api.ldap.model.schema.parsers.LdapComparatorDescriptionSchemaParser;
import org.apache.directory.api.ldap.model.schema.parsers.LdapSyntaxDescriptionSchemaParser;
import org.apache.directory.api.ldap.model.schema.parsers.MatchingRuleDescriptionSchemaParser;
import org.apache.directory.api.ldap.model.schema.parsers.MatchingRuleUseDescriptionSchemaParser;
import org.apache.directory.api.ldap.model.schema.parsers.NameFormDescriptionSchemaParser;
import org.apache.directory.api.ldap.model.schema.parsers.NormalizerDescription;
import org.apache.directory.api.ldap.model.schema.parsers.NormalizerDescriptionSchemaParser;
import org.apache.directory.api.ldap.model.schema.parsers.ObjectClassDescriptionSchemaParser;
import org.apache.directory.api.ldap.model.schema.parsers.SyntaxCheckerDescription;
import org.apache.directory.api.ldap.model.schema.parsers.SyntaxCheckerDescriptionSchemaParser;
import org.apache.directory.server.i18n.I18n;

/**
 * TODO: move to apacheds-core?
 *
 * Parses descriptions using a number of different parsers for schema descriptions.
 * Also checks to make sure some things are valid as it's parsing paramters of
 * certain entity types.
 *
 * @author Apache Directory Project
 */
public class DescriptionParsers
{
    /** Empty arrays of SchemaObjects */
    private static final LdapComparatorDescription[] EMPTY_COMPARATORS = new LdapComparatorDescription[0];
    private static final NormalizerDescription[] EMPTY_NORMALIZERS = new NormalizerDescription[0];
    private static final SyntaxCheckerDescription[] EMPTY_SYNTAX_CHECKERS = new SyntaxCheckerDescription[0];
    private static final LdapSyntax[] EMPTY_SYNTAXES = new LdapSyntax[0];
    private static final MatchingRule[] EMPTY_MATCHING_RULES = new MatchingRule[0];
    private static final AttributeType[] EMPTY_ATTRIBUTE_TYPES = new AttributeType[0];
    private static final ObjectClass[] EMPTY_OBJECT_CLASSES = new ObjectClass[0];
    private static final MatchingRuleUse[] EMPTY_MATCHING_RULE_USES = new MatchingRuleUse[0];
    private static final DitStructureRule[] EMPTY_DIT_STRUCTURE_RULES = new DitStructureRule[0];
    private static final DitContentRule[] EMPTY_DIT_CONTENT_RULES = new DitContentRule[0];
    private static final NameForm[] EMPTY_NAME_FORMS = new NameForm[0];

    /** The SchemaObject description's parsers */
    private final LdapComparatorDescriptionSchemaParser comparatorParser = new LdapComparatorDescriptionSchemaParser();
    private final NormalizerDescriptionSchemaParser normalizerParser = new NormalizerDescriptionSchemaParser();
    private final SyntaxCheckerDescriptionSchemaParser syntaxCheckerParser = new SyntaxCheckerDescriptionSchemaParser();
    private final LdapSyntaxDescriptionSchemaParser syntaxParser = new LdapSyntaxDescriptionSchemaParser();
    private final MatchingRuleDescriptionSchemaParser matchingRuleParser = new MatchingRuleDescriptionSchemaParser();
    private final AttributeTypeDescriptionSchemaParser attributeTypeParser = new AttributeTypeDescriptionSchemaParser();
    private final ObjectClassDescriptionSchemaParser objectClassParser = new ObjectClassDescriptionSchemaParser();
    private final MatchingRuleUseDescriptionSchemaParser matchingRuleUseParser = new MatchingRuleUseDescriptionSchemaParser();
    private final DitStructureRuleDescriptionSchemaParser ditStructureRuleParser = new DitStructureRuleDescriptionSchemaParser();
    private final DitContentRuleDescriptionSchemaParser ditContentRuleParser = new DitContentRuleDescriptionSchemaParser();
    private final NameFormDescriptionSchemaParser nameFormParser = new NameFormDescriptionSchemaParser();

    /** The SchemaManager instance */
    private final SchemaManager schemaManager;

    /**
     * Creates a description parser.
     *
     * @param schemaManager The server schemaManager to use while creating new schema entities
     */
    public DescriptionParsers( SchemaManager schemaManager )
    {
        this.schemaManager = schemaManager;
    }

    /**
     * Parse the SyntaxCheckers description
     *
     * @param attr The attribute containing the SC description
     * @return The array of SyntaxCheckerDescription instances
     * @throws LdapInvalidAttributeValueException If something went wrong
     */
    public SyntaxCheckerDescription[] parseSyntaxCheckers( Attribute attr ) throws LdapInvalidAttributeValueException
    {
        if ( ( attr == null ) || ( attr.size() == 0 ) )
        {
            return EMPTY_SYNTAX_CHECKERS;
        }

        SyntaxCheckerDescription[] syntaxCheckerDescriptions = new SyntaxCheckerDescription[attr.size()];

        int pos = 0;

        for ( Value value : attr )
        {
            try
            {
                syntaxCheckerDescriptions[pos++] = syntaxCheckerParser
                    .parse( value.getString() );
            }
            catch ( ParseException e )
            {
                LdapInvalidAttributeValueException iave = new LdapInvalidAttributeValueException(
                    ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_405,
                        value ) );
                iave.initCause( e );
                throw iave;
            }
        }

        return syntaxCheckerDescriptions;
    }

    public NormalizerDescription[] parseNormalizers( Attribute attr ) throws LdapInvalidAttributeValueException
    {
        if ( attr == null || attr.size() == 0 )
        {
            return EMPTY_NORMALIZERS;
        }

        NormalizerDescription[] normalizerDescriptions = new NormalizerDescription[attr.size()];

        int pos = 0;

        for ( Value value : attr )
        {
            try
            {
                normalizerDescriptions[pos++] = normalizerParser.parse( value.getString() );
            }
            catch ( ParseException e )
            {
                LdapInvalidAttributeValueException iave = new LdapInvalidAttributeValueException(
                    ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_406,
                        value.getString() ) );
                iave.initCause( e );
                throw iave;
            }
        }

        return normalizerDescriptions;
    }

    public LdapComparatorDescription[] parseComparators( Attribute attr ) throws LdapInvalidAttributeValueException
    {
        if ( attr == null || attr.size() == 0 )
        {
            return EMPTY_COMPARATORS;
        }

        LdapComparatorDescription[] comparatorDescriptions = new LdapComparatorDescription[attr.size()];

        int pos = 0;

        for ( Value value : attr )
        {
            try
            {
                comparatorDescriptions[pos++] = comparatorParser.parse( value.getString() );
            }
            catch ( ParseException e )
            {
                LdapInvalidAttributeValueException iave = new LdapInvalidAttributeValueException(
                    ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_407,
                        value.getString() ) );
                iave.initCause( e );
                throw iave;
            }
        }

        return comparatorDescriptions;
    }

    /**
     * Parses a set of attributeTypeDescriptions held within an attribute into
     * schema entities.
     *
     * @param attr the attribute containing attributeTypeDescriptions
     * @return the set of attributeType objects for the descriptions
     * @throws LdapException if there are problems parsing the descriptions
     */
    public AttributeType[] parseAttributeTypes( Attribute attr ) throws LdapException
    {
        if ( ( attr == null ) || ( attr.size() == 0 ) )
        {
            return EMPTY_ATTRIBUTE_TYPES;
        }

        AttributeType[] attributeTypes = new AttributeType[attr.size()];

        int pos = 0;

        for ( Value value : attr )
        {
            AttributeType attributeType = null;

            try
            {
                attributeType = attributeTypeParser.parse( value.getString() );
            }
            catch ( ParseException e )
            {
                LdapInvalidAttributeValueException iave = new LdapInvalidAttributeValueException(
                    ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_408,
                        value.getString() ) );
                iave.initCause( e );
                throw iave;
            }

            // if the supertype is provided make sure it exists in some schema
            if ( ( attributeType.getSuperiorOid() != null )
                && !schemaManager.getAttributeTypeRegistry().contains( attributeType.getSuperiorOid() ) )
            {
                throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM,
                    I18n.err( I18n.ERR_409, attributeType.getSuperiorOid() ) );
            }

            // if the syntax is provided by the description make sure it exists in some schema
            if ( ( attributeType.getSyntaxOid() != null )
                && !schemaManager.getLdapSyntaxRegistry().contains( attributeType.getSyntaxOid() ) )
            {
                throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM,
                    I18n.err( I18n.ERR_410, attributeType.getSyntaxOid() ) );
            }

            // if the matchingRule is provided make sure it exists in some schema
            if ( ( attributeType.getEqualityOid() != null )
                && !schemaManager.getMatchingRuleRegistry().contains( attributeType.getEqualityOid() ) )
            {
                throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM,
                    I18n.err( I18n.ERR_411, attributeType.getEqualityOid() ) );
            }

            // if the matchingRule is provided make sure it exists in some schema
            if ( ( attributeType.getOrderingOid() != null )
                && !schemaManager.getMatchingRuleRegistry().contains( attributeType.getOrderingOid() ) )
            {
                throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM,
                    I18n.err( I18n.ERR_412, attributeType.getOrderingOid() ) );
            }

            // if the matchingRule is provided make sure it exists in some schema
            if ( ( attributeType.getSubstringOid() != null )
                && !schemaManager.getMatchingRuleRegistry().contains( attributeType.getSubstringOid() ) )
            {
                throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM,
                    I18n.err( I18n.ERR_413, attributeType.getSubstringOid() ) );
            }

            attributeTypes[pos++] = attributeType;
        }

        return attributeTypes;
    }

    /**
     * Parses a set of objectClassDescriptions held within an attribute into
     * schema entities.
     *
     * @param attr the attribute containing objectClassDescriptions
     * @return the set of objectClass objects for the descriptions
     * @throws LdapException if there are problems parsing the descriptions
     */
    public ObjectClass[] parseObjectClasses( Attribute attr ) throws LdapException
    {
        if ( attr == null || attr.size() == 0 )
        {
            return EMPTY_OBJECT_CLASSES;
        }

        ObjectClass[] objectClasses = new ObjectClass[attr.size()];

        int pos = 0;

        for ( Value value : attr )
        {
            ObjectClass objectClass = null;

            try
            {
                objectClass = objectClassParser.parse( value.getString() );
            }
            catch ( ParseException e )
            {
                LdapInvalidAttributeValueException iave = new LdapInvalidAttributeValueException(
                    ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_417,
                        value.getString() ) );
                iave.initCause( e );
                throw iave;
            }

            // if the super objectClasses are provided make sure it exists in some schema
            if ( objectClass.getSuperiorOids() != null && !objectClass.getSuperiorOids().isEmpty() )
            {
                for ( String superiorOid : objectClass.getSuperiorOids() )
                {
                    if ( superiorOid.equals( SchemaConstants.TOP_OC_OID )
                        || superiorOid.equalsIgnoreCase( SchemaConstants.TOP_OC ) )
                    {
                        continue;
                    }

                    if ( !schemaManager.getObjectClassRegistry().contains( superiorOid ) )
                    {
                        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM,
                            I18n.err( I18n.ERR_418, superiorOid ) );
                    }
                }
            }

            // if the may list is provided make sure attributes exists in some schema
            if ( objectClass.getMayAttributeTypeOids() != null && !objectClass.getMayAttributeTypeOids().isEmpty() )
            {
                for ( String mayAttrOid : objectClass.getMayAttributeTypeOids() )
                {
                    if ( !schemaManager.getAttributeTypeRegistry().contains( mayAttrOid ) )
                    {
                        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM,
                            I18n.err( I18n.ERR_419, mayAttrOid ) );
                    }
                }
            }

            // if the must list is provided make sure attributes exists in some schema
            if ( objectClass.getMustAttributeTypeOids() != null && !objectClass.getMustAttributeTypeOids().isEmpty() )
            {
                for ( String mustAttrOid : objectClass.getMustAttributeTypeOids() )
                {
                    if ( !schemaManager.getAttributeTypeRegistry().contains( mustAttrOid ) )
                    {
                        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM,
                            I18n.err( I18n.ERR_420, mustAttrOid ) );
                    }
                }
            }

            objectClasses[pos++] = objectClass;
        }

        return objectClasses;
    }

    /**
     * Parses a set of matchingRuleUseDescriptions held within an attribute into
     * schema entities.
     *
     * @param attr the attribute containing matchingRuleUseDescriptions
     * @return the set of matchingRuleUse objects for the descriptions
     * @throws org.apache.directory.api.ldap.model.exception.LdapException if there are problems parsing the descriptions
     */
    public MatchingRuleUse[] parseMatchingRuleUses( Attribute attr ) throws LdapException
    {
        if ( attr == null || attr.size() == 0 )
        {
            return EMPTY_MATCHING_RULE_USES;
        }

        MatchingRuleUse[] matchingRuleUses = new MatchingRuleUse[attr.size()];

        int pos = 0;

        for ( Value value : attr )
        {
            MatchingRuleUse matchingRuleUse = null;

            try
            {
                matchingRuleUse = matchingRuleUseParser.parse( value.getString() );
                matchingRuleUse.setSpecification( value.getString() );
            }
            catch ( ParseException e )
            {
                LdapInvalidAttributeValueException iave = new LdapInvalidAttributeValueException(
                    ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_421,
                        value.getString() ) );
                iave.initCause( e );
                throw iave;
            }

            matchingRuleUses[pos++] = matchingRuleUse;
        }

        return matchingRuleUses;
    }

    /**
     * Parses a set of ldapSyntaxes held within an attribute into
     * schema entities.
     *
     * @param attr the attribute containing ldapSyntaxes
     * @return the set of Syntax objects for the descriptions
     * @throws org.apache.directory.api.ldap.model.exception.LdapException if there are problems parsing the descriptions
     */
    public LdapSyntax[] parseLdapSyntaxes( Attribute attr ) throws LdapException
    {
        if ( attr == null || attr.size() == 0 )
        {
            return EMPTY_SYNTAXES;
        }

        LdapSyntax[] syntaxes = new LdapSyntax[attr.size()];

        int pos = 0;

        for ( Value value : attr )
        {
            LdapSyntax ldapSyntax = null;

            try
            {
                ldapSyntax = syntaxParser.parse( value.getString() );
                ldapSyntax.setSpecification( value.getString() );
            }
            catch ( ParseException e )
            {
                LdapInvalidAttributeValueException iave = new LdapInvalidAttributeValueException(
                    ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_422,
                        value.getString() ) );
                iave.initCause( e );
                throw iave;
            }

            if ( !schemaManager.getSyntaxCheckerRegistry().contains( ldapSyntax.getOid() ) )
            {
                throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, I18n.err( I18n.ERR_423 ) );
            }

            // Call this method once to initialize the flags
            ldapSyntax.isHumanReadable();

            syntaxes[pos++] = ldapSyntax;
        }

        return syntaxes;
    }

    /**
     * Parses a set of matchingRuleDescriptions held within an attribute into
     * schema entities.
     *
     * @param attr the attribute containing matchingRuleDescriptions
     * @return the set of matchingRule objects for the descriptions
     * @throws LdapException if there are problems parsing the descriptions
     */
    public MatchingRule[] parseMatchingRules( Attribute attr ) throws LdapException
    {
        if ( attr == null || attr.size() == 0 )
        {
            return EMPTY_MATCHING_RULES;
        }

        MatchingRule[] matchingRules = new MatchingRule[attr.size()];

        int pos = 0;

        for ( Value value : attr )
        {
            MatchingRule matchingRule = null;

            try
            {
                matchingRule = matchingRuleParser.parse( value.getString() );
                matchingRule.setSpecification( value.getString() );
            }
            catch ( ParseException e )
            {
                LdapInvalidAttributeValueException iave = new LdapInvalidAttributeValueException(
                    ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_424,
                        value.getString() ) );
                iave.initCause( e );
                throw iave;
            }

            if ( !schemaManager.getLdapSyntaxRegistry().contains( matchingRule.getSyntaxOid() ) )
            {
                throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM,
                    I18n.err( I18n.ERR_425, matchingRule.getSyntaxOid() ) );
            }

            matchingRules[pos++] = matchingRule;
        }

        return matchingRules;
    }

    /**
     * Parses a set of dITStructureRuleDescriptions held within an attribute into
     * schema entities.
     *
     * @param attr the attribute containing dITStructureRuleDescriptions
     * @return the set of DitStructureRule objects for the descriptions
     * @throws LdapException if there are problems parsing the descriptions
     */
    public DitStructureRule[] parseDitStructureRules( Attribute attr ) throws LdapException
    {
        if ( attr == null || attr.size() == 0 )
        {
            return EMPTY_DIT_STRUCTURE_RULES;
        }

        DitStructureRule[] ditStructureRules = new DitStructureRule[attr.size()];

        int pos = 0;

        for ( Value value : attr )
        {
            DitStructureRule ditStructureRule = null;

            try
            {
                ditStructureRule = ditStructureRuleParser.parse( value.getString() );
                ditStructureRule.setSpecification( value.getString() );
            }
            catch ( ParseException e )
            {
                LdapInvalidAttributeValueException iave = new LdapInvalidAttributeValueException(
                    ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_426,
                        value.getString() ) );
                iave.initCause( e );
                throw iave;
            }

            ditStructureRules[pos++] = ditStructureRule;
        }

        return ditStructureRules;
    }

    /**
     * Parses a set of dITContentRuleDescriptions held within an attribute into
     * schema entities.
     *
     * @param attr the attribute containing dITContentRuleDescriptions
     * @return the set of DitContentRule objects for the descriptions
     * @throws LdapException if there are problems parsing the descriptions
     */
    public DitContentRule[] parseDitContentRules( Attribute attr ) throws LdapException
    {
        if ( attr == null || attr.size() == 0 )
        {
            return EMPTY_DIT_CONTENT_RULES;
        }

        DitContentRule[] ditContentRules = new DitContentRule[attr.size()];

        int pos = 0;

        for ( Value value : attr )
        {
            DitContentRule ditContentRule = null;

            try
            {
                ditContentRule = ditContentRuleParser.parse( value.getString() );
                ditContentRule.setSpecification( value.getString() );
            }
            catch ( ParseException e )
            {
                LdapInvalidAttributeValueException iave = new LdapInvalidAttributeValueException(
                    ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_427,
                        value.getString() ) );
                iave.initCause( e );
                throw iave;
            }

            ditContentRules[pos++] = ditContentRule;
        }

        return ditContentRules;
    }

    /**
     * Parses a set of nameFormDescriptions held within an attribute into
     * schema entities.
     *
     * @param attr the attribute containing nameFormDescriptions
     * @return the set of NameFormRule objects for the descriptions
     * @throws LdapException if there are problems parsing the descriptions
     */
    public NameForm[] parseNameForms( Attribute attr ) throws LdapException
    {
        if ( attr == null || attr.size() == 0 )
        {
            return EMPTY_NAME_FORMS;
        }

        NameForm[] nameForms = new NameForm[attr.size()];

        int pos = 0;

        for ( Value value : attr )
        {
            NameForm nameForm = null;

            try
            {
                nameForm = nameFormParser.parse( value.getString() );
                nameForm.setSpecification( value.getString() );
            }
            catch ( ParseException e )
            {
                LdapInvalidAttributeValueException iave = new LdapInvalidAttributeValueException(
                    ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, I18n.err( I18n.ERR_428,
                        value.getString() ) );
                iave.initCause( e );
                throw iave;
            }

            nameForms[pos++] = nameForm;
        }

        return nameForms;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.zhuoyou.pay.sdk.window.ZYFloatView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#00FFFFFF" >

        <LinearLayout
            android:id="@+id/zy_float_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:alpha="0"
            android:background="@drawable/zy_float_content_bg" >

            <LinearLayout
                android:id="@+id/zy_float_center_layout"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_centerVertical="true"
                android:layout_gravity="center_vertical" >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:paddingLeft=" 8dp"
                    android:text="@string/zy_person_center"
                    android:textColor="@color/zy_float_content_textcolor"
                    android:textSize="@dimen/zy_float_content_textsize" />

                <View
                    android:id="@+id/zy_float_line_pay_center"
                    android:layout_width="@dimen/zy_float_line_width"
                    android:layout_height="@dimen/zy_float_line_height"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="@dimen/zy_float_line_margin"
                    android:background="@color/zy_float_line_color" />
            </LinearLayout>

            <RelativeLayout
                android:id="@+id/zy_float_pay_layout"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="center_vertical" >

                <TextView
                    android:id="@+id/zy_float_pay_text"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:layout_gravity="center_vertical"
                    android:paddingLeft="8dp"
                    android:text="@string/zy_pay"
                    android:textColor="@color/zy_float_content_textcolor"
                    android:textSize="@dimen/zy_float_content_textsize" />

                <ImageView
                    android:id="@+id/zy_pay_red_point"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:layout_toRightOf="@id/zy_float_pay_text"
                    android:src="@drawable/zy_red_point"
                    android:visibility="gone" />
            </RelativeLayout>

            <LinearLayout
                android:id="@+id/zy_float_activity_layout"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_centerVertical="true"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="@dimen/zy_float_line_margin" >

                <View
                    android:layout_width="@dimen/zy_float_line_width"
                    android:layout_height="@dimen/zy_float_line_height"
                    android:layout_gravity="center_vertical"
                    android:background="@color/zy_float_line_color" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:paddingLeft="8dp"
                    android:text="@string/zy_activity"
                    android:textColor="@color/zy_float_content_textcolor"
                    android:textSize="@dimen/zy_float_content_textsize" />
            </LinearLayout>

            <LinearLayout
                android:id="@+id/zy_float_gift_layout"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="@dimen/zy_float_line_margin" >

                <View
                    android:layout_width="@dimen/zy_float_line_width"
                    android:layout_height="@dimen/zy_float_line_height"
                    android:layout_gravity="center_vertical"
                    android:background="@color/zy_float_line_color" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="@dimen/zy_float_line_margin"
                    android:text="@string/zy_gift"
                    android:textColor="@color/zy_float_content_textcolor"
                    android:textSize="@dimen/zy_float_content_textsize" />
            </LinearLayout>

            <LinearLayout
                android:id="@+id/zy_float_strategy_layout"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="@dimen/zy_float_line_margin" >

                <View
                    android:layout_width="@dimen/zy_float_line_width"
                    android:layout_height="@dimen/zy_float_line_height"
                    android:layout_gravity="center_vertical"
                    android:background="@color/zy_float_line_color" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="@dimen/zy_float_line_margin"
                    android:text="@string/zy_strategy"
                    android:textColor="@color/zy_float_content_textcolor"
                    android:textSize="@dimen/zy_float_content_textsize" />
            </LinearLayout>
        </LinearLayout>
    </com.zhuoyou.pay.sdk.window.ZYFloatView>

    <LinearLayout
        android:id="@+id/zy_jw_pay_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/zy_jw_pay_status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:alpha="0.2"
            android:background="#000000"
            android:clickable="false"
            android:textColor="#ffffff"
            android:textSize="14sp" />

        <ImageView
            android:id="@+id/zy_jw_pay_cancel"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            android:alpha="0.3"
            android:background="#000000"
            android:src="@drawable/zy_pay_cancel"
            android:visibility="gone" />
    </LinearLayout>

</RelativeLayout>