text:
//
// Pythagoras - a collection of geometry classes
// http://github.com/samskivert/pythagoras

package pythagoras.i;

/**
 * An interface provided by all shapes.
 */
public interface IShape
{
    /** Returns true if this shape encloses no area. */
    boolean isEmpty ();

    /** Returns true if this shape contains the specified point. */
    boolean contains (int x, int y);

    /** Returns true if this shape contains the supplied point. */
    boolean contains (IPoint point);

    /** Returns true if this shape completely contains the specified rectangle. */
    boolean contains (int x, int y, int width, int height);

    /** Returns true if this shape completely contains the supplied rectangle. */
    boolean contains (IRectangle r);

    /** Returns true if this shape intersects the specified rectangle. */
    boolean intersects (int x, int y, int width, int height);

    /** Returns true if this shape intersects the supplied rectangle. */
    boolean intersects (IRectangle r);

    /** Returns a copy of the bounding rectangle for this shape. */
    Rectangle bounds ();

    /** Initializes the supplied rectangle with this shape's bounding rectangle.
     * @return the supplied rectangle. */
    Rectangle bounds (Rectangle target);
}


text:
package org.apache.drill.exec.physical.rowSet.model;

import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.record.MaterializedField;
import org.apache.drill.exec.record.VectorContainer;
import org.apache.drill.exec.vector.ValueVector;
import org.apache.drill.exec.vector.complex.AbstractMapVector;
import org.apache.drill.exec.vector.complex.BaseRepeatedValueVector;
import org.apache.drill.exec.vector.complex.ListVector;
import org.apache.drill.exec.vector.complex.RepeatedListVector;
import org.apache.drill.exec.vector.complex.RepeatedMapVector;

public class ContainerVisitor<R, A> {

  public R apply(VectorContainer container, A arg) {
    return visitContainer(container, arg);
  }

  private R visitContainer(VectorContainer container, A arg) {
    return visitChildren(container, arg);
  }

  public R visitChildren(VectorContainer container, A arg) {
    for (int i = 0; i < container.getNumberOfColumns(); i++) {
      @SuppressWarnings("resource")
      ValueVector vector = container.getValueVector(i).getValueVector();
      apply(vector, arg);
    }
    return null;
  }

  protected R apply(ValueVector vector, A arg) {
    MaterializedField schema = vector.getField();
    MajorType majorType = schema.getType();
    MinorType type = majorType.getMinorType();
    DataMode mode = majorType.getMode();
    switch (type) {
    case MAP:
      if (mode == DataMode.REPEATED) {
        return visitRepeatedMap((RepeatedMapVector) vector, arg);
      } else {
        return visitMap((AbstractMapVector) vector, arg);
      }
    case LIST:
      if (mode == DataMode.REPEATED) {
        return visitRepeatedList((RepeatedListVector) vector, arg);
      } else {
        return visitList((ListVector) vector, arg);
      }
    default:
      if (mode == DataMode.REPEATED) {
        return visitRepeatedPrimitive((BaseRepeatedValueVector) vector, arg);
      } else {
        return visitPrimitive(vector, arg);
      }
    }
  }

  protected R visitRepeatedMap(RepeatedMapVector vector, A arg) {
    visitChildren(vector, arg);
    return visitVector(vector, arg);
  }

  protected R visitMap(AbstractMapVector vector, A arg) {
    visitChildren(vector, arg);
    return visitVector(vector, arg);
  }

  private R visitChildren(AbstractMapVector vector, A arg) {
    for (int i = 0; i < vector.size(); i++) {
      apply(vector.getChildByOrdinal(i), arg);
    }
    return null;
  }

  protected R visitRepeatedList(RepeatedListVector vector, A arg) {
    return visitVector(vector, arg);
  }

  protected R visitList(ListVector vector, A arg) {
    return visitVector(vector, arg);
  }

  protected R visitRepeatedPrimitive(BaseRepeatedValueVector vector, A arg) {
    return visitVector(vector, arg);
  }

  protected R visitPrimitive(ValueVector vector, A arg) {
    return visitVector(vector, arg);
  }

  protected R visitVector(ValueVector vector, A arg) {
    return null;
  }

}

redpajama_set_name: RedPajamaGithub


text:
"""Utils tests."""

import pytest

from invenio_records_rest.proxies import current_records_rest
from invenio_records_rest.utils import build_default_endpoint_prefixes

@pytest.mark.parametrize(
    "app",
    [
        dict(
            records_rest_endpoints=dict(
                recid=dict(
                    pid_type="recid",
                    default_endpoint_prefix=False,
                )
            ),
        )
    ],
    indirect=["app"],
)
def test_build_default_endpoint_prefixes_simple(app):
    with app.test_client():
        assert current_records_rest.default_endpoint_prefixes["recid"] == "recid"

@pytest.mark.parametrize(
    "app",
    [
        dict(
            records_rest_endpoints=dict(
                recid=dict(
                    pid_type="recid",
                    default_endpoint_prefix=True,
                )
            ),
        )
    ],
    indirect=["app"],
)
def test_build_default_endpoint_prefixes_simple_with_default(app):
    with app.test_client():
        assert current_records_rest.default_endpoint_prefixes["recid"] == "recid"

@pytest.mark.parametrize(
    "app",
    [
        dict(
            records_rest_endpoints=dict(
                recid=dict(
                    pid_type="recid",
                    default_endpoint_prefix=False,
                ),
                recid2=dict(
                    pid_type="recid",
                    default_endpoint_prefix=False,
                ),
            ),
        )
    ],
    indirect=["app"],
)
def test_build_default_endpoint_prefixes_two_simple_endpoints(app):
    with app.test_client():
        assert current_records_rest.default_endpoint_prefixes["recid"] == "recid"

@pytest.mark.parametrize(
    "app",
    [
        dict(
            records_rest_endpoints=dict(
                recid=dict(
                    pid_type="recid",
                    default_endpoint_prefix=True,
                ),
                recid2=dict(
                    pid_type="recid",
                    default_endpoint_prefix=False,
                ),
            ),
        )
    ],
    indirect=["app"],
)
def test_build_default_endpoint_prefixes_redundant_default(app):
    with app.test_client():
        assert current_records_rest.default_endpoint_prefixes["recid"] == "recid"

@pytest.mark.parametrize(
    "app",
    [
        dict(
            records_rest_endpoints=dict(
                recid=dict(
                    pid_type="recid",
                    default_endpoint_prefix=False,
                ),
                recid2=dict(
                    pid_type="recid",
                    default_endpoint_prefix=True,
                ),
            ),
        )
    ],
    indirect=["app"],
)
def test_build_default_endpoint_prefixes_two_endpoints_with_default(app):
    with app.test_client():
        assert current_records_rest.default_endpoint_prefixes["recid"] == "recid2"

def test_get_default_endpoint_for_inconsistent(app):
    with pytest.raises(ValueError) as excinfo:
        build_default_endpoint_prefixes(
            {
                "recid1": {
                    "pid_type": "recid",
                    "default_endpoint_prefix": True,
                },
                "recid2": {
                    "pid_type": "recid",
                    "default_endpoint_prefix": True,
                },
            }
        )
    assert "More than one" in str(excinfo.value)

    with pytest.raises(ValueError) as excinfo:
        build_default_endpoint_prefixes(
            {
                "recid1": {
                    "pid_type": "recid",
                },
                "recid2": {
                    "pid_type": "recid",
                },
            }
        )
    assert "No endpoint-prefix" in str(excinfo.value)


text:
goog.module('goog.style.bidiTest');
goog.setTestOnly();

const bidi = goog.require('goog.style.bidi');
const dom = goog.require('goog.dom');
const style = goog.require('goog.style');
const testSuite = goog.require('goog.testing.testSuite');
const userAgent = goog.require('goog.userAgent');

// Updates the calculated metrics.
function updateInfo() {
  let element = document.getElementById('scrolledElementRtl');
  /**
   * @suppress {strictMissingProperties} suppression added to enable type
   * checking
   */
  document.getElementById('elementScrollLeftRtl').innerHTML =
      element.offsetParent.scrollLeft;
  document.getElementById('bidiOffsetStartRtl').textContent =
      bidi.getOffsetStart(element);
  /**
   * @suppress {strictMissingProperties} suppression added to enable type
   * checking
   */
  document.getElementById('bidiScrollLeftRtl').textContent =
      bidi.getScrollLeft(element.offsetParent);

  element = document.getElementById('scrolledElementLtr');
  /**
   * @suppress {strictMissingProperties} suppression added to enable type
   * checking
   */
  document.getElementById('elementScrollLeftLtr').innerHTML =
      element.offsetParent.scrollLeft;
  document.getElementById('bidiOffsetStartLtr').textContent =
      bidi.getOffsetStart(element);
  /**
   * @suppress {strictMissingProperties} suppression added to enable type
   * checking
   */
  document.getElementById('bidiScrollLeftLtr').textContent =
      bidi.getScrollLeft(element.offsetParent);
}

testSuite({
  setUpPage() {
    for (const e of Array.from(document.querySelectorAll('.scrollDiv'))) {
      // Defer assigning scroll handlers until after tests begins in case of
      // aberrant scrolls.
      e.addEventListener('scroll', updateInfo);
    }

    updateInfo();
  },

  tearDown() {
    document.documentElement.dir = 'ltr';
    document.body.dir = 'ltr';
  },

  testGetOffsetStart() {
    let elm = document.getElementById('scrolledElementRtl');
    assertEquals(elm.style['right'], bidi.getOffsetStart(elm) + 'px');
    elm = document.getElementById('scrolledElementLtr');
    assertEquals(elm.style['left'], bidi.getOffsetStart(elm) + 'px');
  },

  testSetScrollOffsetRtl() {
    const scrollElm = document.getElementById('scrollDivRtl');
    const scrolledElm = document.getElementById('scrolledElementRtl');
    const originalDistance =
        style.getRelativePosition(scrolledElm, document.body).x;
    const scrollAndAssert = (pixels) => {
      bidi.setScrollOffset(scrollElm, pixels);
      assertEquals(
          originalDistance + pixels,
          style.getRelativePosition(scrolledElm, document.body).x);
    };
    scrollAndAssert(0);
    scrollAndAssert(50);
    scrollAndAssert(100);
    scrollAndAssert(150);
    scrollAndAssert(155);
    scrollAndAssert(0);
  },

  testSetScrollOffsetLtr() {
    const scrollElm = document.getElementById('scrollDivLtr');
    const scrolledElm = document.getElementById('scrolledElementLtr');
    const originalDistance =
        style.getRelativePosition(scrolledElm, document.body).x;
    const scrollAndAssert = (pixels) => {
      bidi.setScrollOffset(scrollElm, pixels);
      assertEquals(
          originalDistance - pixels,
          style.getRelativePosition(scrolledElm, document.body).x);
    };
    scrollAndAssert(0);
    scrollAndAssert(50);
    scrollAndAssert(100);
    scrollAndAssert(150);
    scrollAndAssert(155);
    scrollAndAssert(0);
  },

  /**
     @suppress {strictMissingProperties} suppression added to enable type
     checking
   */
  testFixedBodyChildLtr() {
    const bodyChild = document.getElementById('bodyChild');
    assertEquals(
        userAgent.GECKO ? document.body : null, bodyChild.offsetParent);
    assertEquals(60, bidi.getOffsetStart(bodyChild));
  },

  /**
     @suppress {strictMissingProperties} suppression added to enable type
     checking
   */
  testFixedBodyChildRtl() {
    document.documentElement.dir = 'rtl';
    document.body.dir = 'rtl';

    const bodyChild = document.getElementById('bodyChild');
    assertEquals(
        userAgent.GECKO ? document.body : null, bodyChild.offsetParent);

    /**
     * @suppress {strictMissingProperties} suppression added to enable type
     * checking
     */
    let expectedOffsetStart =
        dom.getViewportSize().width - 60 - bodyChild.offsetWidth;

    // Gecko seems to also add in the marginbox for the body.
    // It's not really clear to me if this is true in the general case,
    // or just under certain conditions.
    if (userAgent.GECKO) {
      const marginBox = style.getMarginBox(document.body);
      expectedOffsetStart -= (marginBox.left + marginBox.right);
    }

    assertEquals(expectedOffsetStart, bidi.getOffsetStart(bodyChild));
  },

  testGetScrollLeftRTL() {
    const scrollLeftDiv = document.getElementById('scrollLeftRtl');
    scrollLeftDiv.style.overflow = 'visible';
    assertEquals(0, bidi.getScrollLeft(scrollLeftDiv));
    scrollLeftDiv.style.overflow = 'hidden';
    assertEquals(0, bidi.getScrollLeft(scrollLeftDiv));
    // NOTE: 'auto' must go above the 'scroll' assertion. Chrome 47 has a bug
    // with non-deterministic scroll positioning. Maybe it recalculates the
    // layout on accessing those properties?
    // TODO(joeltine): Remove this comment when
    // https://code.google.com/p/chromium/issues/detail?id=568706 is resolved.
    scrollLeftDiv.style.overflow = 'auto';
    assertEquals(0, bidi.getScrollLeft(scrollLeftDiv));
    scrollLeftDiv.style.overflow = 'scroll';
    assertEquals(0, bidi.getScrollLeft(scrollLeftDiv));
  },
});


text:
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel.Description;
using System.Xml;
using System.Xml.Schema;
using ServiceImport.Framework.Extension;
using ServiceImport.Framework.Model;

namespace ServiceImport.Framework.Factory
{
    public class WsdlImporterFactory : IWsdlImporterFactory
    {
        public WsdlImporter Create(MetadataSet metadataSet,
            XsdDataContractImporter xsdDataContractImporter,
            Dictionary<XmlQualifiedName, Dictionary<string, NillableOverride>> nillableOverrides,
            IDictionary<XmlTypeCode, XmlTypeMapping> xmlTypeMappings,
            DataContractGenerationOptions dataContractGenerationOptions)
        {
            var serviceModel = new ServiceModel();

            var wsdlImporter = new WsdlImporter(metadataSet);
            wsdlImporter.WsdlImportExtensions.Add(new RemoveIExtensibleDataObjectImplementationExtension());
            wsdlImporter.WsdlImportExtensions.Add(new ServiceModelBuilderExtension(serviceModel));
            wsdlImporter.WsdlImportExtensions.Add(new OperationParameterNillableExtension(serviceModel));
            wsdlImporter.WsdlImportExtensions.Add(new ComplexTypeElementTypeMappingExtension(serviceModel, xmlTypeMappings));

            if ((dataContractGenerationOptions & DataContractGenerationOptions.OptionalElementAsNullable) != 0)
            {
                wsdlImporter.WsdlImportExtensions.Add(new ComplexTypeOptionalElementsNillableExtension(serviceModel));
            }

            wsdlImporter.WsdlImportExtensions.Add(new NillableOverrideExtension(nillableOverrides));
            wsdlImporter.WsdlImportExtensions.Add(new EmitDefaultValueExtension(serviceModel, xmlTypeMappings));
            wsdlImporter.WsdlImportExtensions.Add(new AbstractTypeExtension(serviceModel));
            wsdlImporter.WsdlImportExtensions.Add(new OperationParameterTypeMappingExtension(xmlTypeMappings));
            wsdlImporter.WsdlImportExtensions.Add(new PascalCaseFieldNamesExtension());
            wsdlImporter.WsdlImportExtensions.Add(new OperationParameterPascalCaseExtension());
            wsdlImporter.WsdlImportExtensions.Add(new OperationContractReplyActionRemovalExtension());
            wsdlImporter.WsdlImportExtensions.Add(new XmlCommentExtension(serviceModel));
            wsdlImporter.State.Add(typeof(XsdDataContractImporter), xsdDataContractImporter);
            return wsdlImporter;
        }
    }
}


text:
**I'm submitting a ...**  (check one with "x")
[ ] bug report
[ ] feature request

**Current behavior:**
<!-- Describe how the bug manifests. -->

**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->

**Steps to reproduce:**
<!-- If you are able to illustrate the bug or feature request with an example, please provide steps to reproduce
-->

**Related code:**

```
insert any relevant code here
```

**Other information:**
<!-- List any other information that is relevant to your issue. Stack traces, related issues, suggestions on how to fix, Stack Overflow links, forum links, etc. -->

**Stack trace:**

```
insert the output from the stack trace here
```


text:
namespace IECorePython
{

void bindImfTimeCode();

}

#endif // IECOREPYTHON_IMFTIMECODEBINDING_H


text:
FROM ubuntu:14.04
MAINTAINER Sergey Skripnick <sskripnick@mirantis.com>
COPY . /tmp/rally
RUN apt-get update && \
    apt-get -y install git python2.7 bash-completion python-dev libffi-dev \
                       libxml2-dev libxslt1-dev libssl-dev &&\
    cd /tmp/rally &&\
    ./install_rally.sh &&\
    sed 's|#*connection *=.*|connection = sqlite:////home/rally/.rally.sqlite|' -i /etc/rally/rally.conf &&\
    apt-get -y remove libssl-dev libffi-dev python-dev libxml2-dev \
                      libxslt1-dev build-essential gcc-4.8 python3 && \
    apt-get -y autoremove &&\
    apt-get clean &&\
    mv doc /usr/share/doc/rally &&\
    rm -fr /tmp/* &&\
    rm -rf /var/lib/apt/lists/* &&\
    update-alternatives --install /usr/bin/python python /usr/bin/python2.7 10 &&\
    useradd -u 65500 -m rally &&\
    ln -s /usr/share/doc/rally /home/rally/rally-docs
USER rally
CMD bash --login
ENV HOME /home/rally
WORKDIR /home/rally


text:
package com.sample.tests.pages;

import org.openqa.selenium.WebDriver;

import com.sample.framework.Configuration;
import com.sample.framework.Platform;
import com.sample.framework.ui.FindBy;
import com.sample.framework.ui.Page;
import com.sample.framework.ui.controls.Control;
import com.sample.framework.ui.controls.Edit;
import com.sample.framework.ui.controls.SelectList;
import com.sample.tests.controls.LocationLookupEdit;

public class SearchPage extends Page {

    @FindBy(locator = "search_searchInput", platform = Platform.ANRDOID_NATIVE)
    @FindBy(locator = "ss")
    public LocationLookupEdit editDestination;

    @FindBy(locator = "checkincell", platform = Platform.ANRDOID_NATIVE)
    @FindBy(locator = "css=i.sb-date-field__chevron.bicon-downchevron")
    public Control checkoutDayExpand;

    @FindBy(locator = "xpath=(//android.widget.TextView[contains(@resource-id, 'calendar_tv') and @enabled='true'])[1]",
                platform = Platform.ANRDOID_NATIVE)
    @FindBy(locator = "//table[@class='c2-month-table']//td[contains(@class, 'c2-day-s-today')]")
    public Control checkoutDayToday;

    @FindBy(locator = "business_purpose_leisure", platform = Platform.ANRDOID_NATIVE)
    @FindBy(locator = "xpath=(//input[@name='sb_travel_purpose'])[2]")
    public Control radioLeisure;

    @FindBy(locator = "business_purpose_business", platform = Platform.ANRDOID_NATIVE)
    @FindBy(locator = "xpath=(//input[@name='sb_travel_purpose'])[1]")
    public Control radioBusiness;

    @FindBy(locator = "", platform = Platform.ANRDOID_NATIVE)
    @FindBy(locator = "xpath=(//input[@name='nflt'])[2]")
    public Control radioHotels;

    @FindBy(locator = "adult_count", platform = Platform.ANRDOID_NATIVE)
    @FindBy(locator = "group_adults")
    public SelectList  selectAdultsNumber;

    @FindBy(locator = "search_search", platform = Platform.ANRDOID_NATIVE)
    @FindBy(locator = "//button[@type='submit']")
    public Control buttonSubmit;

    public SearchPage(WebDriver driverValue) {
        super(driverValue);
    }

    @Override
    public Page navigate() {
        if (Configuration.platform().isWeb()) {
            String baseUrl = Configuration.get("url");
            this.getDriver().get(baseUrl);
        }
        return this;
    }
    public void checkInToday() {
        checkoutDayExpand.click();
        checkoutDayToday.click();
    }
    public void selectTravelFor(boolean isLeisure) {
        if (isLeisure) {
            radioLeisure.click();
        } else {
            radioBusiness.click();
        }
    }
}


text:
export default Ember.Route.extend({
  model: function () {
    return this.store.find('redirect').then(function (redirects) {
      redirects.forEach(function (redirect, index) {
        redirect.set('priority', index);
      });
      return Ember.RSVP.Promise.resolve(redirects);
    });
  },
  setupController: function (controller) {

    var siteName = this.get('session.site.name');

    window.ENV.firebaseRoot.child("management/sites/" + siteName + "/dns").once('value', function(snapshot) {
      controller.set('domain', snapshot.val());
    });

    this._super.apply(this, arguments);

  }
});


text:
from setuptools import setup

setup(name='pyecoplug',
        version='0.0.6',
        description='Interface for the EcoPlug outlet',
        url='http://github.com/philburr/pyecoplug',
        author='phil.burr@gmail.com',
        license='MIT',
        packages=['pyecoplug'],
        install_requires=[],
        zip_safe=True)


text:
package org.flowvisor.classifier;

import org.flowvisor.log.SendRecvDropStats;
import org.openflow.protocol.OFMessage;

public interface FVSendMsg {
	public void sendMsg(OFMessage msg, FVSendMsg from);

	public void dropMsg(OFMessage msg, FVSendMsg from);

	public SendRecvDropStats getStats();

	public String getConnectionName();

	public String getName();
}


text:
package com.consol.citrus.dsl.design;

import com.consol.citrus.TestCase;
import com.consol.citrus.actions.ReceiveTimeoutAction;
import com.consol.citrus.container.SequenceAfterTest;
import com.consol.citrus.container.SequenceBeforeTest;
import com.consol.citrus.endpoint.Endpoint;
import com.consol.citrus.report.TestActionListeners;
import com.consol.citrus.testng.AbstractTestNGUnitTest;
import org.mockito.Mockito;
import org.springframework.context.ApplicationContext;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.HashMap;

import static org.mockito.Mockito.*;

/**
 * @author Christoph Deppisch
 * @since 1.3
 */
public class ReceiveTimeoutTestDesignerTest extends AbstractTestNGUnitTest {

    private Endpoint messageEndpoint = Mockito.mock(Endpoint.class);

    private ApplicationContext applicationContextMock = Mockito.mock(ApplicationContext.class);

    @Test
    public void testReceiveTimeoutBuilder() {
        MockTestDesigner builder = new MockTestDesigner(applicationContext, context) {
            @Override
            public void configure() {
                receiveTimeout(messageEndpoint)
                    .timeout(5000)
                    .selector("TestMessageSelectorString");
            }
        };

        builder.configure();

        TestCase test = builder.getTestCase();
        Assert.assertEquals(test.getActionCount(), 1);
        Assert.assertEquals(test.getActions().get(0).getClass(), ReceiveTimeoutAction.class);

        ReceiveTimeoutAction action = (ReceiveTimeoutAction)test.getActions().get(0);
        Assert.assertEquals(action.getName(), "receive-timeout");
        Assert.assertEquals(action.getEndpoint(), messageEndpoint);
        Assert.assertEquals(action.getMessageSelector(),"TestMessageSelectorString");
        Assert.assertEquals(action.getTimeout(), 5000);
    }

    @Test
    public void testReceiveTimeoutBuilderWithEndpointName() {
        reset(applicationContextMock);
        when(applicationContextMock.getBean(TestActionListeners.class)).thenReturn(new TestActionListeners());
        when(applicationContextMock.getBeansOfType(SequenceBeforeTest.class)).thenReturn(new HashMap<String, SequenceBeforeTest>());
        when(applicationContextMock.getBeansOfType(SequenceAfterTest.class)).thenReturn(new HashMap<String, SequenceAfterTest>());
        MockTestDesigner builder = new MockTestDesigner(applicationContextMock, context) {
            @Override
            public void configure() {
                receiveTimeout("fooMessageEndpoint")
                    .timeout(500);
            }
        };

        builder.configure();

        TestCase test = builder.getTestCase();
        Assert.assertEquals(test.getActionCount(), 1);
        Assert.assertEquals(test.getActions().get(0).getClass(), ReceiveTimeoutAction.class);

        ReceiveTimeoutAction action = (ReceiveTimeoutAction)test.getActions().get(0);
        Assert.assertEquals(action.getName(), "receive-timeout");
        Assert.assertEquals(action.getEndpointUri(), "fooMessageEndpoint");
        Assert.assertEquals(action.getTimeout(), 500);

    }
}


text:
import React, { useState } from 'react'

import siteMetadata from '@/data/siteMetadata'

const Disqus = ({ frontMatter }) => {
  const [enableLoadComments, setEnabledLoadComments] = useState(true)

  const COMMENTS_ID = 'disqus_thread'

  function LoadComments() {
    setEnabledLoadComments(false)

    window.disqus_config = function () {
      this.page.url = window.location.href
      this.page.identifier = frontMatter.slug
    }
    if (window.DISQUS === undefined) {
      const script = document.createElement('script')
      script.src = 'https://' + siteMetadata.comment.disqusConfig.shortname + '.disqus.com/embed.js'
      script.setAttribute('data-timestamp', +new Date())
      script.setAttribute('crossorigin', 'anonymous')
      script.async = true
      document.body.appendChild(script)
    } else {
      window.DISQUS.reset({ reload: true })
    }
  }

  return (

      {enableLoadComments && <button onClick={LoadComments}>Load Comments</button>}

  )
}

export default Disqus


text:
@interface DemoViewController ()

@end

@implementation DemoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * indentifier = @"AKBBCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text = @"ABCDEFG";

    return cell;
}

@end


text:
package net.tascalate.concurrent.locks;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

import net.tascalate.concurrent.CompletableFutureWrapper;
import net.tascalate.concurrent.Promise;
import net.tascalate.concurrent.Promises;

abstract class AsyncSemaphoreBase<T> {

    private final long totalPermits;
    private final boolean fair;

    private final AtomicLong availablePermits;
    private final Queue<AbstractSemaphorePromise> waiters;

    AsyncSemaphoreBase(long totalPermits, boolean fair) {
        if (totalPermits <= 0) {
            throw new IllegalArgumentException("totalPermits must be a positive integer");
        }
        this.totalPermits = totalPermits;
        this.fair         = fair;

        availablePermits = new AtomicLong(totalPermits);
        waiters = new ConcurrentLinkedQueue<>();
    }

    public long availablePermits() {
        return availablePermits.get();
    }

    public int getQueueLength() {
        return waiters.size();
    }

    long drainPermitsInternal() {
        if (fair) {
            //nextWaiters();
        }
        long acquired = availablePermits.getAndSet(0);
        return acquired;
    }

    boolean tryAcquireInternal(long permits) {
        if (permits <= 0 || permits > totalPermits) {
            throw new IllegalArgumentException(
                String.format("Requested number of permits %d is not within range 1..%d", permits, totalPermits)
            );
        }

        if (fair) {
            //nextWaiters();
            if (null != waiters.peek()) {
                // Let fulfill queued requests first
                return false;
            }
        }

        boolean[] altered = {false};
        availablePermits.accumulateAndGet(permits, (current, delta) -> {
            if (current >= delta) {
                altered[0]  = true;
                return current - delta;
            } else {
                altered[0] = false;
                return current;
            }
        });
        return altered[0];
    }

    public Promise<T> acquire(long permits) {
        // argument check is in tryAcquire
        if (tryAcquireInternal(permits)) {
            return Promises.success(createPromisePayload(permits));
        } else {
            AbstractSemaphorePromise promise = createPromise(permits);
            waiters.add(promise);
            // Need to call waiters while available permits might change
            // right after adding this promise to the queue
            nextWaiters();
            return promise;
        }
    }

    void release(long permits) {
        long current = availablePermits.addAndGet(permits);
        if (current < 0 || current > totalPermits) {
            throw new IllegalStateException(String.format(
                "After releasing %d permits number of available permits %d is not within range 1..%d",
                permits, current, totalPermits
            ));
        }
        nextWaiters();
    }

    abstract protected T createPromisePayload(long permits);
    abstract protected AbstractSemaphorePromise createPromise(long permits);

    private void nextWaiters() {
        AbstractSemaphorePromise head = null;
        do {
            head = waiters.peek();
            if (null == head) {
                // waiters queue is empty
                break;
            }

            if (head.lock()) {
                try {
                    if (head.isDone()) {
                        // Same as edge case below - just for speed-up:
                        // If canceled fully or canceling is in progress
                        // remove here just to avoid wasting cycles
                        // when same remove is running in
                        // AbstractSemaphorePromise.cancel
                        waiters.remove(head);
                        continue;
                    }

                    long oldPermits = availablePermits.get();
                    long newPermits = oldPermits - head.permits();
                    if (newPermits < 0) {
                        // No available permits
                        // just exit loop
                        break;
                    }

                    if (availablePermits.compareAndSet(oldPermits, newPermits)) {
                        if (head.acquire()) {
                            // due to head.acquire each head may be removed only once
                            // regardless of concurrent access (due to inherited CompletableFuture behavior)
                            AbstractSemaphorePromise found = waiters.poll();
                            if (found != head) {
                                throw new IllegalStateException("The acquired semaphore promise is not equal to the top of the queue");
                            }
                        } else {
                            // Edge case:
                            // head was cancelled concurrently revert permits and continue;
                            // same as with releasePermits but with loop instead of recursion
                            waiters.remove(head); // ???
                            availablePermits.addAndGet(head.permits());
                        }
                    } else {
                        // concurrently acquired permits --
                        // need re-check on next iteration
                    }
                } finally {
                    head.unlock();
                }
            } else {
                // concurrent access to the same head
                // just exit loop in this thread
                break;
            }
        } while (head != null);
    }

    @Override
    public String toString() {
        return String.format(
            "%s(totalPermits=%d, fair=%s, availablePermits=%d, queueSize=%d)",
            getClass().getSimpleName(), totalPermits, fair, availablePermits.get(), waiters.size()
        );
    }

    abstract protected class AbstractSemaphorePromise extends CompletableFutureWrapper<T> {
        private final AtomicBoolean locked = new AtomicBoolean();

        boolean lock() {
            return locked.compareAndSet(false,  true);
        }

        boolean unlock() {
            return locked.compareAndSet(true,  false);
        }

        abstract long permits();

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            if (super.cancel(mayInterruptIfRunning)) {
                waiters.remove(this);
                return true;
            } else {
                return false;
            }
        }

        abstract boolean acquire();
    }

}


text:
"""
.. module:: dj-stripe.tests.test_mixins
   :synopsis: dj-stripe Mixin Tests.

.. moduleauthor:: Alex Kavanaugh (@kavdev)

"""

from copy import deepcopy

from django.contrib.auth import get_user_model
from django.test.client import RequestFactory
from django.test.testcases import TestCase
from mock import patch

from djstripe.mixins import PaymentsContextMixin, SubscriptionMixin
from djstripe.models import Plan
from tests import FAKE_CUSTOMER, FAKE_PLAN, FAKE_PLAN_II

class TestPaymentsContextMixin(TestCase):

    def test_get_context_data(self):
        from django.conf import settings

        class TestSuperView(object):
            def get_context_data(self):
                return {}

        class TestView(PaymentsContextMixin, TestSuperView):
            pass

        context = TestView().get_context_data()
        self.assertIn("STRIPE_PUBLIC_KEY", context, "STRIPE_PUBLIC_KEY missing from context.")
        self.assertEqual(context["STRIPE_PUBLIC_KEY"], settings.STRIPE_PUBLIC_KEY, "Incorrect STRIPE_PUBLIC_KEY.")

        self.assertIn("plans", context, "pans missing from context.")
        self.assertEqual(list(Plan.objects.all()), list(context["plans"]), "Incorrect plans.")

class TestSubscriptionMixin(TestCase):

    def setUp(self):
        Plan.sync_from_stripe_data(deepcopy(FAKE_PLAN))
        Plan.sync_from_stripe_data(deepcopy(FAKE_PLAN_II))

    @patch("stripe.Customer.create", return_value=deepcopy(FAKE_CUSTOMER))
    def test_get_context_data(self, stripe_create_customer_mock):

        class TestSuperView(object):
            def get_context_data(self):
                return {}

        class TestView(SubscriptionMixin, TestSuperView):
            pass

        test_view = TestView()

        test_view.request = RequestFactory()
        test_view.request.user = get_user_model().objects.create(username="x", email="user@test.com")

        context = test_view.get_context_data()
        self.assertIn("is_plans_plural", context, "is_plans_plural missing from context.")
        self.assertTrue(context["is_plans_plural"], "Incorrect is_plans_plural.")

        self.assertIn("customer", context, "customer missing from context.")


text:
class ShoppingList < ApplicationRecord
  belongs_to :store
  belongs_to :user
  validates :date, presence: true
end


text:
package com.vmware.vim25;
import lombok.Getter;
import lombok.Setter;

/**
 * Created by Michael Rice on Sun May 24 16:15:36 CDT 2015
 *
 * Copyright 2015 Michael Rice
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * @since 6.0
 */

public class VirtualMachineVMCIDeviceOption extends VirtualDeviceOption {
    @Getter @Setter public BoolOption allowUnrestrictedCommunication;
    @Getter @Setter public VirtualMachineVMCIDeviceOptionFilterSpecOption filterSpecOption;
    @Getter @Setter public BoolOption filterSupported;
}


text:
        Home

      Overview

      Concepts

      History

      Team

      Versions


text:
package me.fornever.checktimer

import java.io.File
import java.nio.charset.StandardCharsets
import java.nio.file.Files

import org.scalatest.{FlatSpec, Matchers}

class ConfigurationSpec extends FlatSpec with Matchers {

  "The Configuration" should "load the default instance if the file doesn't exist" in {
    val nonexistent = File.createTempFile("checktimer", "cfg")
    nonexistent.delete()

    Configuration.loadFrom(nonexistent.getAbsolutePath) should be(Configuration.default)
  }

  it should "be loaded from existing file successfully" in {
    val configFile = File.createTempFile("checktimer", "cfg")
    configFile.deleteOnExit()

    Files.write(
      configFile.toPath,
      """
        |database: "C:\\Users\\Герасим\\checktimer.csv"
        |task: "zomg"
      """.stripMargin.getBytes(StandardCharsets.UTF_8))

    val config = Configuration("C:\\Users\\Герасим\\checktimer.csv", "zomg")
    Configuration.loadFrom(configFile.getAbsolutePath) should be(config)
  }
}


text:
namespace Google.Cloud.Dlp.V2.Snippets
{
    // [START dlp_v2_generated_DlpService_DeleteDlpJob_async_flattened_resourceNames]
    using Google.Cloud.Dlp.V2;
    using System.Threading.Tasks;

    public sealed partial class GeneratedDlpServiceClientSnippets
    {
        /// <summary>Snippet for DeleteDlpJobAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task DeleteDlpJobResourceNamesAsync()
        {
            // Create client
            DlpServiceClient dlpServiceClient = await DlpServiceClient.CreateAsync();
            // Initialize request argument(s)
            DlpJobName name = DlpJobName.FromProjectDlpJob("[PROJECT]", "[DLP_JOB]");
            // Make the request
            await dlpServiceClient.DeleteDlpJobAsync(name);
        }
    }
    // [END dlp_v2_generated_DlpService_DeleteDlpJob_async_flattened_resourceNames]
}


text:
module Hans.Socket.Handle(makeHansHandle) where

import Control.Concurrent
import Control.Concurrent.MVar
import Control.Exception
import Control.Monad
import qualified Data.ByteString as BSS
import Data.ByteString.Lazy(ByteString)
import qualified Data.ByteString.Lazy as BS
import Data.Typeable
import Foreign.Ptr
import GHC.IO.Buffer
import GHC.IO.BufferedIO
import GHC.IO.Device
import GHC.IO.Handle
import Hans.Layer.Tcp.Socket(canSend, canRecv)
import Hans.NetworkStack
import Prelude hiding (read)
import System.IO

data BufferedSocket = BS {
    bsSocket   :: Socket
  , bsRefCount :: MVar Int
  }
 deriving (Typeable)

newBufferedSocket :: Socket -> IO BufferedSocket
newBufferedSocket sock =
  do mv <- newMVar 1
     return (BS sock mv)

addRef :: BufferedSocket -> IO ()
addRef bs = modifyMVar_ (bsRefCount bs) (return . (+ 1))

dropRef :: BufferedSocket -> IO ()
dropRef bs =
  do count <- modifyMVar (bsRefCount bs) $
                \ x ->
                  let x' = x - 1
                  in return (x', x')
     when (count == 0) $ Hans.NetworkStack.close (bsSocket bs)

instance IODevice BufferedSocket where
  ready dev write msecs =
    do let tester = if write then canSend else canRecv
       canDo <- tester (bsSocket dev)
       if | canDo      -> return True
          | msecs <= 0 -> return False
          | otherwise  -> do let delay = min msecs 100
                             threadDelay (delay * 1000)
                             ready dev write (msecs - delay)
  close bs     = dropRef bs
  isTerminal _ = return False
  isSeekable _ = return False
  seek _ _ _   = throwIO (userError "Seek on HaNS socket.")
  tell _       = throwIO (userError "Tell on HaNS socket.")
  getSize _    = throwIO (userError "getSize on HaNS socket.")
  setSize _ _  = throwIO (userError "setSize on HaNS socket.")
  setEcho _ _  = throwIO (userError "setEcho on HaNS socket.")
  getEcho _    = throwIO (userError "getEcho on HaNS socket.")
  setRaw _ _   = return ()
  devType _    = return Stream
  dup bs       = addRef bs >> return bs
  dup2 _ _     = throwIO (userError "dup2 on HaNS socket.")

instance RawIO BufferedSocket where
  read sock dptr sz =
    do bstr <- recvBytes (bsSocket sock) (fromIntegral sz)
       when (BS.length bstr > 0) $ copyBS (BS.toChunks bstr) dptr sz
       return (fromIntegral (BS.length bstr))
  readNonBlocking sock dptr sz =
    do canGo <- canRecv (bsSocket sock)
       if canGo
          then Just `fmap` read sock dptr sz
          else return (Just 0)
  write sock ptr sz =
    do bstr <- BSS.packCStringLen (castPtr ptr, sz)
       sendAll (bsSocket sock) (BS.fromStrict bstr)
   where
    sendAll sock bstr
      | BS.null bstr = return ()
      | otherwise    = do num <- sendBytes sock bstr
                          sendAll sock (BS.drop (fromIntegral num) bstr)
  writeNonBlocking sock ptr sz =
    do canGo <- canSend (bsSocket sock)
       if canGo
          then do bstr <- BSS.packCStringLen (castPtr ptr, sz)
                  num  <- sendBytes (bsSocket sock) (BS.fromStrict bstr)
                  return (fromIntegral num)
          else return 0

instance BufferedIO BufferedSocket where
  newBuffer         _ = newByteBuffer (64 * 1024)
  fillReadBuffer      = readBuf
  fillReadBuffer0     = readBufNonBlocking
  flushWriteBuffer    = writeBuf
  flushWriteBuffer0   = writeBufNonBlocking

makeHansHandle :: Socket -> IOMode -> IO Handle
makeHansHandle socket mode =
  do buffSocket <- newBufferedSocket socket
     mkFileHandle buffSocket "<socket>" mode Nothing noNewlineTranslation

copyBS :: [BSS.ByteString] -> Ptr a -> Int -> IO ()
copyBS [] _ _ = return ()
copyBS (f:rest) sptr szLeft
  | BSS.null f   = copyBS rest sptr szLeft
  | szLeft <= 0  = return ()
  | otherwise    =
      do let (chunk1, chunk2) = BSS.splitAt szLeft f
             amt              = fromIntegral (BSS.length chunk1)
         BSS.useAsCString chunk1 $ \ dptr -> memcpy dptr sptr amt
         copyBS (chunk2 : rest) (sptr `plusPtr` amt) (szLeft - amt)

foreign import ccall unsafe "string.h memcpy"
  memcpy :: Ptr a -> Ptr b -> Int -> IO ()


text:
This is a simple module for applying source maps to JS stack traces in the browser.

## The problem this solves

You have Error.stack() in JS (maybe you're logging a trace, or you're looking at
traces in Jasmine or Mocha), and you need to apply a sourcemap so you can
understand whats happening because you're using some fancy compiled-to-js thing
like coffeescript or traceur. Unfortunately, the browser only applies sourcemaps when the
trace is viewed in its console, not to the underlying stack object, so you're
out of luck.

## Demo

http://novocaine.github.io/sourcemapped-stacktrace-demo/public_html/smst.html

## Install from npm

```
npm install sourcemapped-stacktrace
```

https://www.npmjs.com/package/sourcemapped-stacktrace

The npm bundle contains dist/sourcemapped-stacktrace.js, if that's what you're
after. The built product is not held in this repo.

## Setup

Include sourcemapped-stacktrace.js into your page using either an AMD module
loader or a plain old script include. As an AMD module it exposes the method
'mapStackTrace'. If an AMD loader is not found this function will be set on
window.sourceMappedStackTrace.mapStackTrace.

## API

### mapStackTrace(stack, done [, opts])

Re-map entries in a stacktrace using sourcemaps if available.

**Arguments:**

- *stack*: (str) The stacktrace from the browser.

- *done*: Callback invoked with the transformed stacktrace (an Array of Strings) passed as the first argument

- *opts*: Optional options object containing:
  - *filter*: Function that filters each stacktrace line.
              It is invoked with _(line)_ and should return truthy/ falsy value.
              Sources which do not pass the filter won't be processed.
  - *cacheGlobally*: Boolean. If `true`, sourcemaps are cached across multiple `mapStackTrace()` calls,
                     allowing for better performance if called repeatedly, or when browser's cache is disabled.
                     Defaults to `false`.
  - *sync*: Boolean. Whether to use synchronous ajax to load the sourcemaps.

**Supported browsers**
  - Chrome
  - Firefox
  - Safari
  - Internet Explorer 11 and up
  - Microsoft Edge

## Example

```javascript
try {
  // break something
  bork();
} catch (e) {
  // pass e.stack to window.mapStackTrace
  window.mapStackTrace(e.stack, function(mappedStack) {
    // do what you want with mappedStack here
    console.log(mappedStack.join("\n"));
  }, {
    filter: function (line) {
      // process only sources containing `spec.js`
      return /(spec\.js)/.test(line);
    }
  });
}
```

## Longer Explanation

Several modern browsers support sourcemaps when viewing stack traces from errors in their native console, but as of the time of writing there is no support for applying a sourcemap to the (highly non-standardised) [Error.prototype.stack](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack). Error.prototype.stack can be used for logging errors and for displaying errors in test frameworks, and it is not very convenient to have unmapped traces in either of those use cases.

This module fetches all the scripts referenced by the stack trace, determines
whether they have an applicable sourcemap, fetches the sourcemap from the
server, then uses the [Mozilla source-map library](https://github.com/mozilla/source-map/) to do the mapping. Browsers that support sourcemaps don't offer a standardised sourcemap API, so we have to do all that work ourselves.

The nice part about doing it ourselves is that the library could be extended to
work in browsers that don't support sourcemaps, which could be good for
logging and debugging problems. Currently, only Chrome and Firefox are supported, but it
would be easy to support those formats by ripping off [stacktrace.js](https://github.com/stacktracejs/stacktrace.js/).

## Known issues

* Doesn't support exception formats of any browser other than Chrome and
  Firefox
* Only supports JS containing //# sourceMappingURL= declarations (i.e. no
  support for the SourceMap: HTTP header (yet)
* Some prominent sourcemap generators (including CoffeeScript, Traceur, Babel)
  don't emit a list of 'names' in the source-map, which means that frames from transpiled code will have (unknown) instead of the original function name. Those generators should support this feature better.


text:
/*!
   angular-block-ui v0.2.0
   (c) 2015 (null) McNull https://github.com/McNull/angular-block-ui
   License: MIT
*/

.block-ui {
  position: relative;
}

body.block-ui {
  /* IE8 doesn't support .block-ui:not(body) */

  position: static;
}

body.block-ui > .block-ui-container,
.block-ui-main > .block-ui-container {
  position: fixed;
}

.block-ui-container {
  position: absolute;
  z-index: 20000; /*original value: 10000; modified for webreserve requirements*/
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  height: 0;
  overflow: hidden;
  opacity: 0;
  filter: alpha(opacity=00);
}

.block-ui-active > .block-ui-container {
  height: 100%;
  /*cursor: wait;*/ /*original value removed for webreserve requirements*/
}

.block-ui-active .block-ui-active > .block-ui-container {
  height: 0;
}

.block-ui-visible > .block-ui-container {
  opacity: 1;
  filter: alpha(opacity=100);
}

.block-ui-overlay {
  width: 100%;
  height: 100%;
  opacity: 0.5;
  filter: alpha(opacity=50);
  background-color: darkgrey; /*original value: white; modified for webreserve requirements*/
}
.block-ui-overlay .backgroundNone {
  background-color: none; /*original value: white; modified for webreserve requirements*/
}

.block-ui-message-container {
  position: absolute;
  top: 35%;
  left: 0;
  right: 0;
  height: 0;
  text-align: center;
  z-index: 20001;/* original value: 10001; modified for webreserve requirements*/
}

/* modified by shashi for webreserve requirements */
.block-ui-message {
  display: inline-block;
  text-align: left;
  background-color: #fff;
  color: #333;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;

  filter: alpha(opacity=100);
}

/* original */
/*.block-ui-message {
  display: inline-block;
  text-align: left;
  background-color: #333;
  color: #f5f5f5;
  padding: 20px;
  border-radius: 4px;
  font-size: 20px;
  font-weight: bold;

  filter: alpha(opacity=100);
}*/

/* - - - - - - 8-< - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

.block-ui-anim-fade > .block-ui-container {
  -webkit-transition: height 0s linear 200ms, opacity 200ms ease 0s;
          transition: height 0s linear 200ms, opacity 200ms ease 0s;
}

.block-ui-anim-fade.block-ui-active > .block-ui-container {
  /*this resets the initial delay of the height */
  /*and sizes the block to full height at once at the start of the block. */
  -webkit-transition-delay: 0s;
          transition-delay: 0s;
}

/* - - - - - - 8-< - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*# sourceMappingURL=angular-block-ui.css.map */


text:
namespace protobuf {
    namespace socketrpc {

        void SocketRpcController::Reset() {
            failed = false;
            error = "";        }

        bool SocketRpcController::Failed() const {
            return failed;
        }

        std::string SocketRpcController::ErrorText() const {
            return error;
        }

        void SocketRpcController::StartCancel() {
            throw "Not supported";
        }

        void SocketRpcController::SetFailed(const std::string& reason) {
            this->failed = true;
            this->error = reason;
        }

        void SocketRpcController::SetFailed(const std::string &error, ErrorReason reason) {
            this->failed = true;
            this->error = error;
            this->reason = reason;
        }

        bool SocketRpcController::IsCanceled() const {
            throw "Not supported";
        }

        void SocketRpcController::NotifyOnCancel(google::protobuf::Closure* callback) {
            throw "Not supported";
        }

    } // namespace
} // namespace


text:
layout: wiki
title: Fragment
cate1: Android
cate2: Components
description: Fragment
keywords: Android
---

## 生命周期

![fragment lifecycle](/images/wiki/fragment-lifecycle.png)

* 在 Fragment 从 BackStack 恢复时,Fragment 对象本身没有销毁,但它里面的 View 销毁重建了。

    保存并恢复 View 的数据的最佳实践是让每个 View 都自己实现了 onSaveInstanceState/onRestoreInstanceState。

    对于 ListView,其实在销毁重建 View 时调用 onCreateView 时,保存的 Fragment 实例里的 mAdapter 并没有销毁,所以可以直接使用里面保存的数据,不用再 new 一个。

    参考:[The Real Best Practices to Save/Restore Activity's and Fragment's state.](https://inthecheesefactory.com/blog/fragment-state-saving-best-practices/en)

## 对应 Activity 状态的 Callbacks

![activity state and fragment callbacks](/images/wiki/activity-state-and-fragment-callbacks.png)

## 遇到的问题

### 点击穿透

比如一个 Fragment 作为 DrawerLayout 里的 Drawer,点击这个 Fragment 没有控件的部分时,如果被覆盖的 Fragment 或者 Activity 上对应位置有按钮,点击事件会分发到这些按钮上去。

解决办法:

给 Fragment 的根 View 添加 clickable 属性,有两种实现方法,推荐第二种。

1. 给所有需要解决此问题的 Fragment 的 Layout 文件的根结点添加 `android:clickable="true"`。

2. 所有 Fragment 继承自一个基类 BaseFragment,覆盖 BaseFragment 的 `onViewCreated` 方法(该方法会在 `onCreateView` 返回之后被调用),在该方法里用代码设置根 View 的 clickable 属性。

    ```java
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 解决点击穿透的问题
        view.setClickable(true);
        ......
    }
    ```

### replace 切换后恢复状态

使用 replace 方式切换 Fragment 后,又切换回来,此时 onCreateView 又会被调用到,如果重新 inflate layout,那界面状态会丢失,比如 Fragment 里有 WebView,那它的滚动位置等会丢失掉。

一种解决办法是在 onCreateView 里将 root view 保存下来,下次 onCreateView 被调用到时,判断 root 是否为空,为空就重新 inflate,不为空就直接复用:

```java
public class MyFragment extends Fragment {

    private View mRoot;

    @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            if (mRoot != null) {
                return mRoot;
            } else {
                // 重新 inflate layout,设置 View 和 data 等
                // ...
            }
        }
}
```


text:
using System;
using System.Diagnostics;
using System.Linq;
using SystemsRx.Extensions;
using EcsRx.Components;
using EcsRx.Examples.Application;
using EcsRx.Examples.ExampleApps.Performance.Helper;
using EcsRx.Extensions;

namespace EcsRx.Examples.ExampleApps.Performance
{
    public class GroupPerformanceApplication : EcsRxConsoleApplication
    {
        private IComponent[] _availableComponents;
        private readonly RandomGroupFactory _groupFactory = new RandomGroupFactory();

        protected override void BindSystems()
        {}

        protected override void ApplicationStarted()
        {
            _availableComponents = _groupFactory.GetComponentTypes
                .Select(x => Activator.CreateInstance(x) as IComponent)
                .ToArray();

            var groups = _groupFactory.CreateTestGroups().ToArray();
            foreach (var group in groups)
            { ObservableGroupManager.GetObservableGroup(group); }

            var firstRun = ProcessEntities(10000);
            var secondRun = ProcessEntities(10000);
            var thirdRun = ProcessEntities(10000);

            Console.WriteLine($"Finished In: {(firstRun + secondRun + thirdRun).TotalSeconds}s");
            Console.WriteLine($"First Took: {firstRun.TotalSeconds}s");
            Console.WriteLine($"Second Took: {secondRun.TotalSeconds}s");
            Console.WriteLine($"Third Took: {thirdRun.TotalSeconds}s");
        }

        private TimeSpan ProcessEntities(int amount)
        {
            var defaultPool = EntityDatabase.GetCollection();
            EntityDatabase.Collections.ForEachRun(x => x.RemoveAllEntities());
            GC.Collect();

            var timer = Stopwatch.StartNew();

            for (var i = 0; i < amount; i++)
            {
                var entity = defaultPool.CreateEntity();
                entity.AddComponents(_availableComponents);
                entity.RemoveComponents(_availableComponents);
            }

            timer.Stop();
            return TimeSpan.FromMilliseconds(timer.ElapsedMilliseconds);
        }
    }
}


text:
package org.wildfly.extras.creaper.commands.elytron.mapper;

import java.io.IOException;
import java.util.List;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.core.CommandFailedException;
import org.wildfly.extras.creaper.core.online.operations.Address;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

@RunWith(Arquillian.class)
public class AddAggregatePrincipalDecoderOnlineTest extends AbstractAddPrincipalDecoderOnlineTest {

    private static final String TEST_AGGREGATE_PRINCIPAL_DECODER_NAME = "CreaperTestAggregatePrincipalDecoder";
    private static final Address TEST_AGGREGATE_PRINCIPAL_DECODER_ADDRESS = SUBSYSTEM_ADDRESS
            .and("aggregate-principal-decoder", TEST_AGGREGATE_PRINCIPAL_DECODER_NAME);
    private static final String TEST_AGGREGATE_PRINCIPAL_DECODER_NAME2 = "CreaperTestAggregatePrincipalDecoder2";
    private static final Address TEST_AGGREGATE_PRINCIPAL_DECODER_ADDRESS2 = SUBSYSTEM_ADDRESS
            .and("aggregate-principal-decoder", TEST_AGGREGATE_PRINCIPAL_DECODER_NAME2);

    @After
    public void cleanup() throws Exception {
        ops.removeIfExists(TEST_AGGREGATE_PRINCIPAL_DECODER_ADDRESS);
        ops.removeIfExists(TEST_AGGREGATE_PRINCIPAL_DECODER_ADDRESS2);
        administration.reloadIfRequired();
    }

    @Test
    public void addAggregatePrincipalDecoder() throws Exception {
        AddAggregatePrincipalDecoder addAggregatePricipalDecoder
                = new AddAggregatePrincipalDecoder.Builder(TEST_AGGREGATE_PRINCIPAL_DECODER_NAME)
                .principalDecoders(TEST_CONSTANT_PRINCIPAL_DECODER_NAME, TEST_CONSTANT_PRINCIPAL_DECODER_NAME2)
                .build();

        client.apply(addAggregatePricipalDecoder);

        assertTrue("Aggregate-principal-decoder should be created",
                ops.exists(TEST_AGGREGATE_PRINCIPAL_DECODER_ADDRESS));
        checkAggregatePrincipalDecoderAttribute("principal-decoders", PRINCIPAL_DECODERS_1_AND_2);
    }

    @Test
    public void addTwoAggregatePrincipalDecoders() throws Exception {
        AddAggregatePrincipalDecoder addAggregatePricipalDecoder
                = new AddAggregatePrincipalDecoder.Builder(TEST_AGGREGATE_PRINCIPAL_DECODER_NAME)
                .principalDecoders(TEST_CONSTANT_PRINCIPAL_DECODER_NAME, TEST_CONSTANT_PRINCIPAL_DECODER_NAME2)
                .build();

        AddAggregatePrincipalDecoder addAggregatePricipalDecoder2
                = new AddAggregatePrincipalDecoder.Builder(TEST_AGGREGATE_PRINCIPAL_DECODER_NAME2)
                .principalDecoders(TEST_CONSTANT_PRINCIPAL_DECODER_NAME2, TEST_DIFFERENT_PRINCIPAL_DECODER_NAME)
                .build();

        client.apply(addAggregatePricipalDecoder);
        client.apply(addAggregatePricipalDecoder2);

        assertTrue("Aggregate-principal-decoder should be created",
                ops.exists(TEST_AGGREGATE_PRINCIPAL_DECODER_ADDRESS));
        assertTrue("Aggregate-principal-decoder should be created",
                ops.exists(TEST_AGGREGATE_PRINCIPAL_DECODER_ADDRESS2));
    }

    @Test(expected = CommandFailedException.class)
    public void addExistAggregatePrincipalDecodersNotAllowed() throws Exception {
        AddAggregatePrincipalDecoder addAggregatePricipalDecoder
                = new AddAggregatePrincipalDecoder.Builder(TEST_AGGREGATE_PRINCIPAL_DECODER_NAME)
                .principalDecoders(TEST_CONSTANT_PRINCIPAL_DECODER_NAME, TEST_CONSTANT_PRINCIPAL_DECODER_NAME2)
                .build();

        AddAggregatePrincipalDecoder addAggregatePricipalDecoder2
                = new AddAggregatePrincipalDecoder.Builder(TEST_AGGREGATE_PRINCIPAL_DECODER_NAME)
                .principalDecoders(TEST_CONSTANT_PRINCIPAL_DECODER_NAME2, TEST_DIFFERENT_PRINCIPAL_DECODER_NAME)
                .build();

        client.apply(addAggregatePricipalDecoder);
        assertTrue("Aggregate-principal-decoder should be created",
                ops.exists(TEST_AGGREGATE_PRINCIPAL_DECODER_ADDRESS));

        client.apply(addAggregatePricipalDecoder2);
        fail("Aggregate-principal-decoder CreaperTestAggregatePrincipalDecoder already exists in configuration, exception should be thrown");
    }

    @Test
    public void addExistAggregatePrincipalDecodersAllowed() throws Exception {
        AddAggregatePrincipalDecoder addAggregatePricipalDecoder
                = new AddAggregatePrincipalDecoder.Builder(TEST_AGGREGATE_PRINCIPAL_DECODER_NAME)
                .principalDecoders(TEST_CONSTANT_PRINCIPAL_DECODER_NAME, TEST_CONSTANT_PRINCIPAL_DECODER_NAME2)
                .build();

        AddAggregatePrincipalDecoder addAggregatePricipalDecoder2
                = new AddAggregatePrincipalDecoder.Builder(TEST_AGGREGATE_PRINCIPAL_DECODER_NAME)
                .principalDecoders(TEST_CONSTANT_PRINCIPAL_DECODER_NAME2, TEST_DIFFERENT_PRINCIPAL_DECODER_NAME)
                .replaceExisting()
                .build();

        client.apply(addAggregatePricipalDecoder);
        assertTrue("Aggregate-principal-decoder should be created",
                ops.exists(TEST_AGGREGATE_PRINCIPAL_DECODER_ADDRESS));

        client.apply(addAggregatePricipalDecoder2);
        assertTrue("Aggregate-principal-decoder should be created",
                ops.exists(TEST_AGGREGATE_PRINCIPAL_DECODER_ADDRESS));
        checkAggregatePrincipalDecoderAttribute("principal-decoders", PRINCIPAL_DECODERS_2_AND_DIFFERENT);
    }

    @Test(expected = CommandFailedException.class)
    public void addAggregatePrincipalDecoderWithoutConfiguredPrincipalsDecoders() throws Exception {
        AddAggregatePrincipalDecoder addAggregatePricipalDecoder
                = new AddAggregatePrincipalDecoder.Builder(TEST_AGGREGATE_PRINCIPAL_DECODER_NAME)
                .principalDecoders(TEST_CONSTANT_PRINCIPAL_DECODER_NAME, "NotConfiguredPrincipalDecoder")
                .build();

        client.apply(addAggregatePricipalDecoder);
        fail("Aggregate-principal-decoder shouldn't be added when using unconfigured principal decoder");
    }

    @Test(expected = IllegalArgumentException.class)
    public void addAggregatePrincipalDecoder_nullName() throws Exception {
        new AddAggregatePrincipalDecoder.Builder(null)
            .principalDecoders(TEST_CONSTANT_PRINCIPAL_DECODER_NAME, TEST_CONSTANT_PRINCIPAL_DECODER_NAME2)
            .build();
        fail("Creating command with null name should throw exception");
    }

    @Test(expected = IllegalArgumentException.class)
    public void addAggregatePrincipalDecoder_emptyName() throws Exception {
        new AddAggregatePrincipalDecoder.Builder("")
            .principalDecoders(TEST_CONSTANT_PRINCIPAL_DECODER_NAME, TEST_CONSTANT_PRINCIPAL_DECODER_NAME2)
            .build();
        fail("Creating command with empty name should throw exception");
    }

    @Test(expected = IllegalArgumentException.class)
    public void addAggregatePrincipalDecoder_nullPrincipalDecoders() throws Exception {
        new AddAggregatePrincipalDecoder.Builder(TEST_AGGREGATE_PRINCIPAL_DECODER_NAME)
            .principalDecoders(null)
            .build();
        fail("Creating command with null principal-decoders should throw exception");
    }

    @Test(expected = IllegalArgumentException.class)
    public void addAggregatePrincipalDecoder_emptyPrincipalDecoders() throws Exception {
        new AddAggregatePrincipalDecoder.Builder(TEST_AGGREGATE_PRINCIPAL_DECODER_NAME)
            .principalDecoders("")
            .build();
        fail("Creating command with empty principal-decoders should throw exception");
    }

    @Test(expected = IllegalArgumentException.class)
    public void addAggregatePrincipalDecoder_onePrincipalDecoder() throws Exception {
        new AddAggregatePrincipalDecoder.Builder(TEST_AGGREGATE_PRINCIPAL_DECODER_NAME)
            .principalDecoders(TEST_CONSTANT_PRINCIPAL_DECODER_NAME)
            .build();
        fail("Creating command with only one principal-decoder should throw exception");
    }

    private void checkAggregatePrincipalDecoderAttribute(String attr, List<String> expected) throws IOException {
        checkAttribute(TEST_AGGREGATE_PRINCIPAL_DECODER_ADDRESS, attr, expected);
    }

}


text:
<?php

namespace Magento\Framework\Search\Request\Config;

class FileSystemReaderTest extends \PHPUnit_Framework_TestCase
{
    /** @var  FilesystemReader */
    protected $object;

    protected function setUp()
    {
        $fileResolver = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
            '\Magento\Framework\Search\Request\Config\FileResolverStub'
        );
        $this->object = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
            '\Magento\Framework\Search\Request\Config\FilesystemReader',
            ['fileResolver' => $fileResolver]
        );
    }

    public function testRead()
    {
        $result = $this->object->read();
        // Filter values added by \Magento\CatalogSearch\Model\Search\ReaderPlugin
        $result = array_intersect_key($result, array_flip(['bool_query', 'filter_query', 'new_match_query']));
        $expected = include __DIR__ . '/../../_files/search_request_merged.php';
        $this->assertEquals($expected, $result);
    }
}


text:
package org.apache.spark.sql.kafka010

import java.{util => ju}

import org.apache.kafka.clients.producer.{Callback, KafkaProducer, ProducerRecord, RecordMetadata}

import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.{Attribute, Cast, Literal, UnsafeProjection}
import org.apache.spark.sql.types.{BinaryType, StringType}

/**
 * Writes out data in a single Spark task, without any concerns about how
 * to commit or abort tasks. Exceptions thrown by the implementation of this class will
 * automatically trigger task aborts.
 */
private[kafka010] class KafkaWriteTask(
    producerConfiguration: ju.Map[String, Object],
    inputSchema: Seq[Attribute],
    topic: Option[String]) extends KafkaRowWriter(inputSchema, topic) {
  // used to synchronize with Kafka callbacks
  private var producer: KafkaProducer[Array[Byte], Array[Byte]] = _

  /**
   * Writes key value data out to topics.
   */
  def execute(iterator: Iterator[InternalRow]): Unit = {
    producer = CachedKafkaProducer.getOrCreate(producerConfiguration)
    while (iterator.hasNext && failedWrite == null) {
      val currentRow = iterator.next()
      sendRow(currentRow, producer)
    }
  }

  def close(): Unit = {
    checkForErrors()
    if (producer != null) {
      producer.flush()
      checkForErrors()
      producer = null
    }
  }
}

private[kafka010] abstract class KafkaRowWriter(
    inputSchema: Seq[Attribute], topic: Option[String]) {

  // used to synchronize with Kafka callbacks
  @volatile protected var failedWrite: Exception = _
  protected val projection = createProjection

  private val callback = new Callback() {
    override def onCompletion(recordMetadata: RecordMetadata, e: Exception): Unit = {
      if (failedWrite == null && e != null) {
        failedWrite = e
      }
    }
  }

  /**
   * Send the specified row to the producer, with a callback that will save any exception
   * to failedWrite. Note that send is asynchronous; subclasses must flush() their producer before
   * assuming the row is in Kafka.
   */
  protected def sendRow(
      row: InternalRow, producer: KafkaProducer[Array[Byte], Array[Byte]]): Unit = {
    val projectedRow = projection(row)
    val topic = projectedRow.getUTF8String(0)
    val key = projectedRow.getBinary(1)
    val value = projectedRow.getBinary(2)
    if (topic == null) {
      throw new NullPointerException(s"null topic present in the data. Use the " +
        s"${KafkaSourceProvider.TOPIC_OPTION_KEY} option for setting a default topic.")
    }
    val record = new ProducerRecord[Array[Byte], Array[Byte]](topic.toString, key, value)
    producer.send(record, callback)
  }

  protected def checkForErrors(): Unit = {
    if (failedWrite != null) {
      throw failedWrite
    }
  }

  private def createProjection = {
    val topicExpression = topic.map(Literal(_)).orElse {
      inputSchema.find(_.name == KafkaWriter.TOPIC_ATTRIBUTE_NAME)
    }.getOrElse {
      throw new IllegalStateException(s"topic option required when no " +
        s"'${KafkaWriter.TOPIC_ATTRIBUTE_NAME}' attribute is present")
    }
    topicExpression.dataType match {
      case StringType => // good
      case t =>
        throw new IllegalStateException(s"${KafkaWriter.TOPIC_ATTRIBUTE_NAME} " +
          s"attribute unsupported type $t. ${KafkaWriter.TOPIC_ATTRIBUTE_NAME} " +
          "must be a StringType")
    }
    val keyExpression = inputSchema.find(_.name == KafkaWriter.KEY_ATTRIBUTE_NAME)
      .getOrElse(Literal(null, BinaryType))
    keyExpression.dataType match {
      case StringType | BinaryType => // good
      case t =>
        throw new IllegalStateException(s"${KafkaWriter.KEY_ATTRIBUTE_NAME} " +
          s"attribute unsupported type $t")
    }
    val valueExpression = inputSchema
      .find(_.name == KafkaWriter.VALUE_ATTRIBUTE_NAME).getOrElse(
      throw new IllegalStateException("Required attribute " +
        s"'${KafkaWriter.VALUE_ATTRIBUTE_NAME}' not found")
    )
    valueExpression.dataType match {
      case StringType | BinaryType => // good
      case t =>
        throw new IllegalStateException(s"${KafkaWriter.VALUE_ATTRIBUTE_NAME} " +
          s"attribute unsupported type $t")
    }
    UnsafeProjection.create(
      Seq(topicExpression, Cast(keyExpression, BinaryType),
        Cast(valueExpression, BinaryType)), inputSchema)
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~  Copyright 1999-2019 Seata.io Group.
  ~
  ~  Licensed under the Apache License, Version 2.0 (the "License");
  ~  you may not use this file except in compliance with the License.
  ~  You may obtain a copy of the License at
  ~
  ~       http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~  Unless required by applicable law or agreed to in writing, software
  ~  distributed under the License is distributed on an "AS IS" BASIS,
  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~  See the License for the specific language governing permissions and
  ~  limitations under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>io.seata</groupId>
        <artifactId>seata-parent</artifactId>
        <version>${revision}</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>seata-spring</artifactId>
    <packaging>jar</packaging>
    <name>seata-spring ${project.version}</name>
    <description>spring for Seata built with Maven</description>

    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>seata-tm</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>seata-rm-datasource</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>seata-tcc</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>seata-rm</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>seata-serializer-all</artifactId>
            <version>${project.version}</version>
        </dependency>

        <!-- spring  -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.jetbrains.kotlinx</groupId>
            <artifactId>kotlinx-coroutines-core</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin-maven-plugin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>process-sources</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
"""
This is an example dag for using `ImapAttachmentToS3Operator` to transfer an email attachment via IMAP
protocol from a mail server to S3 Bucket.
"""

from datetime import datetime
from os import getenv

from airflow import DAG
from airflow.providers.amazon.aws.transfers.imap_attachment_to_s3 import ImapAttachmentToS3Operator

IMAP_ATTACHMENT_NAME = getenv("IMAP_ATTACHMENT_NAME", "test.txt")
IMAP_MAIL_FOLDER = getenv("IMAP_MAIL_FOLDER", "INBOX")
IMAP_MAIL_FILTER = getenv("IMAP_MAIL_FILTER", "All")
S3_BUCKET = getenv("S3_BUCKET", "test-bucket")
S3_KEY = getenv("S3_KEY", "key")

with DAG(
    dag_id="example_imap_attachment_to_s3",
    start_date=datetime(2021, 1, 1),
    schedule_interval=None,
    catchup=False,
    tags=['example'],
) as dag:
    # [START howto_transfer_imap_attachment_to_s3]
    task_transfer_imap_attachment_to_s3 = ImapAttachmentToS3Operator(
        task_id='transfer_imap_attachment_to_s3',
        imap_attachment_name=IMAP_ATTACHMENT_NAME,
        s3_bucket=S3_BUCKET,
        s3_key=S3_KEY,
        imap_mail_folder=IMAP_MAIL_FOLDER,
        imap_mail_filter=IMAP_MAIL_FILTER,
    )
    # [END howto_transfer_imap_attachment_to_s3]


text:
<?php
class Test_Widget_Dashboard extends WP_Widget {

	public function __construct(){
		add_action('wp_dashboard_setup', array($this, 'widget'));
	}

	public function widget(){
		wp_add_dashboard_widget('test_widget_dashboard', 'My Widget', array($this, 'display'));
	}

	public function display(){
		echo '
Ðây là Widget Dashboard
';
	}

}


text:
package ipv6

type sysICMPv6Filter struct {
}

func (f *sysICMPv6Filter) accept(typ ICMPType) {
}

func (f *sysICMPv6Filter) block(typ ICMPType) {
}

func (f *sysICMPv6Filter) setAll(block bool) {
}

func (f *sysICMPv6Filter) willBlock(typ ICMPType) bool {
	return false
}


text:
package org.apache.hadoop.io.compress.zlib;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.compress.Compressor;
import org.apache.hadoop.io.compress.Decompressor;
import org.apache.hadoop.util.NativeCodeLoader;

/**
 * A collection of factories to create the right
 * zlib/gzip compressor/decompressor instances.
 *
 */
public class ZlibFactory {
  private static final Log LOG =
    LogFactory.getLog(ZlibFactory.class);

  private static boolean nativeZlibLoaded = false;

  static {
    if (NativeCodeLoader.isNativeCodeLoaded()) {
      nativeZlibLoaded = ZlibCompressor.isNativeZlibLoaded() &&
        ZlibDecompressor.isNativeZlibLoaded();

      if (nativeZlibLoaded) {
        LOG.info("Successfully loaded & initialized native-zlib library");
      } else {
        LOG.warn("Failed to load/initialize native-zlib library");
      }
    }
  }

  /**
   * Check if native-zlib code is loaded & initialized correctly and
   * can be loaded for this job.
   *
   * @param conf configuration
   * @return true if native-zlib is loaded & initialized
   *         and can be loaded for this job, else false
   */
  public static boolean isNativeZlibLoaded(Configuration conf) {
    return nativeZlibLoaded && conf.getBoolean("hadoop.native.lib", true);
  }

  /**
   * Return the appropriate type of the zlib compressor.
   *
   * @param conf configuration
   * @return the appropriate type of the zlib compressor.
   */
  public static Class<? extends Compressor>
  getZlibCompressorType(Configuration conf) {
    return (isNativeZlibLoaded(conf)) ?
            ZlibCompressor.class : BuiltInZlibDeflater.class;
  }

  /**
   * Return the appropriate implementation of the zlib compressor.
   *
   * @param conf configuration
   * @return the appropriate implementation of the zlib compressor.
   */
  public static Compressor getZlibCompressor(Configuration conf) {
    return (isNativeZlibLoaded(conf)) ?
      new ZlibCompressor() : new BuiltInZlibDeflater();
  }

  /**
   * Return the appropriate type of the zlib decompressor.
   *
   * @param conf configuration
   * @return the appropriate type of the zlib decompressor.
   */
  public static Class<? extends Decompressor>
  getZlibDecompressorType(Configuration conf) {
    return (isNativeZlibLoaded(conf)) ?
            ZlibDecompressor.class : BuiltInZlibInflater.class;
  }

  /**
   * Return the appropriate implementation of the zlib decompressor.
   *
   * @param conf configuration
   * @return the appropriate implementation of the zlib decompressor.
   */
  public static Decompressor getZlibDecompressor(Configuration conf) {
    return (isNativeZlibLoaded(conf)) ?
      new ZlibDecompressor() : new BuiltInZlibInflater();
  }

}


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

namespace PhoneNumbers
{
    /**
    * A utility which knows the data files that are available for the geocoder to use. The data files
    * contain mappings from phone number prefixes to text descriptions, and are organized by country
    * calling code and language that the text descriptions are in.
    *
    * @author Shaopeng Jia
    */
    public class MappingFileProvider
    {
        private int numOfEntries = 0;
        private int[] countryCallingCodes;
        private List<HashSet<String>> availableLanguages;
        private static readonly Dictionary<String, String> LOCALE_NORMALIZATION_MAP;

        static MappingFileProvider()
        {
            var normalizationMap = new Dictionary<String, String>();
            normalizationMap["zh_TW"] = "zh_Hant";
            normalizationMap["zh_HK"] = "zh_Hant";
            normalizationMap["zh_MO"] = "zh_Hant";
            LOCALE_NORMALIZATION_MAP = normalizationMap;
        }

        /**
        * Creates an empty {@link MappingFileProvider}. The default constructor is necessary for
        * implementing {@link Externalizable}. The empty provider could later be populated by
        * {@link #readFileConfigs(java.util.SortedMap)} or {@link #readExternal(java.io.ObjectInput)}.
        */
        public MappingFileProvider()
        {
        }

        /**
         * Initializes an {@link MappingFileProvider} with {@code availableDataFiles}.
         *
         * @param availableDataFiles  a map from country calling codes to sets of languages in which data
         *     files are available for the specific country calling code. The map is sorted in ascending
         *     order of the country calling codes as integers.
         */
        public void ReadFileConfigs(SortedDictionary<int, HashSet<String>> availableDataFiles)
        {
            numOfEntries = availableDataFiles.Count;
            countryCallingCodes = new int[numOfEntries];
            availableLanguages = new List<HashSet<String>>(numOfEntries);
            int index = 0;
            foreach (int countryCallingCode in availableDataFiles.Keys)
            {
                countryCallingCodes[index++] = countryCallingCode;
                availableLanguages.Add(new HashSet<String>(availableDataFiles[countryCallingCode]));
            }
        }

        /**
         * Returns a string representing the data in this class. The string contains one line for each
         * country calling code. The country calling code is followed by a '|' and then a list of
         * comma-separated languages sorted in ascending order.
         */
        public override String ToString()
        {
            StringBuilder output = new StringBuilder();
            for (int i = 0; i < numOfEntries; i++)
            {
                output.Append(countryCallingCodes[i]);
                output.Append('|');
                foreach (var lang in availableLanguages[i].OrderBy(a => a))
                {
                    output.Append(lang);
                    output.Append(',');
                }
                output.Append('\n');
            }
            return output.ToString();
        }

        /**
         * Gets the name of the file that contains the mapping data for the {@code countryCallingCode} in
         * the language specified.
         *
         * @param countryCallingCode  the country calling code of phone numbers which the data file
         *     contains
         * @param language  two-letter lowercase ISO language codes as defined by ISO 639-1
         * @param script  four-letter titlecase (the first letter is uppercase and the rest of the letters
         *     are lowercase) ISO script codes as defined in ISO 15924
         * @param region  two-letter uppercase ISO country codes as defined by ISO 3166-1
         * @return  the name of the file, or empty string if no such file can be found
         */
        public String GetFileName(int countryCallingCode, String language, String script, String region)
        {
            if (language.Length == 0)
            {
                return "";
            }
            int index = Array.BinarySearch(countryCallingCodes, countryCallingCode);
            if (index < 0)
            {
                return "";
            }
            var setOfLangs = availableLanguages[index];
            if (setOfLangs.Count > 0)
            {
                String languageCode = FindBestMatchingLanguageCode(setOfLangs, language, script, region);
                if (languageCode.Length > 0)
                {
                    StringBuilder fileName = new StringBuilder();
                    fileName.Append(countryCallingCode).Append('_').Append(languageCode);
                    return fileName.ToString();
                }
            }
            return "";
        }

        private String FindBestMatchingLanguageCode(
            HashSet<String> setOfLangs, String language, String script, String region)
        {
            StringBuilder fullLocale = ConstructFullLocale(language, script, region);
            String fullLocaleStr = fullLocale.ToString();
            String normalizedLocale;
            if (LOCALE_NORMALIZATION_MAP.TryGetValue(fullLocaleStr, out normalizedLocale))
            {
                if (setOfLangs.Contains(normalizedLocale))
                {
                    return normalizedLocale;
                }
            }
            if (setOfLangs.Contains(fullLocaleStr))
            {
                return fullLocaleStr;
            }

            if (OnlyOneOfScriptOrRegionIsEmpty(script, region))
            {
                if (setOfLangs.Contains(language))
                {
                    return language;
                }
            }
            else if (script.Length > 0 && region.Length > 0)
            {
                StringBuilder langWithScript = new StringBuilder(language).Append('_').Append(script);
                String langWithScriptStr = langWithScript.ToString();
                if (setOfLangs.Contains(langWithScriptStr))
                {
                    return langWithScriptStr;
                }

                StringBuilder langWithRegion = new StringBuilder(language).Append('_').Append(region);
                String langWithRegionStr = langWithRegion.ToString();
                if (setOfLangs.Contains(langWithRegionStr))
                {
                    return langWithRegionStr;
                }

                if (setOfLangs.Contains(language))
                {
                    return language;
                }
            }
            return "";
        }

        private bool OnlyOneOfScriptOrRegionIsEmpty(String script, String region)
        {
            return (script.Length == 0 && region.Length > 0) ||
                    (region.Length == 0 && script.Length > 0);
        }

        private StringBuilder ConstructFullLocale(String language, String script, String region)
        {
            StringBuilder fullLocale = new StringBuilder(language);
            AppendSubsequentLocalePart(script, fullLocale);
            AppendSubsequentLocalePart(region, fullLocale);
            return fullLocale;
        }

        private void AppendSubsequentLocalePart(String subsequentLocalePart, StringBuilder fullLocale)
        {
            if (subsequentLocalePart.Length > 0)
            {
                fullLocale.Append('_').Append(subsequentLocalePart);
            }
        }
    }
}


text:
if(WIN32) # The only platform it makes sense to check for DirectX SDK
  include(FindPkgMacros)
  findpkg_begin(DirectX)

  # Get path, convert backslashes as ${ENV_DXSDK_DIR}
  getenv_path(DXSDK_DIR)
  getenv_path(DIRECTX_HOME)
  getenv_path(DIRECTX_ROOT)
  getenv_path(DIRECTX_BASE)

  # construct search paths
  set(DirectX_PREFIX_PATH
    "${DXSDK_DIR}" "${ENV_DXSDK_DIR}"
    "${DIRECTX_HOME}" "${ENV_DIRECTX_HOME}"
    "${DIRECTX_ROOT}" "${ENV_DIRECTX_ROOT}"
    "${DIRECTX_BASE}" "${ENV_DIRECTX_BASE}"
    "C:/apps_x86/Microsoft DirectX SDK*"
    "C:/Program Files (x86)/Microsoft DirectX SDK*"
    "C:/apps/Microsoft DirectX SDK*"
    "C:/Program Files/Microsoft DirectX SDK*"
	"$ENV{ProgramFiles}/Microsoft DirectX SDK*"
  )
  create_search_paths(DirectX)
  # redo search if prefix path changed
  clear_if_changed(DirectX_PREFIX_PATH
    DirectX_LIBRARY
	DirectX_INCLUDE_DIR
  )

  find_path(DirectX_INCLUDE_DIR NAMES d3d9.h HINTS ${DirectX_INC_SEARCH_PATH})
  # dlls are in DirectX_ROOT_DIR/Developer Runtime/x64|x86
  # lib files are in DirectX_ROOT_DIR/Lib/x64|x86
  if(CMAKE_CL_64)
    set(DirectX_LIBPATH_SUFFIX "x64")
  else(CMAKE_CL_64)
    set(DirectX_LIBPATH_SUFFIX "x86")
  endif(CMAKE_CL_64)
  find_library(DirectX_LIBRARY NAMES d3d9 HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})
  find_library(DirectX_D3DX9_LIBRARY NAMES d3dx9 HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})
  find_library(DirectX_DXERR_LIBRARY NAMES DxErr HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})
  find_library(DirectX_DXGUID_LIBRARY NAMES dxguid HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})

  # look for dxgi (needed by both 10 and 11)
  find_library(DirectX_DXGI_LIBRARY NAMES dxgi HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})

  # look for d3dcompiler (needed by 11)
  find_library(DirectX_D3DCOMPILER_LIBRARY NAMES d3dcompiler HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})

  findpkg_finish(DirectX)
  set(DirectX_LIBRARIES ${DirectX_LIBRARIES}
    ${DirectX_D3DX9_LIBRARY}
    ${DirectX_DXERR_LIBRARY}
    ${DirectX_DXGUID_LIBRARY}
  )

  mark_as_advanced(DirectX_D3DX9_LIBRARY DirectX_DXERR_LIBRARY DirectX_DXGUID_LIBRARY
    DirectX_DXGI_LIBRARY DirectX_D3DCOMPILER_LIBRARY)

  # look for D3D11 components
  if (DirectX_FOUND)
    find_path(DirectX_D3D11_INCLUDE_DIR NAMES D3D11Shader.h HINTS ${DirectX_INC_SEARCH_PATH})
	get_filename_component(DirectX_LIBRARY_DIR "${DirectX_LIBRARY}" PATH)
	message(STATUS "DX lib dir: ${DirectX_LIBRARY_DIR}")
    find_library(DirectX_D3D11_LIBRARY NAMES d3d11 HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})
    find_library(DirectX_D3DX11_LIBRARY NAMES d3dx11 HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})
	if (DirectX_D3D11_INCLUDE_DIR AND DirectX_D3D11_LIBRARY)
	  set(DirectX_D3D11_FOUND TRUE)
	  set(DirectX_D3D11_INCLUDE_DIR ${DirectX_D3D11_INCLUDE_DIR})
	  set(DirectX_D3D11_LIBRARIES ${DirectX_D3D11_LIBRARIES}
	    ${DirectX_D3D11_LIBRARY}
	    ${DirectX_D3DX11_LIBRARY}
	    ${DirectX_DXGI_LIBRARY}
        ${DirectX_DXERR_LIBRARY}
        ${DirectX_DXGUID_LIBRARY}
        ${DirectX_D3DCOMPILER_LIBRARY}
      )
    endif ()
	mark_as_advanced(DirectX_D3D11_INCLUDE_DIR DirectX_D3D11_LIBRARY DirectX_D3DX11_LIBRARY)
  endif ()

endif(WIN32)


text:
        Hoiio AppID is required to call Hoiio API. You can get this by following these steps:

Go to developer.hoiio.com and register a Hoiio Developer account

Login to Developer portal

After creating an App, click on "View Keys" to retrieve the appId


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>General questions about the library — Frequently Asked Questions</title>

    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/logo.ico"/>
    <link rel="top" title="Frequently Asked Questions" href="../index.html" />
    <link rel="next" title="General questions about the CP solver" href="CPsolver.html" />
    <link rel="prev" title="General questions about the installation and the compilation of the library" href="installation.html" />

Navigation

          next

          previous |

FAQ »

General questions about the library

When was the library released?

What is the license you use?

Is it really free and open source?

What guarantees do you provide on the quality of this library?

In what language(s) is the library coded?

What are the supported languages?

What are the supported platforms?

Do you use this library at Google?

What is the future of this library?

What new technologies do you plan to release in the future?

Why did Google, a private company, open source such a project?

When was the library released?

It was released as an open project in September 2010.

What is the license you use?

Apache License 2.0

Is it really free and open source?

As long as you comply with the license.

What guarantees do you provide on the quality of this library?

None. We use it internally at Google and we are happy with it.

In what language(s) is the library coded?

The library itself is coded in C++.

What are the supported languages?

Through SWIG, the library is available in

Python,

Java,

and .NET (using mono on non windows platforms).

What are the supported platforms?

The code is known to compile on:

gcc 4.7.x and above on Ubuntu 12.04 and up (12.04, 12.10, 13.04, 13.10)

XCode >= 5.0 (clang++ with C++11 support)

Microsoft Visual Studio 2012 and 2013 (2010 is not supported as it lacks support for C++11)

Both 32-bit and 64-bit architectures are supported, although the code is optimized to run in 64-bit mode.

Do you use this library at Google?

Yes! The code we have released is a subset of all the OR tools we are
developing at Google. This code is used internally. We will maintain
this open-source branch in sync with our internal code and will likely
contribute more tools, more technology.

What is the future of this library?

Of course, we don’t have a crystal ball to see into the future
and we don’t know what might happen but as far as we are concerned our intentions are clear:
this library will remain actively developed and open sourced.

What new technologies do you plan to release in the future?

While we have a clear idea about the tools we would like to add (or already have implemented in our internal version of the library)
we don’t want to commit publicly. We develop the library primarily for our internal needs and offer parts of our code along the way.
If you have followed this project since its open source release, you know that it is under active development. We don’t plan to change
this.

Why did Google, a private company, open source such a project?

We would like to make contacts with the academic community and benefit from mutual and productive exchanges.

Google or-tools
open source library

Frequently Asked Questions

Google search

<form method="get" action="http://www.google.com/search">

<input type="text"   name="q" size="25"
 maxlength="255" value="" />
<input type="submit" value="Go" />

Search:
<select name="sitesearch" width="125" style="width: 125px">
<option value="http://or-tools.googlecode.com/svn/trunk/documentation/user_manual/">user's manual</option>
<option value="http://or-tools.googlecode.com/svn/trunk/documentation/faq/" selected>faq</option>
<option value="http://or-tools.googlecode.com/svn/trunk/documentation/reference_manual/or-tools/">reference manual</option>
<option value="http://or-tools.googlecode.com/svn/trunk/documentation/">All or-tools doc</option>
</select>

</form>

Welcome

The or-tools open source library

Documentation's hub

Back to main page

Tutorial examples

C++

Python

Java

C#

General questions about:

the documentation

the installation and compilation

the library

the CP Solver

the CP Routing Solver

the Local Search algorithm

Navigation

          next

          previous |

FAQ »

        © Copyright 2012-2014, Google.
      Created using Sphinx 1.1.3.


text:
<?xml version="1.0" encoding="utf-8"?>
<ImageView
        xmlns:android="http://schemas.android.com/apk/res/android"
        style="@style/divider"
        android:id="@+id/divider"
        android:src="@android:drawable/divider_horizontal_dim_dark"/>


text:
package com.node.eduoa.utils;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ser.FilterProvider;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
/**
 * jackson一些转换方法
 *

 *  Jacksons.json().setDateFormate();
 *

 * @author zxh
 * @date 2012-7-25 下午11:36:33
 */
public class Jacksons {

    private ObjectMapper objectMapper;
	/** 格式化时间的string */
	private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static Jacksons json() {
        return new Jacksons();
    }

    /**
     * 构造方法
     */
    private Jacksons() {
        objectMapper =  JacksonMapper.getInstance();
    }

    /**
     * 过滤属性
     *

     * 使用方法:先给ObjectMapper添加一个filter,然后还要在需要过滤的类上加@JsonFilter("filterName")注解。
	 *	比如说要过滤User 上的name属性,先
	 *	Jacksons.json().filter("myFilter", "name").readAsString(user),具体看Jacksons代码。并在User类上加@JsonFilter("myFilter")。
	 *	有点不爽的是如果用另外一个没有添加该filter的ObjectMapper解析的话会报错。
	 *	如果这个User类已经添加了@JsonFilter("myFilter")注解,但在另外一个地方又要解析它并不想过滤name 属性,那只能是
	 *		Jacksons.json().filter("myFilter", ""),然后在读出来。
	 *

     * @param filterName 过滤器的名称
     * @param properties  要过滤的字段名称
     * @return
     */
    public Jacksons filter(String filterName, String... properties) {
        FilterProvider filterProvider = new SimpleFilterProvider().addFilter(filterName,
                SimpleBeanPropertyFilter.serializeAllExcept(properties));
//        objectMapper.setFilters(filterProvider);

        return this;
    }

    /**
     * 混入注解
     *

     * 使用方法:
     *  先定义一个接口或类, 在该类上添加@JsonIgnoreProperties("name"), 然后在ObjectMapper的配置项上添加混入注解
	 *		@JsonIgnoreProperties("name")
	 *		public interface MixInUser {
	 *
	 *		}
	 * 使用:
     * String mixInUser = Jacksons.json()
     * 			.addMixInAnnotations(User.class, MixInUser.class)
     * 			.readAsString(user);

     *

     * @param target 目标对象的class
     * @param mixinSource  接口或类
     * @return
     */
    public Jacksons addMixInAnnotations(Class<?> target, Class<?> mixinSource) {
        objectMapper.getSerializationConfig().addMixInAnnotations(target, mixinSource);
        objectMapper.getDeserializationConfig().addMixInAnnotations(target, mixinSource);
        return this;
    }

    /**
     * 设置日期格式
     * @param dateFormat
     * 		自定义的日期/时间格式。该属性的值遵循java标准的date/time格式规范。如:yyyy-MM-dd
     * @return
     */
    public Jacksons setDateFormate(String dateFormat) {
        objectMapper.getDeserializationConfig().setDateFormat(new SimpleDateFormat(dateFormat));
        objectMapper.getSerializationConfig().setDateFormat(new SimpleDateFormat(dateFormat));
        return this;
    }

    /**
     * 设置默认的日期
     * @return
     */
    public Jacksons setDateFormate() {
        objectMapper.getSerializationConfig().setDateFormat(new SimpleDateFormat(DATE_TIME_FORMAT));
        objectMapper.getDeserializationConfig().setDateFormat(new SimpleDateFormat(DATE_TIME_FORMAT));

        return this;
    }

    /**
     * json转换为java对象
     * @param json  字符串
     * @param clazz  对象的class
     * @return  返回对象
     */
    public <T> T fromJsonToObject(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析json错误");
        }
    }

    /**
     * java对象转换为json字符串
     * @param object java对象
     * @return json字符串
     */
    public String fromObjectToJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析对象错误");
        }
    }

    /**
     * Json转List
     * @param json json字符串
     * @return  list
     */
    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> fromJsonToList(String json) {
        try {
            return objectMapper.readValue(json, List.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析json错误");
        }
    }

    public static void main(String[] args) {
		Jacksons.json().setDateFormate();
		//Jacksons.json().
	}
}


text:
package com.google.api.ads.dfp.jaxws.v201502;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for GrpUnitType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="GrpUnitType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="UNKNOWN"/>
 *     <enumeration value="IMPRESSIONS"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "GrpUnitType")
@XmlEnum
public enum GrpUnitType {

    /**
     *
     *                 The value returned if the actual value is not exposed by the requested API version.
     *
     *
     */
    UNKNOWN,
    IMPRESSIONS;

    public String value() {
        return name();
    }

    public static GrpUnitType fromValue(String v) {
        return valueOf(v);
    }

}