text:
package com.intellij.openapi.options;

import com.intellij.AbstractBundle;
import com.intellij.CommonBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.AbstractExtensionPointBean;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.AtomicNotNullLazyValue;
import com.intellij.util.xmlb.annotations.AbstractCollection;
import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.util.xmlb.annotations.Property;
import com.intellij.util.xmlb.annotations.Tag;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.picocontainer.PicoContainer;

import java.util.ResourceBundle;

/**
 * Declares a named component that enables to configure settings.
 *
 * @author nik
 * @see Configurable
 */
@Tag("configurable")
public class ConfigurableEP<T extends UnnamedConfigurable> extends AbstractExtensionPointBean {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.options.ConfigurableEP");

  /**
   * This attribute specifies the setting name visible to users.
   * It has precedence over the pair of attributes {@link #key}-{@link #bundle}.
   * If the display name is not set, a configurable component will be instantiated to retrieve its name dynamically.
   * This causes a loading of plugin classes and increases the delay before showing the settings dialog.
   * It is highly recommended specifying the display name in XML to improve UI responsiveness.
   */
  @Attribute("displayName")
  public String displayName;

  /**
   * This attribute specifies the resource key in the specified {@link #bundle}.
   * This is another way to specify the {@link #displayName display name}.
   */
  @Attribute("key")
  public String key;

  /**
   * This attribute specifies the resource bundle that contains the specified {@link #key}.
   * This is another way to specify the {@link #displayName display name}.
   */
  @Attribute("bundle")
  public String bundle;

  public String getDisplayName() {
    if (displayName != null) return displayName;
    LOG.assertTrue(bundle != null, "Bundle missed for " + instanceClass);
    final ResourceBundle resourceBundle = AbstractBundle.getResourceBundle(bundle, myPluginDescriptor.getPluginClassLoader());
    return displayName = CommonBundle.message(resourceBundle, key);
  }

  /**
   * @return a resource bundle using the specified base name or {@code null}
   */
  public ResourceBundle findBundle() {
    return bundle == null ? null : AbstractBundle.getResourceBundle(bundle, myPluginDescriptor != null
                                                                            ? myPluginDescriptor.getPluginClassLoader()
                                                                            : getClass().getClassLoader());
  }

  @Property(surroundWithTag = false)
  @AbstractCollection(surroundWithTag = false)
  public ConfigurableEP[] children;

  /**
   * This attribute specifies a name of the extension point of {@code ConfigurableEP} type that will be used to calculate children.
   *
   * @see #dynamic
   */
  @Attribute("childrenEPName")
  public String childrenEPName;

  /**
   * This attribute states that a custom configurable component implements the {@link Configurable.Composite} interface
   * and its children are dynamically calculated by calling the {@link Configurable.Composite#getConfigurables()} method.
   * It is needed to improve performance, because we do not want to load any additional classes during the building a setting tree.
   */
  @Attribute("dynamic")
  public boolean dynamic;

  /**
   * This attribute is used to create a hierarchy of settings.
   * If it is set, the configurable component will be a child of the specified parent component.
   *
   * @see #groupId
   */
  @Attribute("parentId")
  public String parentId;

  public ConfigurableEP[] getChildren() {
    for (ConfigurableEP child : children) {
      child.myPicoContainer = myPicoContainer;
      child.myPluginDescriptor = myPluginDescriptor;
      child.myProject = myProject;
    }
    return children;
  }

  /**
   * This attribute specifies the {@link SearchableConfigurable#getId() unique identifier} of the configurable component.
   * It is also recommended specifying the identifier in XML to improve UI responsiveness.
   */
  @Attribute("id")
  public String id;

  /**
   * This attribute specifies a top-level group, which the configurable component belongs to.
   * If this attribute is not set, the configurable component will be added to the Other Settings group.
   * The following groups are supported:
   *

   *
ROOT {@code groupId="root"}

   *
This is the invisible root group that contains all other groups.
   * Usually, you should not place your settings here.

   *
Appearance & Behavior {@code groupId="appearance"}

   *
This group contains settings to personalize IDE appearance and behavior:
   * change themes and font size, tune the keymap, and configure plugins and system settings,
   * such as password policies, HTTP proxy, updates and more.

   *
Editor {@code groupId="editor"}

   *
This group contains settings to personalize source code appearance by changing fonts,
   * highlighting styles, indents, etc.  Here you can customize the editor from line numbers,
   * caret placement and tabs to source code inspections, setting up templates and file encodings.

   *
Default Project / Project Settings {@code groupId="project"}

   *
This group is intended to store some project-related settings, but now it is rarely used.

   *
Build, Execution, Deployment {@code groupId="build"}

   *
This group contains settings to configure you project integration with the different build tools,
   * modify the default compiler settings, manage server access configurations, customize the debugger behavior, etc.

   *
Build Tools {@code groupId="build.tools"}

   *
This is subgroup of the group above. Here you can configure your project integration
   * with the different build tools, such as Maven, Gradle, or Gant.

   *
Languages & Frameworks {@code groupId="language"}

   *
This group is intended to configure the settings related to specific frameworks and technologies used in your project.

   *
Tools {@code groupId="tools"}

   *
This group contains settings to configure integration with third-party applications,
   * specify the SSH Terminal connection settings, manage server certificates and tasks, configure diagrams layout, etc.

   *
Other Settings {@code groupId="other"}

   *
This group contains settings that are related to non-bundled custom plugins and are not assigned to any other category.

   *

   * This attribute should not be used together with the {@link #parentId} attribute, which has precedence.
   * Currently, it is possible to specify a group identifier in the {@link #parentId} attribute.
   */
  @Attribute("groupId")
  public String groupId;

  /**
   * This attribute specifies the weight of a configurable component within a group or a parent configurable component.
   * The default weight is {@code 0}. If one child in a group or a parent configurable component has non-zero weight,
   * all children will be sorted descending by their weight. And if the weights are equal,
   * the components will be sorted ascending by their display name.
   */
  @Attribute("groupWeight")
  public int groupWeight;

  /**
   * This attribute is applicable to the {@code projectConfigurable} extension only.
   * If it is set to {@code true}, the corresponding project settings will be shown for a real project only,
   * not for the {@link com.intellij.openapi.project.ProjectManager#getDefaultProject() template project},
   * which provides default settings for all the new projects.
   */
  @Attribute("nonDefaultProject")
  public boolean nonDefaultProject;

  public boolean isAvailable() {
    return !nonDefaultProject || !(myProject != null  && myProject.isDefault());
  }

  /**
   * @deprecated use '{@link #instanceClass instance}' or '{@link #providerClass provider}' attribute instead
   */
  @Deprecated
  @Attribute("implementation")
  public String implementationClass;

  /**
   * This attribute specifies a qualified name of a custom implementation of this interface.
   * The constructor will be determined automatically from the tag name:
   *
{@code <extensions defaultExtensionNs="com.intellij">}
   *
{@code     <projectConfigurable instance="fully.qualified.class.name"/>}
   *
{@code </extensions>}
   *
   * @see #providerClass provider
   */
  @Attribute("instance")
  public String instanceClass;

  /**
   * This attribute can be used instead of the {@link #instanceClass instance} attribute.
   * It specifies a qualified name of a custom implementation of the {@link ConfigurableProvider} interface,
   * which provides another way to create a configurable component:
   *
{@code <extensions defaultExtensionNs="com.intellij">}
   *
{@code     <projectConfigurable provider="fully.qualified.class.name"/>}
   *
{@code </extensions>}
   *
   * @see #instanceClass instance
   */
  @Attribute("provider")
  public String providerClass;

  private final AtomicNotNullLazyValue<ObjectProducer> myProducer;
  private PicoContainer myPicoContainer;
  private Project myProject;

  public ConfigurableEP() {
    this(ApplicationManager.getApplication().getPicoContainer(), null);
  }

  @SuppressWarnings("UnusedDeclaration")
  public ConfigurableEP(Project project) {
    this(project.getPicoContainer(), project);
  }

  protected ConfigurableEP(PicoContainer picoContainer, @Nullable Project project) {
    myProject = project;
    myPicoContainer = picoContainer;
    myProducer = new AtomicNotNullLazyValue<ObjectProducer>() {
      @NotNull
      @Override
      protected ObjectProducer compute() {
        try {
          if (providerClass != null) {
            return new ProviderProducer((ConfigurableProvider)instantiate(providerClass, myPicoContainer));
          }
          if (instanceClass != null) {
            return new ClassProducer(myPicoContainer, findClass(instanceClass));
          }
          if (implementationClass != null) {
            return new ClassProducer(myPicoContainer, findClass(implementationClass));
          }
          throw new RuntimeException("configurable class name is not set");
        }
        catch (AssertionError | Exception | LinkageError error) {
          LOG.error(error);
        }
        return new ObjectProducer();
      }
    };
  }

  @Nullable
  public T createConfigurable() {
    ObjectProducer producer = myProducer.getValue();
    if (producer.canCreateElement()) {
      @SuppressWarnings("unchecked")
      T configurable = (T)producer.createElement();
      return configurable;
    }
    return null;
  }

  public Project getProject() {
    return myProject;
  }

  @Override
  public String toString() {
    return getDisplayName();
  }

  public boolean canCreateConfigurable() {
    return myProducer.getValue().canCreateElement();
  }

  /**
   * Returns the type of configurable to create or {@code null},
   * if it cannot be determined.
   *
   * @return the the configurable's type or {@code null}
   */
  @Nullable
  public Class<?> getConfigurableType() {
    return myProducer.getValue().getType();
  }

  private static class ObjectProducer {
    Object createElement() {
      return null;
    }

    boolean canCreateElement() {
      return false;
    }

    Class<?> getType() {
      return null;
    }
  }

  private static final class ProviderProducer extends ObjectProducer {
    private final ConfigurableProvider myProvider;

    private ProviderProducer(ConfigurableProvider provider) {
      myProvider = provider;
    }

    @Override
    Object createElement() {
      return myProvider == null ? null : myProvider.createConfigurable();
    }

    @Override
    boolean canCreateElement() {
      return myProvider != null && myProvider.canCreateConfigurable();
    }
  }

  private static final class ClassProducer extends ObjectProducer {
    private final PicoContainer myContainer;
    private final Class<?> myType;

    private ClassProducer(PicoContainer container, Class<?> type) {
      myContainer = container;
      myType = type;
    }

    @Override
    Object createElement() {
      try {
        return instantiate(myType, myContainer, true);
      }
      catch (ProcessCanceledException exception) {
        throw exception;
      }
      catch (AssertionError | LinkageError | Exception e) {
        LOG.error(e);
      }
      return null;
    }

    @Override
    boolean canCreateElement() {
      return myType != null;
    }

    Class<?> getType() {
      return myType;
    }
  }
}


text:
/*jshint -W020 */

theApp = null;

var $ = require('jquery');

var Backbone = require('backbone');
var Plumage = require('plumage');
var KitchenSinkRouter = require('kitchen_sink/KitchenSinkRouter');
var KitchenSinkNavView = require('kitchen_sink/KitchenSinkNavView');
var KitchenSinkController = require('kitchen_sink/controller/KitchenSinkController');

//Backbone.$ = $;

$(function() {
  var navView = new KitchenSinkNavView();
  theApp = new Plumage.App({
    navView: navView
  });

  var controllers = {
    'kitchenSinkController': new KitchenSinkController(theApp)
  };

  $('#nav').html(navView.render().el);

  var rootUrl = '/kitchen_sink.html';

  window.router = new KitchenSinkRouter({
    app: theApp,
    controllers: controllers,
    defaultUrl: rootUrl,
    rootUrl: rootUrl,
    pushState: false
  });
  window.router.start();
});

redpajama_set_name: RedPajamaGithub


text:
package org.oscm.billingservice.business.calculation.share;

import org.junit.BeforeClass;
import org.junit.Test;

import org.oscm.billingservice.business.calculation.share.setup.SharesAllSellersSetup;
import org.oscm.billingservice.evaluation.BrokerShareResultEvaluator;
import org.oscm.billingservice.evaluation.MarketplaceShareResultEvaluator;
import org.oscm.billingservice.evaluation.ResellerShareResultEvaluator;
import org.oscm.billingservice.evaluation.SupplierShareResultEvaluator;
import org.oscm.billingservice.setup.BillingIntegrationTestBase;
import org.oscm.billingservice.setup.CustomerData;
import org.oscm.billingservice.setup.TestData;
import org.oscm.billingservice.setup.VendorData;
import org.oscm.internal.vo.VOServiceDetails;

/**
 * @author farmaki
 *
 */
public class SharesAllSellersIT extends BillingIntegrationTestBase {

    private SharesAllSellersSetup testSetup = new SharesAllSellersSetup();

    @BeforeClass
    public static void setupOnce() throws Exception {
        BillingIntegrationTestBase.initialize();
        BillingIntegrationTestBase.createBasicTestData(true);
    }

    /**
     * Test the revenue share results for all sellers (supplier, broker
     * reseller, mp owner)
     */
    @Test
    public void sharesForAllSellers() throws Exception {
        // given
        testSetup.setupAllSellers("testSharesForAllSellers");
        TestData testData = getTestData("testSharesForAllSellers");

        VendorData supplier = testData.getVendor(0);
        VendorData broker = testData.getVendor(1);
        VendorData reseller = testData.getVendor(2);

        VOServiceDetails supplierService = supplier.getService(0);
        VOServiceDetails brokerService = broker.getService(0);
        VOServiceDetails resellerService = reseller.getService(0);

        String supplierMpId = supplier.getMarketplaceId(0);
        String brokerMpId = broker.getMarketplaceId(0);
        String resellerMpId = reseller.getMarketplaceId(0);

        // when
        performBillingRun(0, "2013-02-05 00:00:00");

        // then verify all Revenue Share Results
        assertSupplierRevenueShareResult_sharesForAllSellers(supplier, broker,
                reseller, "2013-01-01 00:00:00", "2013-02-01 00:00:00");
        assertBrokerRevenueShareResult_sharesForAllSellers(supplier, broker,
                "2013-01-01 00:00:00", "2013-02-01 00:00:00");
        assertResellerRevenueShareResult_sharesForAllSellers(supplier,
                reseller, "2013-01-01 00:00:00", "2013-02-01 00:00:00");

        // verify MarketplaceOwnerRevenueShareResult for supplier
        MarketplaceShareResultEvaluator mpEvaSupplier = newMarketplaceShareResultEvaluator(
                supplier.getOrganizationKey(), "2013-01-01 00:00:00",
                "2013-02-01 00:00:00");

        mpEvaSupplier.assertRevenueShareDetails(supplierMpId, supplierService,
                "4950.00", "0.00", "0.00", "5.00", "247.50", "4702.50");
        mpEvaSupplier.assertSuppliers(supplierMpId, "4702.50", "4950.00",
                "0.00");
        mpEvaSupplier.assertSuppliersOrganization(supplierMpId,
                supplier.getOrganizationId(), "4702.50", "4950.00", "0.00");
        mpEvaSupplier.assertBrokers(supplierMpId, "0.00", "0.00", "0.00");
        mpEvaSupplier.assertResellers(supplierMpId, "0.00", "0.00", "0.00");
        mpEvaSupplier.assertMarketplaceOwner(supplierMpId, "0.00");
        mpEvaSupplier.assertOverallSuppliers("4702.50", "4950.00", "0.00");
        mpEvaSupplier.assertOverallSuppliersOrganization(
                supplier.getOrganizationId(), "4702.50", "4950.00", "0.00");
        mpEvaSupplier.assertOverallBrokers("0.00", "0.00", "0.00");
        mpEvaSupplier.assertOverallResellers("0.00", "0.00", "0.00");

        // verify MarketplaceOwnerRevenueShareResult for broker
        MarketplaceShareResultEvaluator mpEvaBroker = newMarketplaceShareResultEvaluator(
                broker.getOrganizationKey(), "2013-01-01 00:00:00",
                "2013-02-01 00:00:00");

        mpEvaBroker.assertRevenueShareDetails_BrokerService(brokerMpId,
                brokerService, "4950.00", "10.00", "495.00", "5.00", "247.50",
                "15.00", "742.50", "3465.00");
        mpEvaBroker.assertSuppliers(brokerMpId, "3465.00", "0.00", "0.00");
        mpEvaBroker.assertSuppliersOrganization(brokerMpId,
                supplier.getOrganizationId(), "3465.00", "0.00", "0.00");
        mpEvaBroker.assertBrokers(brokerMpId, "742.50", "4950.00", "495.00");
        mpEvaBroker.assertBrokersOrganization(brokerMpId,
                broker.getOrganizationId(), "742.50", "4950.00", "495.00");
        mpEvaBroker.assertResellers(brokerMpId, "0.00", "0.00", "0.00");
        mpEvaBroker.assertMarketplaceOwner(brokerMpId, "495.00");
        mpEvaBroker.assertOverallSuppliers("3465.00", "0.00", "0.00");
        mpEvaBroker.assertOverallSuppliersOrganization(
                supplier.getOrganizationId(), "3465.00", "0.00", "0.00");
        mpEvaBroker.assertOverallBrokers("742.50", "4950.00", "495.00");
        mpEvaBroker.assertOverallBrokersOrganization(
                broker.getOrganizationId(), "742.50", "4950.00", "495.00");
        mpEvaBroker.assertOverallResellers("0.00", "0.00", "0.00");

        // verify MarketplaceOwnerRevenueShareResult for reseller
        MarketplaceShareResultEvaluator mpEvaReseller = newMarketplaceShareResultEvaluator(
                reseller.getOrganizationKey(), "2013-01-01 00:00:00",
                "2013-02-01 00:00:00");

        mpEvaReseller.assertRevenueShareDetails_ResellerService(resellerMpId,
                resellerService, "4950.00", "10.00", "495.00", "5.00",
                "247.50", "20.00", "990.00", "3217.50");
        mpEvaReseller.assertSuppliers(resellerMpId, "3217.50", "0.00", "0.00");
        mpEvaReseller.assertSuppliersOrganization(resellerMpId,
                supplier.getOrganizationId(), "3217.50", "0.00", "0.00");
        mpEvaReseller.assertResellers(resellerMpId, "990.00", "4950.00",
                "495.00");
        mpEvaReseller.assertResellersOrganization(resellerMpId,
                reseller.getOrganizationId(), "990.00", "4950.00", "495.00");
        mpEvaReseller.assertBrokers(resellerMpId, "0.00", "0.00", "0.00");
        mpEvaReseller.assertMarketplaceOwner(resellerMpId, "495.00");
        mpEvaReseller.assertOverallSuppliers("3217.50", "0.00", "0.00");
        mpEvaReseller.assertOverallSuppliersOrganization(
                supplier.getOrganizationId(), "3217.50", "0.00", "0.00");
        mpEvaReseller.assertOverallResellers("990.00", "4950.00", "495.00");
        mpEvaReseller.assertOverallResellersOrganization(
                reseller.getOrganizationId(), "990.00", "4950.00", "495.00");
        mpEvaReseller.assertOverallBrokers("0.00", "0.00", "0.00");

    }

    private void assertResellerRevenueShareResult_sharesForAllSellers(
            VendorData supplier, VendorData reseller, String periodStart,
            String periodEnd) throws Exception {
        CustomerData resellerCustomer = reseller.getCustomer(0);
        VOServiceDetails resellerService = reseller.getService(0);

        ResellerShareResultEvaluator resellerEva = newResellerShareResultEvaluator(
                reseller.getOrganizationKey(), periodStart, periodEnd);

        resellerEva.assertSubscription(supplier.getOrganizationId(),
                "resellerSubscr1", resellerService, "4950.00");
        resellerEva.assertServiceRevenue(supplier.getOrganizationId(),
                resellerService, "4950.00", "20.00", "990.00");
        resellerEva.assertServiceCustomerRevenue(supplier.getOrganizationId(),
                resellerService, resellerCustomer.getOrganizationId(),
                "4950.00", "20.00", "990.00");
        resellerEva.assertResellerRevenuePerSupplier(
                supplier.getOrganizationId(), "4950.00", "990.00", "3960.00");
        resellerEva.assertResellerRevenue("4950.00", "990.00", "3960.00");
    }

    private void assertBrokerRevenueShareResult_sharesForAllSellers(
            VendorData supplier, VendorData broker, String periodStart,
            String periodEnd) throws Exception {
        CustomerData brokerCustomer = broker.getCustomer(0);
        VOServiceDetails brokerService = broker.getService(0);

        BrokerShareResultEvaluator brokerEva = newBrokerShareResultEvaluator(
                broker.getOrganizationKey(), periodStart, periodEnd);

        brokerEva.assertServiceRevenue(supplier.getOrganizationId(),
                brokerService, "4950.00", "15.00", "742.50");
        brokerEva.assertServiceCustomerRevenue(supplier.getOrganizationId(),
                brokerService, brokerCustomer.getOrganizationId(), "4950.00",
                "15.00", "742.50");
        brokerEva.assertBrokerRevenuePerSupplier(supplier.getOrganizationId(),
                "4950.00", "742.50");
        brokerEva.assertBrokerRevenue("4950.00", "742.50");
    }

    private void assertSupplierRevenueShareResult_sharesForAllSellers(
            VendorData supplier, VendorData broker, VendorData reseller,
            String periodStart, String periodEnd) throws Exception {
        CustomerData supplierCustomer = supplier.getCustomer(0);
        CustomerData brokerCustomer = broker.getCustomer(0);

        VOServiceDetails supplierService = supplier.getService(0);
        VOServiceDetails brokerService = broker.getService(0);
        VOServiceDetails resellerService = reseller.getService(0);

        String supplierMpId = supplier.getMarketplaceId(0);
        String brokerMpId = broker.getMarketplaceId(0);
        String resellerMpId = reseller.getMarketplaceId(0);

        SupplierShareResultEvaluator supplEva = newSupplierShareResultEvaluator(
                supplier.getOrganizationKey(), periodStart, periodEnd);

        supplEva.assertRevenuePerMarketplace(supplierMpId, "4950.00", "0.00",
                "247.50", "0.00", "0.00", "4702.50");
        supplEva.assertRevenuePerMarketplace(brokerMpId, "4950.00", "495.00",
                "247.50", "0.00", "742.50", "3465.00");
        supplEva.assertRevenuePerMarketplace(resellerMpId, "4950.00", "495.00",
                "247.50", "990.00", "0.00", "3217.50");

        supplEva.assertRevenueShareDetails(supplierMpId, supplierService,
                "4950.00", "0.00", "0.00", "5.00", "247.50", "4702.50");
        supplEva.assertRevenueShareDetails_BrokerService(brokerMpId,
                brokerService, "4950.00", "10.00", "495.00", "5.00", "247.50",
                "15.00", "742.50", "3465.00");

        supplEva.assertCustomerRevenueShareDetails(supplierMpId,
                supplierService, supplierCustomer.getOrganization()
                        .getOrganizationId(), "4950.00", "0.00", "247.50",
                "4702.50");
        supplEva.assertCustomerRevenueShareDetails_BrokerService(brokerMpId,
                brokerService, brokerCustomer.getOrganizationId(), "4950.00",
                "495.00", "247.50", "3465.00", "742.50");

        supplEva.assertSubscription(supplierMpId, "supplierSubscr1",
                supplierService, "4950.00");
        supplEva.assertSubscription(brokerMpId, "brokerSubscr1", brokerService,
                "4950.00");
        supplEva.assertSubscriptionsRevenue(resellerMpId, resellerService,
                "4950.00");

        supplEva.assertSupplierRevenue("11385.00");
        supplEva.assertDirectRevenue("4950.00", "0.00", "247.50");
        supplEva.assertBrokerRevenue("4950.00", "495.00", "247.50", "742.50");
        supplEva.assertResellerRevenue("4950.00", "495.00", "247.50", "990.00",
                "3217.50");
    }

}


text:
package org.eclipse.bpel.validator.rules;

import java.util.List;

import javax.xml.namespace.QName;

import org.eclipse.bpel.validator.model.ARule;
import org.eclipse.bpel.validator.model.Filter;
import org.eclipse.bpel.validator.model.Filters;
import org.eclipse.bpel.validator.model.IFilter;
import org.eclipse.bpel.validator.model.IModelQueryLookups;
import org.eclipse.bpel.validator.model.INode;
import org.eclipse.bpel.validator.model.IProblem;
import org.eclipse.bpel.validator.model.NodeNameFilter;
import org.eclipse.bpel.validator.model.ValueFilter;

/**
 * Dependency on the BPEL validation model only in here.
 * Structurarily, the onEvent looks like this
 * <pre>
   <onEvent partnerLink="NCName"
      portType="QName"?
      operation="NCName"
      ( messageType="QName" | element="QName" )?
      variable="BPELVariableName"?
      messageExchange="NCName"?>*
      <correlations>?
         <correlation set="NCName" initiate="yes|join|no"? />+
      </correlations>
      <fromParts>?
         <fromPart part="NCName" toVariable="BPELVariableName" />+
      </fromParts>
      <scope ...>...</scope>
    </onEvent>
   </pre>
 */

/**
 * @author Michal Chmielewski (michal.chmielewski@oracle.com)
 * @date Aug 28, 2008
 *
 */

@SuppressWarnings( {"hiding","nls","boxing"} )
public class OnEventValidator extends CPartnerActivityValidator {

	protected INode fMyRoleNode;

	protected INode fVariable;
	protected INode fPortTypeFromRole;
	protected INode fAssociatedScope;

	protected String fCreateInstance;

	protected int fFromPartsCount;

	protected String fVariableName;

	private INode fVariableType;

	/** The parent nodes */
	static public IFilter<INode> PARENTS = new NodeNameFilter( ND_EVENT_HANDLERS );

	/** (non-Javadoc)
	 * @see org.eclipse.bpel.validator.rules.CValidator#checkChildren()
	 */
	@Override
	public void checkChildren () {
		super.checkChildren();
		fFromPartsCount = checkChild(ND_FROM_PARTS,0,1);
		checkChild(ND_SCOPE, 1, 1);
	}

	/**
	 *
	 * @see org.eclipse.bpel.validator.model.Validator#start()
	 */

	@Override
	protected void start () {
		super.start();

		fAssociatedScope = mSelector.selectNode(mNode, ND_SCOPE);

		setValue("associated.scope",fAssociatedScope);
	}

	/**
	 * @see org.eclipse.bpel.validator.rules.CActivityValidator#rule_CheckName_1()
	 */
	@Override
	public void rule_CheckName_1() {
		// we don't check the name, disable it here.
	}

	/**
	 * @see org.eclipse.bpel.validator.rules.CActivityValidator#rule_CheckSuppressJoinFailure_1()
	 */
	@Override
	public void rule_CheckSuppressJoinFailure_1() {
		// we don't do anything here, disable it on OnMessage
	}

	/**
	 * @see org.eclipse.bpel.validator.rules.CPartnerActivityValidator#rule_LookupPartnerLink_0()
	 *
	 * This method overrides the same method in the parent class.
	 */

	@ARule(
		sa = 84,
		desc = "Partner Link resolution: associated scope first, then ancestor scopes",
		author = "michal.chmielewski@oracle.com",
		date = "03/15/2007",
		errors = "BPELC_MISSING_ROLE"
	)
	@Override
	public void rule_LookupPartnerLink_0 () {

		INode context = fAssociatedScope;

		if (isUndefined(context)) {
			context = mNode;
		}

		fPartnerLinkNode = mModelQuery.lookup (context ,
				IModelQueryLookups.LOOKUP_NODE_PARTNER_LINK ,
				mNode.getAttribute( AT_PARTNER_LINK ) );

		markSAExecution(null);
	}

	static IFilter<QName> TYPE_DEFS = new ValueFilter<QName>(
			Filter.QNAME_COMPARATOR,
			AT_MESSAGE_TYPE, AT_ELEMENT);

	/**
	 * If the variable attribute is used in the <onEvent> element, either the
	 * messageType or the element attribute MUST be provided in the <onEvent>
	 * element.
	 */
	@ARule(
		sa = 90,
		desc = "Either messageType or element must be specified if variable variant is used",
		date = "3/15/2007",
		author = "michal.chmielewski@oracle.com",
		errors="BPELC__UNSET_ATTRIBUTE,BPELC__UNRESOLVED_ATTRIBUTE,BPELC__INVALID_ATTRIBUTE_VALUE,BPELC__AT_LEAST_ONE,BPELC__AT_MOST_ONE,BPELC__SPECIFY_NONE"
	)

	public void rule_LookupVariable_5 () {

		fVariableName = getAttribute(mNode, AT_VARIABLE, KIND_ACTIVITY, Filters.NC_NAME, false);

		IProblem problem;

		// messageType or element must be used
		String msgType = mNode.getAttribute(AT_MESSAGE_TYPE);
		String elmDecl = mNode.getAttribute(AT_ELEMENT);

		boolean bMsgTypeEmpty = isEmptyOrWhitespace(msgType);
		boolean bElmDeclEmpty = isEmptyOrWhitespace(elmDecl);

		if (isEmpty(fVariableName) == false) {

			// both empty
			if ( bElmDeclEmpty && bMsgTypeEmpty) {

				problem = createError();
				problem.fill("BPELC__AT_LEAST_ONE",
						toString(mNode.nodeName()),
						KIND_ACTIVITY,
						TYPE_DEFS,
						KIND_ATTRIBUTE
				);

				return ;
			}

			// both specified
			if ( !bElmDeclEmpty && !bMsgTypeEmpty) {

				problem = createError();
				problem.fill("BPELC__AT_MOST_ONE",
						toString(mNode.nodeName()),
						KIND_ACTIVITY,
						TYPE_DEFS,
						KIND_ATTRIBUTE
				);
			}

			if (!bElmDeclEmpty) {
				// element is specified
				fVariableType = mModelQuery.lookup(mNode,
						IModelQueryLookups.LOOKUP_NODE_XSD_ELEMENT,elmDecl);
				checkAttributeNode(mNode, fVariableType, AT_ELEMENT, KIND_ACTIVITY);

			}

			if (!bMsgTypeEmpty) {
				// message type is specified
				fVariableType = mModelQuery.lookup(mNode,
						IModelQueryLookups.LOOKUP_NODE_MESSAGE_TYPE,msgType);
				checkAttributeNode(mNode, fVariableType, AT_MESSAGE_TYPE, KIND_ACTIVITY);
			}

		} else {

			// the message type or element declaration must not be present
			if (!bMsgTypeEmpty || !bElmDeclEmpty) {
				problem = createError();
				problem.fill("BPELC__SPECIFY_NONE",
						toString(mNode.nodeName()),
						KIND_NODE,
						TYPE_DEFS,
						KIND_ATTRIBUTE);
			}
		}

	}

	/**
	 * Check if the partner role is defined on this partner link.
	 */

	@ARule(
			sa = 84,
			author = "michal.chmielewski@oracle.com",
			date = "9/25/2006",
			desc = "Checks if my role is defined in onMessage activity.",
			errors = "BPELC_MISSING_ROLE"
		)
	public void rule_CheckIfMyRoleIsDefined_5 () {
		fMyRoleNode = lookupRoleNode ( fPartnerLinkNode , AT_MY_ROLE );
	}

	/**
	 * Check if the partnerLinkType derived port type and the port type present
	 * on the receive are one and the same.
	 */
	@ARule(
		author = "michal.chmielewski@oracle.com",
		date = "03/13/2007",
		desc = "Checks portType and derived portType values on onEvent.",
		sa = 5 ,
		errors="BPELC_MISMATCH_ROLE_PORT_TYPE"
	)

	public void rule_CheckRolePortTypeWithReceivePortType_10 ()	{
		fPortTypeFromRole = verifyPortTypeFromRole ( fMyRoleNode, AT_MY_ROLE, fPortType ) ;
	}

	/**
	 * 1) Receive needs myRole set.
	 * 2) myRole -> portType
	 * 3) portType (has operations) -> operation
	 * 4) operation -> "input" message must be set.
	 */

	INode fInputMessage ;

	/**
	 * Checks the Input Message for the receive. This just makes
	 * sure that input message is defined in the WSDL.
	 *
	 */

	@ARule(
			author = "michal.chmielewski@oracle.com",
			date = "9/25/2006",
			desc = "Checks if input message is defined for onEvent activity.",
			errors="BPELC_PA__NO_MESSAGE,BPELC_PA__MSG_TYPE"
		)
	public void rule_CheckInputMessage_12 () {
		fInputMessage = findMessageType (fPortTypeFromRole, fOperation,WSDL_ND_INPUT, true );
		setValue("input.message.type", fInputMessage);
	}

	/**
	 *
	 */
	@ARule(
		sa = 87,
		desc = "Check message type compatability on onEvent",
		author = "michal.chmielewski@oracle.com",
		date = "03/15/2007",
		errors="BPELC_PA__MESSAGE_TYPE_MISMATCH"
	)
	public void rule_CheckVariableAndMessageStructureCompatibility_20 ()
	{
		IProblem problem;

		if (isUndefined(fInputMessage)  || isUndefined( fVariableType )) {
			return ;
		}

		// source -> destination
		if (mModelQuery.check( IModelQueryLookups.TEST_COMPATIBLE_PARTNER_ACTIVITY_MESSAGE, fVariableType, fInputMessage ) == false) {

			problem = createError( );
			problem.fill( "BPELC_PA__MESSAGE_TYPE_MISMATCH",  //$NON-NLS-1$
					toString(mNode.nodeName()),
					AT_VARIABLE,
					fVariableName,
					fInputMessage,
					fVariableType
			);
		}

		markSAExecution(null);
	}

	/**
	 * Check the presence of fromParts.
	 */

	@ARule(
		sa = 85,
		desc = "Check to see if fromPart is specified; if so then " +
		       " variable must not be used onEvent.",
		author = "michal.chmielewski@oracle.com",
		date = "03/20/2007",
		errors="BPELC__PA_PARTS"
	)
	public void rule_checkFromPartsPresence_50 () {

		List<INode> fFromParts;

		fFromParts = mSelector.selectNodes(mNode, ND_FROM_PARTS, ND_FROM_PART );

		IProblem problem;

		boolean bNoVariable = isEmptyOrWhitespace(mNode.getAttribute(AT_VARIABLE));
		if (fFromParts.size() > 0 && !bNoVariable)  {
			problem = createError();
			problem.fill("BPELC__PA_PARTS",
					toString(mNode.nodeName()),
					ND_FROM_PART,
					AT_VARIABLE,
					KIND_ACTIVITY);
		}

		if (fFromParts.size() == 0 && bNoVariable) {
			problem = createError();
			problem.fill("BPELC__PA_PARTS",
					toString(mNode.nodeName()),
					ND_FROM_PART,
					AT_VARIABLE,
					KIND_ACTIVITY);
		}
	}

}


text:
<#
    .Synopsis
    PowerShell script which can manage delegates for an exchange mailbox

    .Description

    With this script you can add, remove or list deletgates for an exchange mailbox

    Author: Torsten Schlopsnies

    Version 1.6 2018-05-07

    .NOTES
    Requirements
    - EWS 2.2 installed
    - Impersonation rights
    - Exchange 2013 (tested with CU17) or higher (runs maybe for Exchange 2010 also)
    - GlobalFunctions from Thomas Stensitzki (for logging and console output) => https://github.com/Apoc70/GlobalFunctions

    Revision History
    --------------------------------------------------------------------------------
    1.0     Initial release
    1.1     fixed behaviour when altering delegates
    1.5:
            - fixed various bugs (regarding impersonation, logical).
            - Removed "Mode" switch
            - added possibility to pass credentials and url
            - SSL certificate errors can be ignored now
            - You can remove/set multiple users to one mailbox
            - Instead of the switches from earlier versions you now have to pass $true or $false
    1.6:
            - fixed bug (adding delegates when delegatelist is empty)

    Based on a article from Glen: http://gsexdev.blogspot.de/2012/03/ews-managed-api-and-powershell-how-to.html

    .PARAMETER Identity
    Type: String
    Format: mail address (primary smtp address)
    The mailbox you whish to alter

    .PARAMETER Credentials
    Type: PSCredentials
    Credentials which will be used to create the service.

    .PARAMETER UseDefaultCredentials
    Type: boolean
    Default: $false
    On domain joined computer you can use the session credentials. With this switch these will be passed to the service.

    .PARAMETER Url
    Type: string
    Format: https://servername/ews/exchange.asmx
    To connect to a specific server set this parameter. If not set autodiscover will be used.

    .PARAMETER IgnoreSSLCertificate
    Type: boolean
    Default: $false
    If set invalid SSL certificates will be ignored.

    .PARAMETER Impersonate
    Type: boolean
    Default: $false
    Use if you need to impersonate (alter other mailboxes than yours).

    .PARAMETER DelegateToRemove
    Type: string
    Format: mail address (primary smtp address)
    Define the delegate you want to remove.

    .PARAMETER DelegateToSet
    Type: string
    Format: mail address (primary smtp address)
    Define the delegate you want to set or add.

    .PARAMETER CalendarPermissions
    Type: string
    Allowed value: "None","Reviewer","Author","Editor"
    Default: "None"
    Set the permission for the calendar.

    .PARAMETER ContactsPermissions
    Type: string
    Allowed value: "None","Reviewer","Author","Editor"
    Default: "None"
    Set the permission for the contacts folder.

    .PARAMETER InboxPermissions
    Type: string
    Allowed value: "None","Reviewer","Author","Editor"
    Default: "None"
    Set the permission for the inbox.

    .PARAMETER JournalPermissions
    Type: string
    Allowed value: "None","Reviewer","Author","Editor"
    Default: "None"
    Set the permission for the journal.

    .PARAMETER NotesPermissions
    Type: string
    Allowed value: "None","Reviewer","Author","Editor"
    Default: "None"
    Set the permission for the notes folder.

    .PARAMETER TasksPermissions
    Type: string
    Allowed value: "None","Reviewer","Author","Editor"
    Default: "None"
    Set the permission for the notes folder.

    .PARAMETER ReceiveCopiesOfMeetingMessages
    Type: boolean
    Allowed value: $true,$false
    Default: $false
    Activate the function, that the delegate receives all meeting messages.

    .PARAMETER CanViewPrivateItems
    Type: boolean
    Allowed value: $true,$false
    Default: $false
    Is the delegate allowed to view private items?.

    .PARAMETER WriteOnConsole
    Type: boolean
    Default: $false
    If set the (some) logging output will also be written to the console.

    .PARAMETER NoConfirm
    Type: boolean
    Default: $false
    Will be used for removing delegates. Should be set to $false if script is running as a task. Note: Before removing delegates run the script to list existing delegates with the permission

    .EXAMPLE
    List all delegates with the permissions with impersonisation
    .\Manage-Delegates.p1 -Identity "mollyc@contoso.com" -Impersonate $true -UseDefaultCredentials $true

    .EXAMPLE
    Add a delegate to a mailbox with impersonation only with reviewer rights to the inbox using the session credentials
    .\Manage-Delegates.p1 -Identity "mollyc@contoso.com" -Impersonate $true -DelegateToSet "davids@contoso.com" -InboxPermissions "Reviewer" -UseDefaultCredentials $true

    .EXAMPLE
    Add a delegate to a mailbox with impersonation only with reviewer rights to the inbox using a specific url,ignore ssl certificate errors and session credentials
    .\Manage-Delegates.p1 -Identity "mollyc@contoso.com" -Impersonate $true -DelegateToSet "davids@contoso.com" -InboxPermissions "Reviewer" -UseDefaultCredentials $true -Url "https://Exchangeserver1/ews/exchange.asmx" -IgnoreSSLCertificate $true

    Add a delegate to a mailbox with impersonation only with reviewer rights to the inbox not using the session credentials
    .\Manage-Delegates.p1 -Identity "mollyc@contoso.com" -Impersonate $true -DelegateToSet "davids@contoso.com" -InboxPermissions "Reviewer" -Credentials (Get-Credentials)
    .EXAMPLE
    Remove a delegate
    .\Manage-Delegates.p1 -Identity "mollyc@contoso.com" -Impersonate -DelegateToRemove "davids@contoso.com"

#>

Param(
    [string]$Identity,
    [System.Management.Automation.PSCredential]$Credentials,
    [string]$Url,
    [bool]$IgnoreSSLCertificate = $false,
    [bool]$UseDefaultCredentials = $false,
    [bool]$Impersonate = $false,
    [Parameter(ParameterSetName = "Set")][string[]]$DelegateToRemove,
    [Parameter(ParameterSetName = "Set")][string[]]$DelegateToSet,
    [Parameter(ParameterSetName = "Set")][ValidateSet("None", "Reviewer", "Author", "Editor")][string]$CalendarPermissions = "None",
    [Parameter(ParameterSetName = "Set")][ValidateSet("None", "Reviewer", "Author", "Editor")][string]$ContactsPermissions = "None",
    [Parameter(ParameterSetName = "Set")][ValidateSet("None", "Reviewer", "Author", "Editor")][string]$InboxPermissions = "None",
    [Parameter(ParameterSetName = "Set")][ValidateSet("None", "Reviewer", "Author", "Editor")][string]$JournalPermissions = "None",
    [Parameter(ParameterSetName = "Set")][ValidateSet("None", "Reviewer", "Author", "Editor")][string]$NotesPermissions = "None",
    [Parameter(ParameterSetName = "Set")][ValidateSet("None", "Reviewer", "Author", "Editor")][string]$TasksPermissions = "None",
    [Parameter(ParameterSetName = "Set")][ValidateSet($true, $false)][bool]$ReceiveCopiesOfMeetingMessages = $false,
    [Parameter(ParameterSetName = "Set")][ValidateSet($true, $false)][bool]$CanViewPrivateItems = $false,
    [bool]$WriteOnConsole = $false,
    [bool]$Confirm = $true
)

# Import global modules
Import-Module GlobalFunctions
$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
$ScriptName = $MyInvocation.MyCommand.Name

# Create a log folder
$logger = New-Logger -ScriptRoot $ScriptDir -ScriptName $ScriptName -LogFileRetention 14
$logger.Write('Script started')

# loading the ews.dll
try {
    if ($env:ExchangeInstallPath -ne $null -and $env:ExchangeInstallPath -ne '') {
        # Use local Exchange install path, if available
        $dllpath = "$($env:ExchangeInstallPath)\bin\Microsoft.Exchange.WebServices.dll"
    }
    else {
        # Use EWS managed API install path
        $dllpath = 'C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll'
    }

    [void][Reflection.Assembly]::LoadFile($dllpath)
}
catch {
    $logger.Write('Error on loading the EWS dll. Please check the path or install the EWS Managed API!', 1, $WriteOnConsole)
    $logger.Write('Script aborted', 1, $WriteOnConsole)
    exit(1)
}

# function to connect to a mailbox
function New-Service {
    Param(
        [string]$ID,
        [bool]$Impersonation = $false,
        [System.Management.Automation.PSCredential]$Credentials,
        [bool]$IgnoreSSL = $false,
        [string]$Url,
        [bool]$DefaultCredentials = $false
    )
    try {
        #Create a service reference
        $Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1)
        if ($IgnoreSSLCertificate) {
            Set-IgnoreSSLCerfiticates
        }
        # using default credentials or specified ones
        if ($UseDefaultCredentials) {
            $Service.UseDefaultCredentials = $true
        }
        else {
            try {
                $creds = New-Object System.Net.NetworkCredential($Credentials.UserName.ToString(), $Credentials.GetNetworkCredential().Password.ToString())
                $Service.Credentials = $creds
            }
            catch [Exception] {
                $logger.Write("Failed to set the credentials fot the webservice. Please check the entered credentials", 1, $WriteOnConsole)
                $logger.Write("Exception: $($_.Exception.GetType().FullName) - Message: $($_.Exception.Message)")
                return $null
            }
        }
        # check if we need to connect to a specific server
        if ($Url -ne $null -and $Url -ne "") {
            $uri = [System.Uri]$URl
            $Service.Url = $uri
        }
        else {
            $Service.AutodiscoverUrl($ID, {$true})
        }
        $enumSmtpAddress = [Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress
        if ($Impersonate) {
            # Set Impersonation
            $Service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId($enumSmtpAddress, $ID)
            $logger.Write("Web service for user $($ID) created.")
        }
        else {
            $logger.Write("Web service for user $($ID) created.")
        }
    }
    catch [Exception] {
        $logger.Write("Failed creating the exchange web service for $($ID). Check mailbox name and impersonisation rights.", 1, $WriteOnConsole)
        $logger.Write("Exception: $($_.Exception.GetType().FullName) - Message: $($_.Exception.Message)")
        return $null
    }
    return $Service
}

function Set-IgnoreSSLCerfiticates {
    Add-Type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
}
"@

    [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
}

function Get-Delegates {
    Param(
        [Microsoft.Exchange.WebServices.Data.ExchangeService]$Service,
        [string]$Identity
    )
    $delegates = $null
    try {
        $delegates = $service.GetDelegates($Identity, $true)
    }
    catch [Exception] {
        $logger.Write("Failed to get delegates for user $($Identity)", 1, $WriteOnConsole)
        $logger.Write("Exception: $($_.Exception.GetType().FullName) - Message: $($_.Exception.Message)")
        return $null
    }
    return $delegates
}

function Remove-Delegate {
    Param(
        [Microsoft.Exchange.WebServices.Data.ExchangeService]$Service,
        [string]$Identity,
        [string[]]$DelegateList
    )
    try {
        $null = $service.RemoveDelegates($Identity, $DelegateList)
        for ($i = 0; $i -le $DelegateList.Count - 1; $i++) {
            $logger.Write("$($DelegateList[$i]) removed from $($Identity) successfully.", 1, $true)

        }
    }
    catch [Exception] {
        for ($i = 0; $i -le $DelegateList.Count - 1; $i++) {
            $logger.Write("Failed to remove the delegate $($DelegateList[$i]) from user $($Identity)", 1, $WriteOnConsole)
            $logger.Write("Exception: $($_.Exception.GetType().FullName) - Message: $($_.Exception.Message)")
        }

    }
}

function Set-Delegate {
    Param(
        [Microsoft.Exchange.WebServices.Data.ExchangeService]$Service,
        [string]$Identity,
        [string[]]$Delegates,
        [Microsoft.Exchange.WebServices.Data.DelegateInformation]$DelegateList,
        [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]$CalendarFolderPermissionLevel,
        [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]$ContactsFolderPermissionLevel,
        [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]$InboxFolderPermissionLevel,
        [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]$JournalFolderPermissionLevel,
        [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]$NotesFolderPermissionLevel,
        [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]$TasksFolderPermissionLevel,
        [bool]$ReceiveCopiesOfMeetingMessages,
        [bool]$ViewPrivateItems,
        [switch]$Add
    )

    if ($Add) {
        $logger.Write("Mode: Adding to mailbox", 0, $WriteOnConsole)
    }
    else {
        $logger.Write("Mode: Altering delegates", 0, $WriteOnConsole)
    }

    for ($i = 0; $i -le $Delegates.Count - 1; $i++) {
        $logger.Write("Set the delegate $($Delegates[$i]) to mailbox with following permissions:", 0, $WriteOnConsole)
        $logger.Write(" Calendar: $($CalendarFolderPermissionLevel)", 0, $WriteOnConsole)
        $logger.Write(" Contacts: $($ContactsFolderPermissionLevel)", 0, $WriteOnConsole)
        $logger.Write(" Inbox: $($InboxFolderPermissionLevel)", 0, $WriteOnConsole)
        $logger.Write(" Journal: $($JournalFolderPermissionLevel)", 0, $WriteOnConsole)
        $logger.Write(" Notes: $($NotesFolderPermissionLevel)", 0, $WriteOnConsole)
        $logger.Write(" Tasks: $($TasksFolderPermissionLevel)", 0, $WriteOnConsole)
        $logger.Write(" Receive copies of meeting messages: $($ReceiveCopiesOfMeetingMessages)", 0, $WriteOnConsole)
        $logger.Write(" View private items: $($ViewPrivateItems)", 0, $WriteOnConsole)
    }

    [Microsoft.Exchange.WebServices.Data.DelegateUser[]]$dgArray = @()
    for ($i = 0; $i -le $Delegates.Count - 1; $i++) {
        $dgUser = new-object Microsoft.Exchange.WebServices.Data.DelegateUser($Delegates[$i])
        $dgUser.ViewPrivateItems = $ViewPrivateItems
        $dgUser.ReceiveCopiesOfMeetingMessages = $ReceiveCopiesOfMeetingMessages
        $dgUser.Permissions.CalendarFolderPermissionLevel = $CalendarFolderPermissionLevel
        $dgUser.Permissions.ContactsFolderPermissionLevel = $ContactsFolderPermissionLevel
        $dgUser.Permissions.InboxFolderPermissionLevel = $InboxFolderPermissionLevel
        $dgUser.Permissions.JournalFolderPermissionLevel = $JournalFolderPermissionLevel
        $dgUser.Permissions.NotesFolderPermissionLevel = $NotesFolderPermissionLevel
        $dgUser.Permissions.TasksFolderPermissionLevel = $TasksFolderPermissionLevel
        $dgArray += $dgUser
    }

    if ($Add) {
        try {
            $null = $Service.AddDelegates($Identity, $DeleGateList.MeetingRequestsDeliveryScope, $dgArray)
            for ($i = 0; $i -le $DelegateList.Count - 1; $i++) {
                $logger.Write("$($Delegates[$i]) added to $($Identity) successfully.", 0, $true)
            }
        }
        catch [Exception] {
            for ($i = 0; $i -le $DelegateList.Count - 1; $i++) {
                $logger.Write("Failed to add $($Delegates[$i]) to mailbox $($Identity)", 1, $WriteOnConsole)
                $logger.Write("Exception: $($_.Exception.GetType().FullName) - Message: $($_.Exception.Message)")
            }
        }
    }
    else {
        try {
            $null = $Service.UpdateDelegates($Identity, $DeleGateList.MeetingRequestsDeliveryScope, $dgArray)
            for ($i = 0; $i -le $DelegateList.Count - 1; $i++) {
                $logger.Write("$($Delegates[$i]) for mailbox $($Identity) altered successfully.", 0, $true)
            }
        }
        catch [Exception] {
            for ($i = 0; $i -le $DelegateList.Count - 1; $i++) {
                $logger.Write("Failed to alter $($Delegates[$i]) for mailbox $($Identity)", 1, $WriteOnConsole)
                $logger.Write("Exception: $($_.Exception.GetType().FullName) - Message: $($_.Exception.Message)")
            }
        }
    }
}

function Get-Permission {
    Param(
        [string]$Permission
    )

    switch ($Permission) {
        "None" {
            return [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]::None
        }
        "Editor" {
            return [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]::Editor
        }
        "Author" {
            return [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]::Author
        }
        "Reviewer" {
            return [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]::Reviewer
        }
        default: {
            return [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]::None
        }
    }
}

function Request-Choice {
    [CmdletBinding()]
    param([Parameter(Mandatory = $true)][string]$Caption)
    $choices = [System.Management.Automation.Host.ChoiceDescription[]]@("&Yes", "&No")
    [int]$defaultChoice = 1

    $choiceReturn = $Host.UI.PromptForChoice($Caption, "", $choices, $defaultChoice)

    return $choiceReturn
}

# create the service
$Service = New-Service -Id $Identity -Impersonation $Impersonate -Credentials $Credentials -DefaultCredentials $UseDefaultCredentials -Url $Url -IgnoreSSL $IgnoreSSLCertificate

if ($service -ne $null) {
    # first check, if DelegateToRemove or DelegateToSet got any entries
    if ($DelegateToRemove.Count -eq 0 -or $DelegateToSet.Count -eq 0) {
        $DelegateList = $null
        $DelegateList = Get-Delegates -Service $service -Identity $Identity

        if ($DelegateList -ne $null) {
            if ($DelegateList.DelegateUserResponses.Count -ge 1) {
                $logger.Write("Total delegates: $($DelegateList.DelegateUserResponses.Count)", 0, $WriteOnConsole)
                foreach ($User in $DelegateList.DelegateUserResponses) {
                    $logger.Write("Delegate: $($User.DelegateUser.UserId.PrimarySmtpAddress)", 0, $WriteOnConsole)
                    $logger.Write("Permissions...", 0, $WriteOnConsole)
                    $logger.Write(" Calendar: $($User.DelegateUser.Permissions.CalendarFolderPermissionLevel)", 0, $WriteOnConsole)
                    $logger.Write(" Contacts: $($User.DelegateUser.Permissions.ContactsFolderPermissionLevel)", 0, $WriteOnConsole)
                    $logger.Write(" Inbox: $($User.DelegateUser.Permissions.InboxFolderPermissionLevel)", 0, $WriteOnConsole)
                    $logger.Write(" Journal: $($User.DelegateUser.Permissions.JournalFolderPermissionLevel)", 0, $WriteOnConsole)
                    $logger.Write(" Notes: $($User.DelegateUser.Permissions.NotesFolderPermissionLevel)", 0, $WriteOnConsole)
                    $logger.Write(" Tasks: $($User.DelegateUser.Permissions.TasksFolderPermissionLevel)", 0, $WriteOnConsole)
                    $logger.Write(" Receive copies of meeting messages: $($User.DelegateUser.ReceiveCopiesOfMeetingMessages)", 0, $WriteOnConsole)
                    $logger.Write(" View private items: $($User.DelegateUser.ViewPrivateItems)", 0, $WriteOnConsole)
                }
            }
            else {
                $logger.Write("No delegates are set for $($Identity)", 0, $WriteOnConsole)
            }
        }
        else {
            $logger.Write("Failed to get delegates for $($Idenitty). Check log file for errors.", 0, $WriteOnConsole)
        }
    }

    # check if any value is set fpr remove or set/adding a delegate
    if ($DelegateToRemove.Count -ge 1 -or $DelegateToSet.Count -ge 1) {
        # Variables
        [string[]]$ToRemove = @()
        [hashtable]$FoundDelegates = @{}
        [string[]]$DelegateAddList = @()
        [string[]]$DelegateToAlterList = @()

        $DelegateList = Get-Delegates -service $service -Identity $Identity
        if (($DelegateList -ne $null) -and ($DelegateList.DelegateUserResponses.Count -ge 1)) {
            for ($i = 0; $i -le $delegatelist.DelegateUserResponses.Count - 1; $i++) {
                $FoundDelegates.Add("Delegate $($i)", $DelegateList.DelegateUserResponses[$i].DelegateUser.UserId.PrimarySmtpAddress.ToLower())
            }
        }

        # is there any user to remove?
        if ($DelegateToRemove.Count -ge 1) {
            for ($i = 0; $i -le $DelegateToRemove.Count - 1; $i++) {
                if ($FoundDelegates.ContainsValue($DelegateToRemove[$i].ToLower())) {
                    if ($Confirm) {
                        if ((Request-Choice -Caption "$($DelegateToRemove[$i]) found. Do you want to remove the delegate?") -eq 0) {
                            $ToRemove += $DelegateToRemove[$i].ToLower()
                            $logger.Write("Delegate $($DelegateToRemove[$i]) found. Try to removing now", 0, $WriteOnConsole)
                        }
                        else {
                            $logger.Write("Delegate $($DelegateToRemove[$i]) found but deletion was not approved by the user.", 0, $WriteOnConsole)
                        }
                    }
                    else {
                        $ToRemove += $DelegateToRemove[$i].ToLower()
                        $logger.Write("Delegate $($DelegateToRemove[$i]) found. Try to removing now", 0, $WriteOnConsole)
                    }
                }
                else {
                    $logger.Write("$($DelegateToRemove[$i]) is not a delegate of $($Identity)", 0, $WriteOnConsole)
                }
            }
            if ($ToRemove.Count -ge 1) {
                Remove-Delegate -Service $service -Identity $Identity -DelegateList $ToRemove
            }
        }

        if ($DelegateToSet.Count -ge 1) {
            If ($FoundDelegates.Count -ge 1) {
                foreach ($User in $DelegateToSet) {
                    if ($FoundDelegates.ContainsValue($User.ToLower())) {
                        # User is delegate, we need to alter him
                        $DelegateToAlterList += $User
                    }
                    else {
                        # New delegate to add
                        $DelegateAddList += $User
                    }
                }
            }
            else {
                # we have no delegates on the mailbox, so add all to the $DelegateAddList
                $DelegateAddList = $DelegateToSet
            }

            # First we adding the delegates
            if ($DelegateAddList.Count -ge 1) {
                Set-Delegate -Service $service -Identity $Identity -Delegates $DelegateToSet `
                    -CalendarFolderPermissionLevel (Get-Permission -Permission $CalendarPermissions) `
                    -ContactsFolderPermissionLevel (Get-Permission -Permission $ContactsPermissions) `
                    -InboxFolderPermissionLevel (Get-Permission -Permission $InboxPermissions) -JournalFolderPermissionLevel (Get-Permission -Permission $JournalPermissions) `
                    -NotesFolderPermissionLevel (Get-Permission -Permission $NotesPermissions) -TasksFolderPermissionLevel (Get-Permission -Permission $TasksPermissions) `
                    -ReceiveCopiesOfMeetingMessages $ReceiveCopiesOfMeetingMessages -ViewPrivateItems $CanViewPrivateItems -DelegateList $DelegateList -Add
            }

            # The we alter delegates
            if ($DelegateToAlterList.Count -ge 1) {
                Set-Delegate -Service $service -Identity $Identity -Delegates $DelegateToSet `
                    -CalendarFolderPermissionLevel (Get-Permission -Permission $CalendarPermissions) `
                    -ContactsFolderPermissionLevel (Get-Permission -Permission $ContactsPermissions) `
                    -InboxFolderPermissionLevel (Get-Permission -Permission $InboxPermissions) -JournalFolderPermissionLevel (Get-Permission -Permission $JournalPermissions) `
                    -NotesFolderPermissionLevel (Get-Permission -Permission $NotesPermissions) -TasksFolderPermissionLevel (Get-Permission -Permission $TasksPermissions) `
                    -ReceiveCopiesOfMeetingMessages $ReceiveCopiesOfMeetingMessages -ViewPrivateItems $CanViewPrivateItems -DelegateList $DelegateList
            }
        }
    }
}


text:
/*
Package cache implements data structures used by the kubelet volume manager to
keep track of attached volumes and the pods that mounted them.
*/
package cache

import (
	"fmt"
	"sync"
	"time"

	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/apiserver/pkg/util/feature"
	"k8s.io/component-base/metrics"
	"k8s.io/klog/v2"
	apiv1resource "k8s.io/kubernetes/pkg/api/v1/resource"
	"k8s.io/kubernetes/pkg/features"
	"k8s.io/kubernetes/pkg/volume"
	"k8s.io/kubernetes/pkg/volume/util"
	"k8s.io/kubernetes/pkg/volume/util/operationexecutor"
	"k8s.io/kubernetes/pkg/volume/util/types"
)

// DesiredStateOfWorld defines a set of thread-safe operations for the kubelet
// volume manager's desired state of the world cache.
// This cache contains volumes->pods i.e. a set of all volumes that should be
// attached to this node and the pods that reference them and should mount the
// volume.
// Note: This is distinct from the DesiredStateOfWorld implemented by the
// attach/detach controller. They both keep track of different objects. This
// contains kubelet volume manager specific state.
type DesiredStateOfWorld interface {
	// AddPodToVolume adds the given pod to the given volume in the cache
	// indicating the specified pod should mount the specified volume.
	// A unique volumeName is generated from the volumeSpec and returned on
	// success.
	// If no volume plugin can support the given volumeSpec or more than one
	// plugin can support it, an error is returned.
	// If a volume with the name volumeName does not exist in the list of
	// volumes that should be attached to this node, the volume is implicitly
	// added.
	// If a pod with the same unique name already exists under the specified
	// volume, this is a no-op.
	AddPodToVolume(podName types.UniquePodName, pod *v1.Pod, volumeSpec *volume.Spec, outerVolumeSpecName string, volumeGidValue string, seLinuxContainerContexts []*v1.SELinuxOptions) (v1.UniqueVolumeName, error)

	// MarkVolumesReportedInUse sets the ReportedInUse value to true for the
	// reportedVolumes. For volumes not in the reportedVolumes list, the
	// ReportedInUse value is reset to false. The default ReportedInUse value
	// for a newly created volume is false.
	// When set to true this value indicates that the volume was successfully
	// added to the VolumesInUse field in the node's status. Mount operation needs
	// to check this value before issuing the operation.
	// If a volume in the reportedVolumes list does not exist in the list of
	// volumes that should be attached to this node, it is skipped without error.
	MarkVolumesReportedInUse(reportedVolumes []v1.UniqueVolumeName)

	// DeletePodFromVolume removes the given pod from the given volume in the
	// cache indicating the specified pod no longer requires the specified
	// volume.
	// If a pod with the same unique name does not exist under the specified
	// volume, this is a no-op.
	// If a volume with the name volumeName does not exist in the list of
	// attached volumes, this is a no-op.
	// If after deleting the pod, the specified volume contains no other child
	// pods, the volume is also deleted.
	DeletePodFromVolume(podName types.UniquePodName, volumeName v1.UniqueVolumeName)

	// VolumeExists returns true if the given volume exists in the list of
	// volumes that should be attached to this node.
	// If a pod with the same unique name does not exist under the specified
	// volume, false is returned.
	VolumeExists(volumeName v1.UniqueVolumeName, seLinuxMountContext string) bool

	// PodExistsInVolume returns true if the given pod exists in the list of
	// podsToMount for the given volume in the cache.
	// If a pod with the same unique name does not exist under the specified
	// volume, false is returned.
	// If a volume with the name volumeName does not exist in the list of
	// attached volumes, false is returned.
	PodExistsInVolume(podName types.UniquePodName, volumeName v1.UniqueVolumeName, seLinuxMountContext string) bool

	// GetVolumesToMount generates and returns a list of volumes that should be
	// attached to this node and the pods they should be mounted to based on the
	// current desired state of the world.
	GetVolumesToMount() []VolumeToMount

	// GetPods generates and returns a map of pods in which map is indexed
	// with pod's unique name. This map can be used to determine which pod is currently
	// in desired state of world.
	GetPods() map[types.UniquePodName]bool

	// VolumeExistsWithSpecName returns true if the given volume specified with the
	// volume spec name (a.k.a., InnerVolumeSpecName) exists in the list of
	// volumes that should be attached to this node.
	// If a pod with the same name does not exist under the specified
	// volume, false is returned.
	VolumeExistsWithSpecName(podName types.UniquePodName, volumeSpecName string) bool

	// AddErrorToPod adds the given error to the given pod in the cache.
	// It will be returned by subsequent GetPodErrors().
	// Each error string is stored only once.
	AddErrorToPod(podName types.UniquePodName, err string)

	// PopPodErrors returns accumulated errors on a given pod and clears
	// them.
	PopPodErrors(podName types.UniquePodName) []string

	// GetPodsWithErrors returns names of pods that have stored errors.
	GetPodsWithErrors() []types.UniquePodName

	// MarkVolumeAttachability updates the volume's attachability for a given volume
	MarkVolumeAttachability(volumeName v1.UniqueVolumeName, attachable bool)

	// UpdatePersistentVolumeSize updates persistentVolumeSize in desired state of the world
	// so as it can be compared against actual size and volume expansion performed
	// if necessary
	UpdatePersistentVolumeSize(volumeName v1.UniqueVolumeName, size *resource.Quantity)
}

// VolumeToMount represents a volume that is attached to this node and needs to
// be mounted to PodName.
type VolumeToMount struct {
	operationexecutor.VolumeToMount
}

// NewDesiredStateOfWorld returns a new instance of DesiredStateOfWorld.
func NewDesiredStateOfWorld(volumePluginMgr *volume.VolumePluginMgr, seLinuxTranslator util.SELinuxLabelTranslator) DesiredStateOfWorld {
	if feature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {
		registerSELinuxMetrics()
	}
	return &desiredStateOfWorld{
		volumesToMount:    make(map[v1.UniqueVolumeName]volumeToMount),
		volumePluginMgr:   volumePluginMgr,
		podErrors:         make(map[types.UniquePodName]sets.String),
		seLinuxTranslator: seLinuxTranslator,
	}
}

type desiredStateOfWorld struct {
	// volumesToMount is a map containing the set of volumes that should be
	// attached to this node and mounted to the pods referencing it. The key in
	// the map is the name of the volume and the value is a volume object
	// containing more information about the volume.
	volumesToMount map[v1.UniqueVolumeName]volumeToMount
	// volumePluginMgr is the volume plugin manager used to create volume
	// plugin objects.
	volumePluginMgr *volume.VolumePluginMgr
	// podErrors are errors caught by desiredStateOfWorldPopulator about volumes for a given pod.
	podErrors map[types.UniquePodName]sets.String
	// seLinuxTranslator translates v1.SELinuxOptions to a file SELinux label.
	seLinuxTranslator util.SELinuxLabelTranslator

	sync.RWMutex
}

// The volume object represents a volume that should be attached to this node,
// and mounted to podsToMount.
type volumeToMount struct {
	// volumeName contains the unique identifier for this volume.
	volumeName v1.UniqueVolumeName

	// podsToMount is a map containing the set of pods that reference this
	// volume and should mount it once it is attached. The key in the map is
	// the name of the pod and the value is a pod object containing more
	// information about the pod.
	podsToMount map[types.UniquePodName]podToMount

	// pluginIsAttachable indicates that the plugin for this volume implements
	// the volume.Attacher interface
	pluginIsAttachable bool

	// pluginIsDeviceMountable indicates that the plugin for this volume implements
	// the volume.DeviceMounter interface
	pluginIsDeviceMountable bool

	// volumeGidValue contains the value of the GID annotation, if present.
	volumeGidValue string

	// reportedInUse indicates that the volume was successfully added to the
	// VolumesInUse field in the node's status.
	reportedInUse bool

	// desiredSizeLimit indicates the desired upper bound on the size of the volume
	// (if so implemented)
	desiredSizeLimit *resource.Quantity

	// persistentVolumeSize records desired size of a persistent volume.
	// Usually this value reflects size recorded in pv.Spec.Capacity
	persistentVolumeSize *resource.Quantity

	// seLinuxFileLabel is desired SELinux label on files on the volume. If empty, then
	// - either the context+label is unknown (assigned randomly by the container runtime)
	// - or the volume plugin responsible for this volume does not support mounting with -o context
	// - or the OS does not support SELinux
	// In all cases, the SELinux context does not matter when mounting the volume.
	seLinuxFileLabel string
}

// The pod object represents a pod that references the underlying volume and
// should mount it once it is attached.
type podToMount struct {
	// podName contains the name of this pod.
	podName types.UniquePodName

	// Pod to mount the volume to. Used to create NewMounter.
	pod *v1.Pod

	// volume spec containing the specification for this volume. Used to
	// generate the volume plugin object, and passed to plugin methods.
	// For non-PVC volumes this is the same as defined in the pod object. For
	// PVC volumes it is from the dereferenced PV object.
	volumeSpec *volume.Spec

	// outerVolumeSpecName is the volume.Spec.Name() of the volume as referenced
	// directly in the pod. If the volume was referenced through a persistent
	// volume claim, this contains the volume.Spec.Name() of the persistent
	// volume claim
	outerVolumeSpecName string
	// mountRequestTime stores time at which mount was requested
	mountRequestTime time.Time
}

const (
	// Maximum errors to be stored per pod in desiredStateOfWorld.podErrors to
	// prevent unbound growth.
	maxPodErrors = 10
)

func (dsw *desiredStateOfWorld) AddPodToVolume(
	podName types.UniquePodName,
	pod *v1.Pod,
	volumeSpec *volume.Spec,
	outerVolumeSpecName string,
	volumeGidValue string,
	seLinuxContainerContexts []*v1.SELinuxOptions) (v1.UniqueVolumeName, error) {
	dsw.Lock()
	defer dsw.Unlock()

	volumePlugin, err := dsw.volumePluginMgr.FindPluginBySpec(volumeSpec)
	if err != nil || volumePlugin == nil {
		return "", fmt.Errorf(
			"failed to get Plugin from volumeSpec for volume %q err=%v",
			volumeSpec.Name(),
			err)
	}

	var volumeName v1.UniqueVolumeName

	// The unique volume name used depends on whether the volume is attachable/device-mountable
	// or not.
	attachable := util.IsAttachableVolume(volumeSpec, dsw.volumePluginMgr)
	deviceMountable := util.IsDeviceMountableVolume(volumeSpec, dsw.volumePluginMgr)
	if attachable || deviceMountable {
		// For attachable/device-mountable volumes, use the unique volume name as reported by
		// the plugin.
		volumeName, err =
			util.GetUniqueVolumeNameFromSpec(volumePlugin, volumeSpec)
		if err != nil {
			return "", fmt.Errorf(
				"failed to GetUniqueVolumeNameFromSpec for volumeSpec %q using volume plugin %q err=%v",
				volumeSpec.Name(),
				volumePlugin.GetPluginName(),
				err)
		}
	} else {
		// For non-attachable and non-device-mountable volumes, generate a unique name based on the pod
		// namespace and name and the name of the volume within the pod.
		volumeName = util.GetUniqueVolumeNameFromSpecWithPod(podName, volumePlugin, volumeSpec)
	}

	seLinuxFileLabel, pluginSupportsSELinuxContextMount, err := dsw.getSELinuxLabel(volumeSpec, seLinuxContainerContexts)
	if err != nil {
		return "", err
	}
	klog.V(4).InfoS("expected volume SELinux label context", "volume", volumeSpec.Name(), "label", seLinuxFileLabel)

	if vol, volumeExists := dsw.volumesToMount[volumeName]; !volumeExists {
		var sizeLimit *resource.Quantity
		if volumeSpec.Volume != nil {
			if util.IsLocalEphemeralVolume(*volumeSpec.Volume) {
				_, podLimits := apiv1resource.PodRequestsAndLimits(pod)
				ephemeralStorageLimit := podLimits[v1.ResourceEphemeralStorage]
				sizeLimit = resource.NewQuantity(ephemeralStorageLimit.Value(), resource.BinarySI)
				if volumeSpec.Volume.EmptyDir != nil &&
					volumeSpec.Volume.EmptyDir.SizeLimit != nil &&
					volumeSpec.Volume.EmptyDir.SizeLimit.Value() > 0 &&
					(sizeLimit.Value() == 0 || volumeSpec.Volume.EmptyDir.SizeLimit.Value() < sizeLimit.Value()) {
					sizeLimit = resource.NewQuantity(volumeSpec.Volume.EmptyDir.SizeLimit.Value(), resource.BinarySI)
				}
			}
		}
		if !util.VolumeSupportsSELinuxMount(volumeSpec) {
			// Clear SELinux label for the volume with unsupported access modes.
			klog.V(4).InfoS("volume does not support SELinux context mount, clearing the expected label", "volume", volumeSpec.Name())
			seLinuxFileLabel = ""
		}
		if seLinuxFileLabel != "" {
			seLinuxVolumesAdmitted.Add(1.0)
		}
		vmt := volumeToMount{
			volumeName:              volumeName,
			podsToMount:             make(map[types.UniquePodName]podToMount),
			pluginIsAttachable:      attachable,
			pluginIsDeviceMountable: deviceMountable,
			volumeGidValue:          volumeGidValue,
			reportedInUse:           false,
			desiredSizeLimit:        sizeLimit,
			seLinuxFileLabel:        seLinuxFileLabel,
		}
		// record desired size of the volume
		if volumeSpec.PersistentVolume != nil {
			pvCap := volumeSpec.PersistentVolume.Spec.Capacity.Storage()
			if pvCap != nil {
				pvCapCopy := pvCap.DeepCopy()
				vmt.persistentVolumeSize = &pvCapCopy
			}
		}
		dsw.volumesToMount[volumeName] = vmt
	} else {
		// volume exists
		if pluginSupportsSELinuxContextMount {
			if seLinuxFileLabel != vol.seLinuxFileLabel {
				// TODO: update the error message after tests, e.g. add at least the conflicting pod names.
				fullErr := fmt.Errorf("conflicting SELinux labels of volume %s: %q and %q", volumeSpec.Name(), vol.seLinuxFileLabel, seLinuxFileLabel)
				supported := util.VolumeSupportsSELinuxMount(volumeSpec)
				if err := handleSELinuxMetricError(fullErr, supported, seLinuxVolumeContextMismatchWarnings, seLinuxVolumeContextMismatchErrors); err != nil {
					return "", err
				}
			} else {
				if seLinuxFileLabel != "" {
					seLinuxVolumesAdmitted.Add(1.0)
				}
			}
		}
	}

	oldPodMount, ok := dsw.volumesToMount[volumeName].podsToMount[podName]
	mountRequestTime := time.Now()
	if ok && !volumePlugin.RequiresRemount(volumeSpec) {
		mountRequestTime = oldPodMount.mountRequestTime
	}

	// Create new podToMount object. If it already exists, it is refreshed with
	// updated values (this is required for volumes that require remounting on
	// pod update, like Downward API volumes).
	dsw.volumesToMount[volumeName].podsToMount[podName] = podToMount{
		podName:             podName,
		pod:                 pod,
		volumeSpec:          volumeSpec,
		outerVolumeSpecName: outerVolumeSpecName,
		mountRequestTime:    mountRequestTime,
	}
	return volumeName, nil
}

func (dsw *desiredStateOfWorld) getSELinuxLabel(volumeSpec *volume.Spec, seLinuxContainerContexts []*v1.SELinuxOptions) (string, bool, error) {
	var seLinuxFileLabel string
	var pluginSupportsSELinuxContextMount bool

	if feature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {
		var err error

		if !dsw.seLinuxTranslator.SELinuxEnabled() {
			return "", false, nil
		}

		pluginSupportsSELinuxContextMount, err = dsw.getSELinuxMountSupport(volumeSpec)
		if err != nil {
			return "", false, err
		}
		seLinuxSupported := util.VolumeSupportsSELinuxMount(volumeSpec)
		if pluginSupportsSELinuxContextMount {
			// Ensure that a volume that can be mounted with "-o context=XYZ" is
			// used only by containers with the same SELinux contexts.
			for _, containerContext := range seLinuxContainerContexts {
				newLabel, err := dsw.seLinuxTranslator.SELinuxOptionsToFileLabel(containerContext)
				if err != nil {
					fullErr := fmt.Errorf("failed to construct SELinux label from context %q: %s", containerContext, err)
					if err := handleSELinuxMetricError(fullErr, seLinuxSupported, seLinuxContainerContextWarnings, seLinuxContainerContextErrors); err != nil {
						return "", false, err
					}
				}
				if seLinuxFileLabel == "" {
					seLinuxFileLabel = newLabel
					continue
				}
				if seLinuxFileLabel != newLabel {
					fullErr := fmt.Errorf("volume %s is used with two different SELinux contexts in the same pod: %q, %q", volumeSpec.Name(), seLinuxFileLabel, newLabel)
					if err := handleSELinuxMetricError(fullErr, seLinuxSupported, seLinuxPodContextMismatchWarnings, seLinuxPodContextMismatchErrors); err != nil {
						return "", false, err
					}
				}
			}
		} else {
			// Volume plugin does not support SELinux context mount.
			// DSW will track this volume with SELinux label "", i.e. no mount with
			// -o context.
			seLinuxFileLabel = ""
		}
	}
	return seLinuxFileLabel, pluginSupportsSELinuxContextMount, nil
}

func (dsw *desiredStateOfWorld) MarkVolumesReportedInUse(
	reportedVolumes []v1.UniqueVolumeName) {
	dsw.Lock()
	defer dsw.Unlock()

	reportedVolumesMap := make(
		map[v1.UniqueVolumeName]bool, len(reportedVolumes) /* capacity */)

	for _, reportedVolume := range reportedVolumes {
		reportedVolumesMap[reportedVolume] = true
	}

	for volumeName, volumeObj := range dsw.volumesToMount {
		_, volumeReported := reportedVolumesMap[volumeName]
		volumeObj.reportedInUse = volumeReported
		dsw.volumesToMount[volumeName] = volumeObj
	}
}

func (dsw *desiredStateOfWorld) DeletePodFromVolume(
	podName types.UniquePodName, volumeName v1.UniqueVolumeName) {
	dsw.Lock()
	defer dsw.Unlock()

	delete(dsw.podErrors, podName)

	volumeObj, volumeExists := dsw.volumesToMount[volumeName]
	if !volumeExists {
		return
	}

	if _, podExists := volumeObj.podsToMount[podName]; !podExists {
		return
	}

	// Delete pod if it exists
	delete(dsw.volumesToMount[volumeName].podsToMount, podName)

	if len(dsw.volumesToMount[volumeName].podsToMount) == 0 {
		// Delete volume if no child pods left
		delete(dsw.volumesToMount, volumeName)
	}
}

// UpdatePersistentVolumeSize updates last known PV size. This is used for volume expansion and
// should be only used for persistent volumes.
func (dsw *desiredStateOfWorld) UpdatePersistentVolumeSize(volumeName v1.UniqueVolumeName, size *resource.Quantity) {
	dsw.Lock()
	defer dsw.Unlock()

	vol, volExists := dsw.volumesToMount[volumeName]
	if volExists {
		vol.persistentVolumeSize = size
		dsw.volumesToMount[volumeName] = vol
	}
}

func (dsw *desiredStateOfWorld) VolumeExists(
	volumeName v1.UniqueVolumeName, seLinuxMountContext string) bool {
	dsw.RLock()
	defer dsw.RUnlock()

	vol, volumeExists := dsw.volumesToMount[volumeName]
	if !volumeExists {
		return false
	}
	if feature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {
		// Handling two volumes with the same name and different SELinux context
		// as two *different* volumes here. Because if a volume is mounted with
		// an old SELinux context, it must be unmounted first and then mounted again
		// with the new context.
		//
		// This will happen when a pod A with context alpha_t runs and is being
		// terminated by kubelet and its volumes are being torn down, while a
		// pod B with context beta_t is already scheduled on the same node,
		// using the same volumes
		// The volumes from Pod A must be fully unmounted (incl. UnmountDevice)
		// and mounted with new SELinux mount options for pod B.
		// Without SELinux, kubelet can (and often does) reuse device mounted
		// for A.
		return vol.seLinuxFileLabel == seLinuxMountContext
	}
	return true
}

func (dsw *desiredStateOfWorld) PodExistsInVolume(
	podName types.UniquePodName, volumeName v1.UniqueVolumeName, seLinuxMountOption string) bool {
	dsw.RLock()
	defer dsw.RUnlock()

	volumeObj, volumeExists := dsw.volumesToMount[volumeName]
	if !volumeExists {
		return false
	}

	if feature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {
		if volumeObj.seLinuxFileLabel != seLinuxMountOption {
			// The volume is in DSW, but with a different SELinux mount option.
			// Report it as unused, so the volume is unmounted and mounted back
			// with the right SELinux option.
			return false
		}
	}

	_, podExists := volumeObj.podsToMount[podName]
	return podExists
}

func (dsw *desiredStateOfWorld) VolumeExistsWithSpecName(podName types.UniquePodName, volumeSpecName string) bool {
	dsw.RLock()
	defer dsw.RUnlock()
	for _, volumeObj := range dsw.volumesToMount {
		if podObj, podExists := volumeObj.podsToMount[podName]; podExists {
			if podObj.volumeSpec.Name() == volumeSpecName {
				return true
			}
		}
	}
	return false
}

func (dsw *desiredStateOfWorld) GetPods() map[types.UniquePodName]bool {
	dsw.RLock()
	defer dsw.RUnlock()

	podList := make(map[types.UniquePodName]bool)
	for _, volumeObj := range dsw.volumesToMount {
		for podName := range volumeObj.podsToMount {
			podList[podName] = true
		}
	}
	return podList
}

func (dsw *desiredStateOfWorld) GetVolumesToMount() []VolumeToMount {
	dsw.RLock()
	defer dsw.RUnlock()

	volumesToMount := make([]VolumeToMount, 0 /* len */, len(dsw.volumesToMount) /* cap */)
	for volumeName, volumeObj := range dsw.volumesToMount {
		for podName, podObj := range volumeObj.podsToMount {
			vmt := VolumeToMount{
				VolumeToMount: operationexecutor.VolumeToMount{
					VolumeName:              volumeName,
					PodName:                 podName,
					Pod:                     podObj.pod,
					VolumeSpec:              podObj.volumeSpec,
					PluginIsAttachable:      volumeObj.pluginIsAttachable,
					PluginIsDeviceMountable: volumeObj.pluginIsDeviceMountable,
					OuterVolumeSpecName:     podObj.outerVolumeSpecName,
					VolumeGidValue:          volumeObj.volumeGidValue,
					ReportedInUse:           volumeObj.reportedInUse,
					MountRequestTime:        podObj.mountRequestTime,
					DesiredSizeLimit:        volumeObj.desiredSizeLimit,
					SELinuxLabel:            volumeObj.seLinuxFileLabel,
				},
			}
			if volumeObj.persistentVolumeSize != nil {
				vmt.PersistentVolumeSize = volumeObj.persistentVolumeSize.DeepCopy()
			}
			volumesToMount = append(volumesToMount, vmt)
		}
	}
	return volumesToMount
}

func (dsw *desiredStateOfWorld) AddErrorToPod(podName types.UniquePodName, err string) {
	dsw.Lock()
	defer dsw.Unlock()

	if errs, found := dsw.podErrors[podName]; found {
		if errs.Len() <= maxPodErrors {
			errs.Insert(err)
		}
		return
	}
	dsw.podErrors[podName] = sets.NewString(err)
}

func (dsw *desiredStateOfWorld) PopPodErrors(podName types.UniquePodName) []string {
	dsw.Lock()
	defer dsw.Unlock()

	if errs, found := dsw.podErrors[podName]; found {
		delete(dsw.podErrors, podName)
		return errs.List()
	}
	return []string{}
}

func (dsw *desiredStateOfWorld) GetPodsWithErrors() []types.UniquePodName {
	dsw.RLock()
	defer dsw.RUnlock()

	pods := make([]types.UniquePodName, 0, len(dsw.podErrors))
	for podName := range dsw.podErrors {
		pods = append(pods, podName)
	}
	return pods
}

func (dsw *desiredStateOfWorld) MarkVolumeAttachability(volumeName v1.UniqueVolumeName, attachable bool) {
	dsw.Lock()
	defer dsw.Unlock()
	volumeObj, volumeExists := dsw.volumesToMount[volumeName]
	if !volumeExists {
		return
	}
	volumeObj.pluginIsAttachable = attachable
	dsw.volumesToMount[volumeName] = volumeObj
}

func (dsw *desiredStateOfWorld) getSELinuxMountSupport(volumeSpec *volume.Spec) (bool, error) {
	return util.SupportsSELinuxContextMount(volumeSpec, dsw.volumePluginMgr)
}

// Based on isRWOP, bump the right warning / error metric and either consume the error or return it.
func handleSELinuxMetricError(err error, seLinuxSupported bool, warningMetric, errorMetric *metrics.Gauge) error {
	if seLinuxSupported {
		errorMetric.Add(1.0)
		return err
	}

	// This is not an error yet, but it will be when support for other access modes is added.
	warningMetric.Add(1.0)
	klog.V(4).ErrorS(err, "Please report this error in https://github.com/kubernetes/enhancements/issues/1710, together with full Pod yaml file")
	return nil
}


text:
package com.instaclustr.sstabletools.cli;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import com.google.common.collect.MinMaxPriorityQueue;
import com.instaclustr.sstabletools.ColumnFamilyProxy;
import com.instaclustr.sstabletools.Histogram;
import com.instaclustr.sstabletools.PartitionReader;
import com.instaclustr.sstabletools.PartitionStatistics;
import com.instaclustr.sstabletools.ProgressBar;
import com.instaclustr.sstabletools.SSTableReader;
import com.instaclustr.sstabletools.SSTableStatistics;
import com.instaclustr.sstabletools.Snapshot;
import com.instaclustr.sstabletools.TableBuilder;
import com.instaclustr.sstabletools.Util;
import com.instaclustr.sstabletools.cassandra.CassandraBackend;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;

@Command(
    versionProvider = CLI.class,
    name = "pstats",
    usageHelpWidth = 128,
    description = "Partition size statistics for a column family",
    mixinStandardHelpOptions = true
)
public class PartitionSizeStatisticsCollector implements Runnable {

    @Option(names = {"-n"}, description = "Number of partitions to display", arity = "1", defaultValue = "10")
    public int numPartitions;

    @Option(names = {"-t"}, description = "Snapshot name", arity = "1")
    public String snapshotName;

    @Option(names = {"-f"}, description = "Filter to sstables (comma separated", defaultValue = "")
    public String filters;

    @Option(names = {"-b"}, description = "Batch mode", arity = "0")
    public boolean batch;

    @Parameters(arity = "2", description = "<keyspace> <table>")
    public List<String> params;

    @Override
    public void run() {

        Collection<String> filter = null;

        if (!filters.isEmpty()) {
            String[] names = filters.split(",");
            filter = Arrays.asList(names);
        }

        boolean interactive = true;
        if (batch) {
            interactive = false;
        }

        final String ksName = params.get(0);
        final String cfName = params.get(1);

        try (final ColumnFamilyProxy cfProxy = CassandraBackend.getInstance().getColumnFamily(ksName, cfName, snapshotName, filter)) {
            Collection<SSTableReader> sstableReaders = cfProxy.getIndexReaders();
            long totalLength = 0;
            for (SSTableReader reader : sstableReaders) {
                totalLength += reader.getSSTableStatistics().size;
            }
            if (totalLength == 0) {
                System.out.println("No data found!");
                System.exit(0);
            }

            Histogram sizeHistogram = new Histogram();
            Histogram sstableHistogram = new Histogram();
            long partitionCount = 0;

            MinMaxPriorityQueue<PartitionStatistics> largestPartitions = MinMaxPriorityQueue
                .orderedBy(PartitionStatistics.SIZE_COMPARATOR)
                .maximumSize(numPartitions)
                .create();

            MinMaxPriorityQueue<PartitionStatistics> tableCountLeaders = MinMaxPriorityQueue
                .orderedBy(PartitionStatistics.SSTABLE_COUNT_COMPARATOR)
                .maximumSize(numPartitions)
                .create();

            PartitionReader partitionReader = new PartitionReader(sstableReaders, totalLength);
            PartitionStatistics stat;
            ProgressBar progressBar = new ProgressBar("Analyzing SSTables...", interactive);
            progressBar.updateProgress(0.0);
            while ((stat = partitionReader.read()) != null) {
                progressBar.updateProgress(partitionReader.getProgress());
                largestPartitions.add(stat);
                tableCountLeaders.add(stat);
                sizeHistogram.update(stat.size);
                sstableHistogram.update(stat.tableCount);
                partitionCount++;
            }
            Snapshot sizeSnapshot = sizeHistogram.snapshot();
            Snapshot sstableSnapshot = sstableHistogram.snapshot();

            cfProxy.close();

            System.out.println("Summary:");
            TableBuilder tb = new TableBuilder();
            tb.setHeader("", "Size", "SSTable");
            tb.addRow("Count", Long.toString(partitionCount), "");
            tb.addRow("Total", Util.humanReadableByteCount(sizeSnapshot.getTotal()), Integer.toString(sstableReaders.size()));
            tb.addRow("Minimum", Util.humanReadableByteCount(sizeSnapshot.getMin()), Long.toString(sstableSnapshot.getMin()));
            tb.addRow("Average", Util.humanReadableByteCount(Math.round(sizeSnapshot.getMean())), String.format("%.1f", sstableSnapshot.getMean()));
            tb.addRow("std dev.", Util.humanReadableByteCount(Math.round(sizeSnapshot.getStdDev())), String.format("%.1f", sstableSnapshot.getStdDev()));
            tb.addRow("50%", Util.humanReadableByteCount(Math.round(sizeSnapshot.getPercentile(0.5))), String.format("%.1f", sstableSnapshot.getPercentile(0.5)));
            tb.addRow("75%", Util.humanReadableByteCount(Math.round(sizeSnapshot.getPercentile(0.75))), String.format("%.1f", sstableSnapshot.getPercentile(0.75)));
            tb.addRow("90%", Util.humanReadableByteCount(Math.round(sizeSnapshot.getPercentile(0.9))), String.format("%.1f", sstableSnapshot.getPercentile(0.9)));
            tb.addRow("95%", Util.humanReadableByteCount(Math.round(sizeSnapshot.getPercentile(0.95))), String.format("%.1f", sstableSnapshot.getPercentile(0.95)));
            tb.addRow("99%", Util.humanReadableByteCount(Math.round(sizeSnapshot.getPercentile(0.99))), String.format("%.1f", sstableSnapshot.getPercentile(0.99)));
            tb.addRow("99.9%", Util.humanReadableByteCount(Math.round(sizeSnapshot.getPercentile(0.999))), String.format("%.1f", sstableSnapshot.getPercentile(0.999)));
            tb.addRow("Maximum", Util.humanReadableByteCount(sizeSnapshot.getMax()), Long.toString(sstableSnapshot.getMax()));
            System.out.println(tb);

            System.out.println("Largest partitions:");
            TableBuilder lptb = new TableBuilder();
            lptb.setHeader("Key", "Size", "SSTable Count");

            while (!largestPartitions.isEmpty()) {
                PartitionStatistics p = largestPartitions.remove();
                lptb.addRow(
                    cfProxy.formatKey(p.key),
                    Util.humanReadableByteCount(p.size),
                    Integer.toString(p.tableCount)
                );
            }
            System.out.println(lptb);

            System.out.println("SSTable Leaders:");
            TableBuilder sctb = new TableBuilder();
            sctb.setHeader("Key", "SSTable Count", "Size");
            while (!tableCountLeaders.isEmpty()) {
                PartitionStatistics p = tableCountLeaders.remove();
                sctb.addRow(
                    cfProxy.formatKey(p.key),
                    Long.toString(p.tableCount),
                    Util.humanReadableByteCount(p.size)
                );
            }
            System.out.println(sctb);

            System.out.println("SSTables:");
            TableBuilder cltb = new TableBuilder();
            cltb.setHeader(
                "SSTable",
                "Size",
                "Min Timestamp",
                "Max Timestamp",
                "Level",
                "Partitions",
                "Avg Partition Size",
                "Max Partition Size"
            );
            List<SSTableStatistics> sstableStats = partitionReader.getSSTableStatistics();
            Comparator<SSTableStatistics> comparator = SSTableStatistics.LIVENESS_COMPARATOR;
            if (cfProxy.isDTCS()) {
                comparator = SSTableStatistics.DTCS_COMPARATOR;
            }
            if (cfProxy.isTWCS()) {
                comparator = SSTableStatistics.TWCS_COMPARATOR;
            }
            Collections.sort(sstableStats, comparator);
            for (SSTableStatistics stats : sstableStats) {
                cltb.addRow(
                    stats.filename,
                    Util.humanReadableByteCount(stats.size),
                    Util.UTC_DATE_FORMAT.format(new Date(stats.minTimestamp / 1000)),
                    Util.UTC_DATE_FORMAT.format(new Date(stats.maxTimestamp / 1000)),
                    Integer.toString(stats.level),
                    Long.toString(stats.partitionCount),
                    Util.humanReadableByteCount(stats.size / stats.partitionCount),
                    Util.humanReadableByteCount(stats.maxPartitionSize)
                );
            }
            System.out.println(cltb);
        }
    }
}


text:
import {Manager, cmsOperations, abeExtend, cmsData} from '../../../../cli'

var route = function(req, res, next) {
  abeExtend.hooks.instance.trigger('beforeRoute', req, res, next)
  if (typeof res._header !== 'undefined' && res._header !== null) return

  var operation = cmsData.regex.getWorkflowFromOperationsUrl(req.originalUrl)

  var p = cmsOperations.post.submit(
    operation.postUrl,
    req.body.json,
    operation.workflow,
    res.user
  )

  p
    .then(
      result => {
        Manager.instance.events.activity.emit('activity', {
          operation: operation.workflow,
          post: operation.postUrl,
          user: res.user
        })
        res.set('Content-Type', 'application/json')
        res.send(JSON.stringify(result))
      },
      result => {
        res.set('Content-Type', 'application/json')
        res.send(JSON.stringify(result))
      }
    )
    .catch(function(e) {
      console.error('[ERROR] post-save.js', e)
    })
}

export default route


text:
package org.knowm.xchange.examples.gdax;

import java.io.IOException;
import java.util.Arrays;

import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.Trades;
import org.knowm.xchange.gdax.GDAXExchange;
import org.knowm.xchange.gdax.dto.marketdata.GDAXTrade;
import org.knowm.xchange.gdax.service.GDAXMarketDataServiceRaw;
import org.knowm.xchange.service.marketdata.MarketDataService;

public class GDAXTradesDemo {

  public static void main(String[] args) throws IOException {

    Exchange exchange = ExchangeFactory.INSTANCE.createExchange(GDAXExchange.class.getName());
    MarketDataService marketDataService = exchange.getMarketDataService();

    generic(marketDataService);
    raw((GDAXMarketDataServiceRaw) marketDataService);
  }

  public static void generic(MarketDataService marketDataService) throws IOException {

    Trades trades = marketDataService.getTrades(CurrencyPair.BTC_USD);
    System.out.println(trades);
  }

  public static void raw(GDAXMarketDataServiceRaw marketDataServiceRaw) throws IOException {

    GDAXTrade[] trades = marketDataServiceRaw.getGDAXTrades(CurrencyPair.BTC_USD);
    System.out.println(Arrays.toString(trades));
  }
}


text:
package org.jasig.portal.events.aggr.portletlayout;

import java.util.List;

import org.jasig.portal.events.aggr.AggregationInterval;
import org.jasig.portal.events.aggr.BaseAggregationDao;
import org.jasig.portal.events.aggr.groups.AggregatedGroupMapping;
import org.joda.time.DateTime;

/**
 * DAO used to query information about portlet layout aggregates
 *
 * @author Chris Waymire <cwaymire@unicon.net>
 */
public interface PortletLayoutAggregationDao<T extends PortletLayoutAggregation> extends BaseAggregationDao<T,PortletLayoutAggregationKey> {
    /**
     * Get a list of all aggregations for the date range and groups.
     *
     * @param start Start date (inclusive)
     * @param end End date (exclusive)
     * @param interval The aggregation interval
     * @param aggregatedGroupMapping The groups to get data for
     * @param aggregatedGroupMappings The groups to get data for
     * @return
     */
    List<T> getAggregationsForAllPortlets(DateTime start, DateTime end, AggregationInterval interval,
            AggregatedGroupMapping aggregatedGroupMapping, AggregatedGroupMapping... aggregatedGroupMappings);
}


text:
package com.automationrockstars.design.gir.webdriver;

import org.openqa.selenium.By;

public interface CanVerify {

    void verifyVisible();

    void verifyVisible(String failMessage);

    void verifyVisible(String failMessage, HasLocator errorObject);

    void verifyVisible(String failMessage, By errorObject);

}


text: [![Code Climate](https://codeclimate.com/github/SoftwareWise/Koinonia/badges/gpa.svg)](https://codeclimate.com/github/SoftwareWise/Koinonia)


text:
package org.arsenal.framework.core.concurrent;
import org.arsenal.framework.context.Identity;

public interface Worker  extends Identity<String>, java.lang.Runnable {

}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Material extends MX_Controller {

    public function __construct() {
        // parent::__construct();
        $this->load->module('init_sys/Init_sys');
        $this->load->model('Material_models');
    }

    public function material_page()
    {
        // $cat_id = $this->uri->segment(3);
        // $data['raw_detail'] = $this->Material_models->get_group_material($cat_id);
        $data['txt_search_name'] = $this->input->post('txt_search_name');

        $material_list = $this->get_mate_group($data['txt_search_name']);
        $data['material_list'] = array_filter($material_list, function($value) {
            if ($value['cat_type'] == 1) {
                return $value;
            }
        });

        // echo '<pre>', print_r($data['material_list']);exit();

        $data['content']='material/group';

        $this->init_sys->content($data);
    }

    public function material_d_page()
    {
        $data['txt_search_name'] = $this->input->post('txt_search_name');
        $data['cat_id'] = ($this->uri->segment(3) !=''? $this->uri->segment(3) : $this->input->post('cat_id'));
        $qstr_sess=array('select_items_one'=>$data['cat_id']);
        $this->session->set_userdata($qstr_sess);

        $qstr_cate=array('cat_id'=>$data['cat_id']);
        $data['material_detail'] = $this->Material_models->get_raw_material($qstr_cate, $data['txt_search_name']);
        // echo '<pre>', print_r($data['material_detail']);exit();
        $data['content']='material/raw-material-page';

        $this->init_sys->content($data);
    }

    //edit page
    public function edit_page()
    {
        $mat_id = $this->uri->segment(4);
        $data['material_detail'] = $this->Material_models->get_material_details($mat_id);
        $data['content']='material/edit-material';

        $this->init_sys->content($data);
    }

    //page show
    public function raw_page()
    {
        $data['content']='material/add-material';
        $this->init_sys->content($data);
    }

    public function material_group_page()
    {
        $data['content']='material/add-group';
        $this->init_sys->content($data);
    }

    //Add Group
    public function add_mate_group()
    {
        $cat_id = $this->session->userdata("cat_id");
        $timestam = date('Y-m-d H:i:s');

        // $data['material_list'] = $this->get_mate_group();
        $this->Material_models->add_mate_group();
        $this->session->set_flashdata('alert', 1);

        redirect('material/material_page/'.$cat_id);
    }

    public function get_mate_group($qstr ='')
    {
        $result = $this->Material_models->get_mate_group($qstr);
        return $result;
    }

    //Add Material
    public function add_raw_material()
    {
        $mat_id = $this->session->userdata('select_items_one');
        $this->Material_models->add_raw_material();
        $this->session->set_flashdata('alert', 1);

        redirect('material/material_d_page/'.$mat_id);
    }

    public function get_raw_material()
    {
        $this->load->model('Material_models');
        $result = $this->Material_models->get_raw_material();
        return $result;
    }

    //Update form edit
    public function update_material()
    {
        $cat_id = $this->session->userdata('select_items_one');
        $mat_id = $this->uri->segment(3);
        $timestam = date('Y-m-d H:i:s');

        $this->Material_models->update_material($mat_id);
        $this->session->set_flashdata('alert', 1);

        redirect('material/material_d_page/'.$cat_id);
    }

    //delete
    public function delete_material()
    {
        $cat_id = $this->session->userdata('select_items_one');
        $mat_id = $this->uri->segment(3);

        $this->Material_models->delete_material($mat_id);
        $this->session->set_flashdata('alert', 2);

        redirect('material/material_d_page/'.$cat_id);
    }
}//end class