text:
from mock import patch
from unittests.common import *

from oss2.models import SimplifiedBucketInfo, SimplifiedObjectInfo, Owner
from oss2 import to_string

class TestIterator(OssTestCase):
    def assertInstanceEqual(self, a, b):
        adict = vars(a)
        bdict = vars(b)

        for k, v in adict.items():
            self.assertEqual(adict[k], bdict[k])

    def assertSimpleObjectInfoEqual(self, a, b):
        self.assertEqual(a.key, b.key)
        self.assertEqual(a.last_modified, b.last_modified)
        self.assertEqual(a.etag, b.etag)
        self.assertEqual(a.type, b.type)
        self.assertEqual(a.size, b.size)
        self.assertEqual(a.storage_class, b.storage_class)
        if a.owner is None:
            self.assertIsNone(b.owner)
        else:
            self.assertEqual(a.owner.display_name, b.owner.display_name)
            self.assertEqual(a.owner.id, b.owner.id)

    @patch('oss2.Session.do_request')
    def test_bucket_iterator_not_truncated(self, do_request):
        body_list = [b'''<?xml version="1.0" encoding="UTF-8"?>
        <ListAllMyBucketsResult>
          <Owner>
            <ID>1047205513514293</ID>
            <DisplayName>1047205513514293</DisplayName>
          </Owner>
          <Buckets>
            <Bucket>
              <CreationDate>2015-12-12T00:35:31.000Z</CreationDate>
              <ExtranetEndpoint>oss-cn-hangzhou.aliyuncs.com</ExtranetEndpoint>
              <IntranetEndpoint>oss-cn-hangzhou-internal.aliyuncs.com</IntranetEndpoint>
              <Location>oss-cn-hangzhou</Location>
              <Name>bucket-1</Name>
              <StorageClass>Standard</StorageClass>
            </Bucket>
            <Bucket>
              <CreationDate>2015-12-11T09:01:57.000Z</CreationDate>
              <ExtranetEndpoint>oss-us-west-1.aliyuncs.com</ExtranetEndpoint>
              <IntranetEndpoint>oss-us-west-internal-1.aliyuncs.com</IntranetEndpoint>
              <Location>oss-us-west-1</Location>
              <Name>bucket-2</Name>
              <StorageClass>Standard</StorageClass>
            </Bucket>
          </Buckets>
        </ListAllMyBucketsResult>
        ''']

        req_info = RequestInfo()

        do_request.auto_spec = True
        do_request.side_effect = make_do4body(req_infos=[req_info], body_list=body_list)

        expected = [SimplifiedBucketInfo('bucket-1', 'oss-cn-hangzhou', 1449880531, 'oss-cn-hangzhou.aliyuncs.com',
                                         'oss-cn-hangzhou-internal.aliyuncs.com', 'Standard'),
                    SimplifiedBucketInfo('bucket-2', 'oss-us-west-1', 1449824517, 'oss-us-west-1.aliyuncs.com',
                                         'oss-us-west-internal-1.aliyuncs.com', 'Standard')]

        got = list(oss2.BucketIterator(service()))

        self.assertEqual(len(expected), len(got))
        self.assertInstanceEqual(expected[0], got[0])
        self.assertInstanceEqual(expected[1], got[1])

        self.assertEqual(req_info.req.params.get('prefix', ''), '')
        self.assertEqual(req_info.req.params.get('marker', ''), '')

    @patch('oss2.Session.do_request')
    def test_bucket_iterator_truncated(self, do_request):
        body_list = [b'''<?xml version="1.0" encoding="UTF-8"?>
        <ListAllMyBucketsResult>
          <Owner>
            <ID>1047205513514293</ID>
            <DisplayName>1047205513514293</DisplayName>
          </Owner>
          <Buckets>
            <Bucket>
              <CreationDate>2015-12-23T07:08:55.000Z</CreationDate>
              <ExtranetEndpoint>oss-cn-beijing.aliyuncs.com</ExtranetEndpoint>
              <IntranetEndpoint>oss-cn-beijing-internal.aliyuncs.com</IntranetEndpoint>
              <Location>oss-cn-beijing</Location>
              <Name>ming-bj</Name>
              <StorageClass>Standard</StorageClass>
            </Bucket>
            <Bucket>
              <CreationDate>2014-09-06T13:20:33.000Z</CreationDate>
              <ExtranetEndpoint>oss-cn-hangzhou.aliyuncs.com</ExtranetEndpoint>
              <IntranetEndpoint>oss-cn-hangzhou-internal.aliyuncs.com</IntranetEndpoint>
              <Location>oss-cn-hangzhou</Location>
              <Name>ming-oss-share</Name>
              <StorageClass>Standard</StorageClass>
            </Bucket>
          </Buckets>
          <Prefix></Prefix>
          <Marker></Marker>
          <MaxKeys>1</MaxKeys>
          <IsTruncated>true</IsTruncated>
          <NextMarker>ming-oss-share</NextMarker>
        </ListAllMyBucketsResult>''',

        b'''<?xml version="1.0" encoding="UTF-8"?>
        <ListAllMyBucketsResult>
          <Owner>
            <ID>1047205513514293</ID>
            <DisplayName>1047205513514293</DisplayName>
          </Owner>
          <Buckets>
            <Bucket>
              <CreationDate>2015-12-25T04:22:43.000Z</CreationDate>
              <ExtranetEndpoint>oss-cn-qingdao.aliyuncs.com</ExtranetEndpoint>
              <IntranetEndpoint>oss-cn-qingdao-internal.aliyuncs.com</IntranetEndpoint>
              <Location>oss-cn-qingdao</Location>
              <Name>ming-qd</Name>
              <StorageClass>Standard</StorageClass>
            </Bucket>
            <Bucket>
              <CreationDate>2015-06-29T13:43:52.000Z</CreationDate>
              <ExtranetEndpoint>oss-cn-hangzhou.aliyuncs.com</ExtranetEndpoint>
              <IntranetEndpoint>oss-cn-hangzhou-internal.aliyuncs.com</IntranetEndpoint>
              <Location>oss-cn-hangzhou</Location>
              <Name>ming-spike</Name>
              <StorageClass>Standard</StorageClass>
            </Bucket>
          </Buckets>
          <Prefix></Prefix>
          <Marker>ming-oss-share</Marker>
          <MaxKeys>2</MaxKeys>
          <IsTruncated>true</IsTruncated>
          <NextMarker>ming-spike</NextMarker>
        </ListAllMyBucketsResult>''',

        b'''<?xml version="1.0" encoding="UTF-8"?>
        <ListAllMyBucketsResult>
          <Owner>
            <ID>1047205513514293</ID>
            <DisplayName>1047205513514293</DisplayName>
          </Owner>
          <Buckets>
            <Bucket>
              <CreationDate>2015-12-15T13:52:50.000Z</CreationDate>
              <ExtranetEndpoint>oss-cn-hangzhou.aliyuncs.com</ExtranetEndpoint>
              <IntranetEndpoint>oss-cn-hangzhou-internal.aliyuncs.com</IntranetEndpoint>
              <Location>oss-cn-hangzhou</Location>
              <Name>zzy-share</Name>
              <StorageClass>Standard</StorageClass>
            </Bucket>
          </Buckets>
        </ListAllMyBucketsResult>''']

        expected = [SimplifiedBucketInfo('ming-bj', 'oss-cn-beijing', 1450854535, 'oss-cn-beijing.aliyuncs.com',
                                         'oss-cn-beijing-internal.aliyuncs.com', 'Standard'),
                    SimplifiedBucketInfo('ming-oss-share', 'oss-cn-hangzhou', 1410009633, 'oss-cn-hangzhou.aliyuncs.com'
                                         , 'oss-cn-hangzhou-internal.aliyuncs.com', 'Standard'),
                    SimplifiedBucketInfo('ming-qd', 'oss-cn-qingdao', 1451017363, 'oss-cn-qingdao.aliyuncs.com',
                                         'oss-cn-qingdao-internal.aliyuncs.com', 'Standard'),
                    SimplifiedBucketInfo('ming-spike', 'oss-cn-hangzhou', 1435585432, 'oss-cn-hangzhou.aliyuncs.com'
                                         , 'oss-cn-hangzhou-internal.aliyuncs.com', 'Standard'),
                    SimplifiedBucketInfo('zzy-share', 'oss-cn-hangzhou',1450187570, 'oss-cn-hangzhou.aliyuncs.com'
                                         , 'oss-cn-hangzhou-internal.aliyuncs.com', 'Standard')]

        nreq = 3

        req_infos = [RequestInfo() for i in range(nreq)]

        do_request.auto_spec = True
        do_request.side_effect = make_do4body(req_infos=req_infos, body_list=body_list)

        got = list(oss2.BucketIterator(service(), max_keys=2))

        self.assertEqual(len(expected), len(got))

        for i in range(len(got)):
            self.assertInstanceEqual(expected[i], got[i])

        for i in range(nreq):
            self.assertEqual(req_infos[i].req.params.get('max-keys'), '2')
            self.assertEqual(req_infos[i].req.params.get('prefix', ''), '')

        self.assertEqual(req_infos[0].req.params.get('marker', ''), '')
        self.assertEqual(req_infos[1].req.params.get('marker', ''), 'ming-oss-share')
        self.assertEqual(req_infos[2].req.params.get('marker', ''), 'ming-spike')

    @patch('oss2.Session.do_request')
    def test_object_iterator_empty(self, do_request):
        body_list = [b'''<?xml version="1.0" encoding="UTF-8"?>
        <ListBucketResult>
          <Name>ming-bj</Name>
          <Prefix></Prefix>
          <Marker></Marker>
          <MaxKeys>1000</MaxKeys>
          <Delimiter></Delimiter>
          <EncodingType>url</EncodingType>
          <IsTruncated>false</IsTruncated>
        </ListBucketResult>''']

        do_request.auto_spec = True
        do_request.side_effect = make_do4body(body_list=body_list)

        got = list(oss2.ObjectIterator(bucket(), max_keys=1000))
        self.assertEqual(len(got), 0)

    @patch('oss2.Session.do_request')
    def test_object_iterator_not_truncated(self, do_request):
        body_list = [b'''<?xml version="1.0" encoding="UTF-8"?>
        <ListBucketResult>
          <Name>zzy-share</Name>
          <Prefix></Prefix>
          <Marker></Marker>
          <MaxKeys>1000</MaxKeys>
          <Delimiter></Delimiter>
          <IsTruncated>false</IsTruncated>
          <Contents>
            <Key>object-1</Key>
            <LastModified>2015-02-02T05:15:13.000Z</LastModified>
            <ETag>"716AF6FFD529DFEA856FAA4E12D2C5EA"</ETag>
            <Type>Normal</Type>
            <Size>4308</Size>
            <StorageClass>Standard</StorageClass>
            <Owner>
              <ID>1047205513514293</ID>
              <DisplayName>1047205513514293</DisplayName>
            </Owner>
          </Contents>
          <Contents>
            <Key>object-2</Key>
            <LastModified>2015-06-23T09:56:55.000Z</LastModified>
            <ETag>"333D74B47CB1B0E275D2AB3CDDA02665-26"</ETag>
            <Type>Multipart</Type>
            <Size>3389246</Size>
            <StorageClass>Standard</StorageClass>
            <Owner>
              <ID>1047205513514293</ID>
              <DisplayName>1047205513514293</DisplayName>
            </Owner>
          </Contents>
          <Contents>
            <Key>object-3</Key>
            <LastModified>2015-01-16T12:41:34.000Z</LastModified>
            <ETag>"B28F7255E6EA777DB0AFB1C58C2CFCFE"</ETag>
            <Type>Normal</Type>
            <Size>10718416</Size>
            <StorageClass>Standard</StorageClass>
            <Owner>
              <ID>1047205513514293</ID>
              <DisplayName>1047205513514293</DisplayName>
            </Owner>
          </Contents>
        </ListBucketResult>
        ''']

        req_info = RequestInfo()

        do_request.auto_spec = True
        do_request.side_effect = make_do4body(req_infos=[req_info], body_list=body_list)

        got = list(oss2.ObjectIterator(bucket(), max_keys=1000))

        expected = [SimplifiedObjectInfo('object-1', 1422854113, '716AF6FFD529DFEA856FAA4E12D2C5EA', 'Normal',
                                         4308, 'Standard', Owner('1047205513514293', '1047205513514293')),
                    SimplifiedObjectInfo('object-2', 1435053415, '333D74B47CB1B0E275D2AB3CDDA02665-26', 'Multipart',
                                         3389246, 'Standard', Owner('1047205513514293', '1047205513514293')),
                    SimplifiedObjectInfo('object-3', 1421412094, 'B28F7255E6EA777DB0AFB1C58C2CFCFE', 'Normal',
                                         10718416, 'Standard', Owner('1047205513514293', '1047205513514293'))]

        self.assertEqual(len(expected), len(got))

        for i in range(len(expected)):
            self.assertSimpleObjectInfoEqual(expected[i], got[i])

        self.assertEqual(req_info.req.params.get('prefix', ''), '')
        self.assertEqual(req_info.req.params.get('marker', ''), '')
        self.assertEqual(req_info.req.params.get('encoding-type'), 'url')

    @patch('oss2.Session.do_request')
    def test_object_iterator_truncated(self, do_request):
        body_list = [b'''<?xml version="1.0" encoding="UTF-8"?>
        <ListBucketResult>
          <Name>ming-spike</Name>
          <Prefix></Prefix>
          <Marker></Marker>
          <MaxKeys>1</MaxKeys>
          <Delimiter></Delimiter>
          <EncodingType>url</EncodingType>
          <IsTruncated>true</IsTruncated>
          <NextMarker>a.txt</NextMarker>
          <Contents>
            <Key>a.txt</Key>
            <LastModified>2016-01-07T11:10:00.000Z</LastModified>
            <ETag>"5EB63BBBE01EEED093CB22BB8F5ACDC3"</ETag>
            <Type>Normal</Type>
            <Size>11</Size>
            <StorageClass>Standard</StorageClass>
            <Owner>
              <ID>1047205513514293</ID>
              <DisplayName>1047205513514293</DisplayName>
            </Owner>
          </Contents>
        </ListBucketResult>''',
        b'''<?xml version="1.0" encoding="UTF-8"?>
        <ListBucketResult>
          <Name>ming-spike</Name>
          <Prefix></Prefix>
          <Marker>a.txt</Marker>
          <MaxKeys>1</MaxKeys>
          <Delimiter></Delimiter>
          <EncodingType>url</EncodingType>
          <IsTruncated>true</IsTruncated>
          <NextMarker>%E4%B8%AD%E6%96%87.txt</NextMarker>
          <Contents>
            <Key>%E4%B8%AD%E6%96%87.txt</Key>
            <LastModified>2016-01-07T11:09:39.000Z</LastModified>
            <ETag>"FC3FF98E8C6A0D3087D515C0473F8677"</ETag>
            <Type>Normal</Type>
            <Size>12</Size>
            <StorageClass>Standard</StorageClass>
            <Owner>
              <ID>1047205513514293</ID>
              <DisplayName>1047205513514293</DisplayName>
            </Owner>
          </Contents>
        </ListBucketResult>''',
        b'''<?xml version="1.0" encoding="UTF-8"?>
        <ListBucketResult>
          <Name>ming-spike</Name>
          <Prefix></Prefix>
          <Marker>%E4%B8%AD%E6%96%87.txt</Marker>
          <MaxKeys>1</MaxKeys>
          <Delimiter></Delimiter>
          <EncodingType>url</EncodingType>
          <IsTruncated>false</IsTruncated>
          <Contents>
            <Key>%E9%98%BF%E9%87%8C%E4%BA%91.txt</Key>
            <LastModified>2016-01-07T11:07:32.000Z</LastModified>
            <ETag>"5D41402ABC4B2A76B9719D911017C592"</ETag>
            <Type>Normal</Type>
            <Size>5</Size>
            <StorageClass>Standard</StorageClass>
            <Owner>
              <ID>1047205513514293</ID>
              <DisplayName>1047205513514293</DisplayName>
            </Owner>
          </Contents>
        </ListBucketResult>''']

        expected = [SimplifiedObjectInfo('a.txt', 1452165000, '5EB63BBBE01EEED093CB22BB8F5ACDC3', 'Normal', 11,
                                         'Standard', Owner('1047205513514293', '1047205513514293')),
                    SimplifiedObjectInfo('中文.txt', 1452164979, 'FC3FF98E8C6A0D3087D515C0473F8677', 'Normal', 12,
                                         'Standard', Owner('1047205513514293', '1047205513514293')),
                    SimplifiedObjectInfo('阿里云.txt', 1452164852, '5D41402ABC4B2A76B9719D911017C592', 'Normal', 5,
                                         'Standard', Owner('1047205513514293', '1047205513514293'))]

        nreq = 3

        req_infos = [RequestInfo() for i in range(nreq)]

        do_request.auto_spec = True
        do_request.side_effect = make_do4body(req_infos=req_infos, body_list=body_list)

        got = list(oss2.ObjectIterator(bucket(), max_keys=1))

        for i in range(len(expected)):
            self.assertSimpleObjectInfoEqual(expected[i], got[i])

        for i in range(nreq):
            self.assertEqual(req_infos[i].req.params.get('prefix', ''), '')
            self.assertEqual(req_infos[i].req.params.get('max-keys', ''), '1')
            self.assertEqual(req_infos[i].req.params.get('delimiter', ''), '')
            self.assertEqual(req_infos[i].req.params.get('encoding-type', ''), 'url')

        self.assertEqual(req_infos[0].req.params.get('marker', ''), '')
        self.assertEqual(req_infos[1].req.params.get('marker', ''), 'a.txt')
        self.assertEqual(req_infos[2].req.params.get('marker', ''), '中文.txt')

    @patch('oss2.Session.do_request')
    def test_object_iterator_dir(self, do_request):
        body_list=[b'''<?xml version="1.0" encoding="UTF-8"?>
        <ListBucketResult>
          <Name>ming-spike</Name>
          <Prefix></Prefix>
          <Marker></Marker>
          <MaxKeys>1000</MaxKeys>
          <Delimiter>%2F</Delimiter>
          <EncodingType>url</EncodingType>
          <IsTruncated>false</IsTruncated>
          <Contents>
            <Key>a.txt</Key>
            <LastModified>2016-01-07T11:10:00.000Z</LastModified>
            <ETag>"5EB63BBBE01EEED093CB22BB8F5ACDC3"</ETag>
            <Type>Normal</Type>
            <Size>11</Size>
            <StorageClass>Standard</StorageClass>
            <Owner>
              <ID>1047205513514293</ID>
              <DisplayName>1047205513514293</DisplayName>
            </Owner>
          </Contents>
          <CommonPrefixes>
            <Prefix>%E6%96%87%E4%BB%B6%2F</Prefix>
          </CommonPrefixes>
        </ListBucketResult>''']

        expected = [SimplifiedObjectInfo('a.txt', 1452165000, '5EB63BBBE01EEED093CB22BB8F5ACDC3', 'Normal', 11,
                        'Standard', Owner('1047205513514293', '1047205513514293')),
                    SimplifiedObjectInfo('文件/', None, None, None, None, None, None)]

        req_info = RequestInfo()
        do_request.auto_spec = True
        do_request.side_effect = make_do4body(req_infos=[req_info], body_list=body_list)

        got = list(oss2.ObjectIterator(bucket(), max_keys=1000))

        for i in range(len(expected)):
            self.assertSimpleObjectInfoEqual(expected[i], got[i])

    @patch('oss2.Session.do_request')
    def test_upload_iterator_empty(self, do_request):
        body_list = [b'''<?xml version="1.0" encoding="UTF-8"?>
        <ListMultipartUploadsResult>
          <EncodingType>url</EncodingType>
          <Bucket>ming-spike</Bucket>
          <KeyMarker></KeyMarker>
          <UploadIdMarker></UploadIdMarker>
          <NextKeyMarker></NextKeyMarker>
          <NextUploadIdMarker></NextUploadIdMarker>
          <Delimiter></Delimiter>
          <Prefix></Prefix>
          <MaxUploads>1000</MaxUploads>
          <IsTruncated>false</IsTruncated>
        </ListMultipartUploadsResult>''']

        do_request.auto_spec = True
        do_request.side_effect = make_do4body(body_list=body_list)

        got = list(oss2.MultipartUploadIterator(bucket(), max_uploads=1000))
        self.assertEqual(len(got), 0)

    def test_part_iterator_default_max_retries(self):
        iter = oss2.PartIterator(bucket(), 'fake-key', 'fake-upload-id')
        self.assertEqual(iter.max_retries, oss2.defaults.request_retries)

        oss2.defaults.request_retries = 100
        iter = oss2.PartIterator(bucket(), 'fake-key', 'fake-upload-id')
        self.assertEqual(iter.max_retries, 100)

        iter = oss2.PartIterator(bucket(), 'fake-key', 'fake-upload-id', max_retries=1)
        self.assertEqual(iter.max_retries, 1)

    def test_object_iterator_default_max_retries(self):
        iter = oss2.ObjectIterator(bucket())
        self.assertEqual(iter.max_retries, oss2.defaults.request_retries)

        oss2.defaults.request_retries = 100
        iter = oss2.ObjectIterator(bucket())
        self.assertEqual(iter.max_retries, 100)

        iter = oss2.ObjectIterator(bucket(), max_retries=1)
        self.assertEqual(iter.max_retries, 1)

    def test_bucket_iterator_default_max_retries(self):
        iter = oss2.BucketIterator(service())
        self.assertEqual(iter.max_retries, oss2.defaults.request_retries)

        oss2.defaults.request_retries = 100
        iter = oss2.BucketIterator(service())
        self.assertEqual(iter.max_retries, 100)

        iter = oss2.BucketIterator(service(), max_retries=1)
        self.assertEqual(iter.max_retries, 1)

    def test_object_upload_iterator_default_max_retries(self):
        iter = oss2.ObjectUploadIterator(bucket(), 'fake-key')
        self.assertEqual(iter.max_retries, oss2.defaults.request_retries)

        oss2.defaults.request_retries = 100
        iter = oss2.ObjectUploadIterator(bucket(), 'fake-key')
        self.assertEqual(iter.max_retries, 100)

        iter = oss2.ObjectUploadIterator(bucket(), 'fake-key', max_retries=1)
        self.assertEqual(iter.max_retries, 1)

if __name__ == '__main__':
    unittest.main()


text:
package au.com.borner.salesforce.plugin.apex.language.structure;

import com.intellij.ide.structureView.StructureViewModel;
import com.intellij.ide.structureView.StructureViewModelBase;
import com.intellij.ide.structureView.StructureViewTreeElement;
import com.intellij.ide.util.treeView.smartTree.Sorter;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;

/**
 * @author Mark Borner (gzhomzb)
 */
public class ApexStructureViewModel extends StructureViewModelBase implements StructureViewModel.ElementInfoProvider {

    public ApexStructureViewModel(@NotNull PsiFile psiFile) {
        super(psiFile, new ApexStructureViewElement(psiFile));
    }

    @NotNull
    @Override
    public Sorter[] getSorters() {
        return new Sorter[] { Sorter.ALPHA_SORTER };
    }

    @Override
    public boolean isAlwaysShowsPlus(StructureViewTreeElement element) {
        return false;
    }

    @Override
    public boolean isAlwaysLeaf(StructureViewTreeElement element) {
        return false;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text;
using System.IO;
using System.Security;

namespace PgpSharp.IO
{
    [TestClass]
    public class IOUtilityTests
    {
        #region WriteSecret

        [TestMethod]
        public void WriteSecret_Should_Ignore_Null_Or_Empty()
        {
            // throw no exceptions with null args
            IOUtility.WriteSecret(null, null);
            using (var ss = new SecureString())
            {
                IOUtility.WriteSecret(null, ss);

                // test with empty
                StringBuilder sb = new StringBuilder();
                using (StringWriter sw = new StringWriter(sb))
                {
                    IOUtility.WriteSecret(sw, ss);
                }
                Assert.IsTrue(sb.Length == 0, "Written string not empty.");
            }
        }

        [TestMethod]
        public void WriteSecret_Works_With_Ascii_Text()
        {
            string text = "simple text";

            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            using (SecureString ss = Util.MakeSecureString(text))
            {
                IOUtility.WriteSecret(sw, ss);
                Assert.AreEqual(text, sb.ToString());
            }
        }

        [TestMethod]
        public void WriteSecret_Works_With_Non_Ascii_Text()
        {
            string text = "日本語です";

            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            using (SecureString ss = Util.MakeSecureString(text))
            {
                IOUtility.WriteSecret(sw, ss);
                Assert.AreEqual(text, sb.ToString());
            }
        }

        #endregion

        #region DecodeAsciiEscapes

        [TestMethod]
        public void DecodeAsciiEscapes_Handles_Null()
        {
            string input = null;
            var output = IOUtility.DecodeAsciiEscapes(input);
            Assert.AreEqual(input, output);
        }

        [TestMethod]
        public void DecodeAsciiEscapes_Handles_No_Escapes()
        {
            var input = "hello world!";
            var output = IOUtility.DecodeAsciiEscapes(input);
            Assert.AreEqual(input, output);
        }

        [TestMethod]
        public void DecodeAsciiEscapes_Handles_One_Escapes()
        {
            var input = @"hello\x20world!";
            var output = IOUtility.DecodeAsciiEscapes(input);
            Assert.AreEqual("hello world!", output);
        }

        [TestMethod]
        public void DecodeAsciiEscapes_Handles_Multiple_Escapes()
        {
            // also use this test for begin and end
            var input = @"\x40hello\x20world!\x3a";
            var output = IOUtility.DecodeAsciiEscapes(input);
            Assert.AreEqual("@hello world!:", output);
        }

        [TestMethod]
        public void DecodeAsciiEscapes_Handles_Ambiguous_Escapes()
        {
            var input = @"\x4010 cats say\x3aa lol cat.";
            var output = IOUtility.DecodeAsciiEscapes(input);
            Assert.AreEqual("@10 cats say:a lol cat.", output);
        }

        #endregion
    }
}


text:
#ifndef ma_dyncol_h
#define ma_dyncol_h

#include <decimal.h>
#include <my_decimal_limits.h>
#include <mysql_time.h>

/*
  Max length for data in a dynamic colums. This comes from how the
  how the offset are stored.
*/
#define MAX_DYNAMIC_COLUMN_LENGTH 0X1FFFFFFFL

/* NO and OK is the same used just to show semantics */
#define ER_DYNCOL_NO ER_DYNCOL_OK

enum enum_dyncol_func_result
{
  ER_DYNCOL_OK= 0,
  ER_DYNCOL_YES= 1,                /* For functions returning 0/1 */
  ER_DYNCOL_FORMAT= -1,            /* Wrong format of the encoded string */
  ER_DYNCOL_LIMIT=  -2,            /* Some limit reached */
  ER_DYNCOL_RESOURCE= -3,          /* Out of resourses */
  ER_DYNCOL_DATA= -4,              /* Incorrect input data */
  ER_DYNCOL_UNKNOWN_CHARSET= -5    /* Unknown character set */
};

typedef DYNAMIC_STRING DYNAMIC_COLUMN;

enum enum_dynamic_column_type
{
  DYN_COL_NULL= 0,
  DYN_COL_INT,
  DYN_COL_UINT,
  DYN_COL_DOUBLE,
  DYN_COL_STRING,
  DYN_COL_DECIMAL,
  DYN_COL_DATETIME,
  DYN_COL_DATE,
  DYN_COL_TIME
};

typedef enum enum_dynamic_column_type DYNAMIC_COLUMN_TYPE;

struct st_dynamic_column_value
{
  DYNAMIC_COLUMN_TYPE type;
  union
  {
    long long long_value;
    unsigned long long ulong_value;
    double double_value;
    struct {
      LEX_STRING value;
      CHARSET_INFO *charset;
    } string;
    struct {
      decimal_digit_t buffer[DECIMAL_BUFF_LENGTH];
      decimal_t value;
    } decimal;
    MYSQL_TIME time_value;
  } x;
};

typedef struct st_dynamic_column_value DYNAMIC_COLUMN_VALUE;

enum enum_dyncol_func_result
dynamic_column_create(DYNAMIC_COLUMN *str,
                      uint column_nr, DYNAMIC_COLUMN_VALUE *value);

enum enum_dyncol_func_result
dynamic_column_create_many(DYNAMIC_COLUMN *str,
                           uint column_count,
                           uint *column_numbers,
                           DYNAMIC_COLUMN_VALUE *values);

enum enum_dyncol_func_result
dynamic_column_update(DYNAMIC_COLUMN *org, uint column_nr,
                      DYNAMIC_COLUMN_VALUE *value);
enum enum_dyncol_func_result
dynamic_column_update_many(DYNAMIC_COLUMN *str,
                           uint add_column_count,
                           uint *column_numbers,
                           DYNAMIC_COLUMN_VALUE *values);

enum enum_dyncol_func_result
dynamic_column_delete(DYNAMIC_COLUMN *org, uint column_nr);

enum enum_dyncol_func_result
dynamic_column_exists(DYNAMIC_COLUMN *org, uint column_nr);

/* List of not NULL columns */
enum enum_dyncol_func_result
dynamic_column_list(DYNAMIC_COLUMN *org, DYNAMIC_ARRAY *array_of_uint);

/*
   if the column do not exists it is NULL
*/
enum enum_dyncol_func_result
dynamic_column_get(DYNAMIC_COLUMN *org, uint column_nr,
                   DYNAMIC_COLUMN_VALUE *store_it_here);

#define dynamic_column_initialize(A) memset((A), 0, sizeof(*(A)))
#define dynamic_column_column_free(V) dynstr_free(V)

/***************************************************************************
 Internal functions, don't use if you don't know what you are doing...
***************************************************************************/

#define dynamic_column_reassociate(V,P,L, A) dynstr_reassociate((V),(P),(L),(A))

#define dynamic_column_value_init(V) (V)->type= DYN_COL_NULL

/*
  Prepare value for using as decimal
*/
void dynamic_column_prepare_decimal(DYNAMIC_COLUMN_VALUE *value);

#endif


text:
from django.conf.urls import patterns, url, static, include
from django.contrib import admin
from django.views.generic import TemplateView

from pic import views

urlpatterns = patterns('',
  url(r'^uploadfile/$', views.uploadpic, name='uploadpic'),
  url(r'^listfiles/$', views.displaypic, name='displaypic'),
  url(r'^afterupload/$', TemplateView.as_view(template_name='pic/afterupload.html'), name='afterupload')
)


text:
"""Init for `cltk.lemmatize`."""

from .processes import *


text:
package usn.net.ssl.util;

import java.net.Socket;
import java.security.Security;
import java.util.Properties;

import javax.mail.AuthenticationFailedException;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

/**
 * A {@link StarttlsHandler} implementation for POP3 protocol.
 */
public class StarttlsHandlerPOP3
        implements StarttlsHandler, Runnable {

    @Override
    public boolean run(String host, int port, Socket tunnel) throws Exception // see http://javamail.kenai.com/nonav/javadocs/com/sun/mail/pop3/package-summary.html
    // TODO verify this method against some real POP3/STARTTLS server
    {
        this.host = host;
        this.port = port;

        final int timeout = 5000;
        Thread t = new Thread(this);
        t.start();

        Thread.sleep(timeout);
        t.interrupt();

        try {
            t.suspend();
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
        try {
            t.stop();
        } catch (Throwable ex) {
            ex.printStackTrace();
        }

        return returnValue;
    } // run

    boolean returnValue = false;
    String host = "";
    int port = 0;

    @Override
    public void run() {
        System.out.println("... trying POP3 with STARTTLS extension ...");
        Properties mailProps = new Properties();
        mailProps.put("mail.store.protocol", "pop3");
        mailProps.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        mailProps.put("mail.pop3.socketFactory.fallback", "false");
        mailProps.put("mail.pop3.starttls.enable", "true");

        mailProps.put("mail.smtp.timeout", "1000");
        mailProps.put("mail.smtp.connectiontimeout", "1000");
        mailProps.put("mail.pop3.timeout", "1000");
        mailProps.put("mail.pop3.connectiontimeout", "1000");
        mailProps.put("mail.imap.timeout", "1000");
        mailProps.put("mail.imap.connectiontimeout", "1000");
        mailProps.put("mail.imap.connectionpooltimeout", "1000");

        Security.setProperty("ssl.SocketFactory.provider",
                SavingSSLSocketFactory.class.getName());
        Session mailSession = Session.getDefaultInstance(mailProps);

        Store store = null;
        try {
            store = mailSession.getStore("pop3");
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            returnValue = false;
        }
        try {
            store.connect(host, port, "", "");
        } catch (AuthenticationFailedException e) {
            // likely got an unknown certificate, just report it and return
            // success
            System.out.println("ERROR on POP3 authentication: "
                    + e.toString());
            returnValue = false;
        } catch (MessagingException e) {
            System.out.println(e);
            returnValue = false;
        } finally {
            if (store.isConnected()) {
                try {
                    store.close();
                } catch (MessagingException e) {
                    // nothing to do here...
                }
            }

        }

        System.out.println("... trying POP3 with stopped...");
    }
} // class StarttlsHandlerPOP3


text:
#include <aws/frauddetector/model/UpdateModelVersionRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::FraudDetector::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

UpdateModelVersionRequest::UpdateModelVersionRequest() :
    m_modelIdHasBeenSet(false),
    m_modelType(ModelTypeEnum::NOT_SET),
    m_modelTypeHasBeenSet(false),
    m_majorVersionNumberHasBeenSet(false),
    m_externalEventsDetailHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
}

Aws::String UpdateModelVersionRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_modelIdHasBeenSet)
  {
   payload.WithString("modelId", m_modelId);

  }

  if(m_modelTypeHasBeenSet)
  {
   payload.WithString("modelType", ModelTypeEnumMapper::GetNameForModelTypeEnum(m_modelType));
  }

  if(m_majorVersionNumberHasBeenSet)
  {
   payload.WithString("majorVersionNumber", m_majorVersionNumber);

  }

  if(m_externalEventsDetailHasBeenSet)
  {
   payload.WithObject("externalEventsDetail", m_externalEventsDetail.Jsonize());

  }

  if(m_tagsHasBeenSet)
  {
   Array<JsonValue> tagsJsonList(m_tags.size());
   for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
   {
     tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize());
   }
   payload.WithArray("tags", std::move(tagsJsonList));

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection UpdateModelVersionRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSHawksNestServiceFacade.UpdateModelVersion"));
  return headers;

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<project name="maven-antrun-" default="main"  >
<target name="main">
  <mkdir dir="D:\ryneli\eclipse\git\RsyncHadoop\hadoop-common-project\hadoop-common\target/test-dir"/>
  <mkdir dir="D:\ryneli\eclipse\git\RsyncHadoop\hadoop-common-project\hadoop-common\target/test/data"/>
</target>
</project>


text:
package org.apache.apex.malhar.stream.sample;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import org.joda.time.Duration;
import org.junit.Assert;
import org.junit.Test;

import org.apache.apex.malhar.lib.function.Function;
import org.apache.apex.malhar.lib.window.TriggerOption;
import org.apache.apex.malhar.lib.window.Tuple;
import org.apache.apex.malhar.lib.window.WindowOption;
import org.apache.apex.malhar.stream.api.impl.ApexStreamImpl;
import org.apache.apex.malhar.stream.api.impl.StreamFactory;

import com.datatorrent.lib.util.KeyValPair;

/**
 * A test class which test your own stream implementation build on default one
 */
@SuppressWarnings("unchecked")
public class MyStreamTest
{
  static Map<String, Long> expected = new HashMap<>();
  static String testId = null;
  static Callable<Boolean> exitCondition = null;
  static {
    expected.put("newword1", 4L);
    expected.put("newword2", 8L);
    expected.put("newword3", 4L);
    expected.put("newword4", 4L);
    expected.put("newword5", 4L);
    expected.put("newword7", 4L);
    expected.put("newword9", 6L);

    exitCondition = new Callable<Boolean>()
    {
      @Override
      public Boolean call() throws Exception
      {
        if (!TupleCollector.results.containsKey(testId) || TupleCollector.results.get(testId).isEmpty()) {
          return false;
        }
        Map<String, Long> dataMap = new HashMap<>();
        List<Tuple.TimestampedTuple<KeyValPair<String, Long>>> data = (List<Tuple.TimestampedTuple<KeyValPair<String, Long>>>)TupleCollector.results.get(testId);
        for (Tuple.TimestampedTuple<KeyValPair<String, Long>> entry : data) {
          dataMap.put(entry.getValue().getKey(), entry.getValue().getValue());
        }
        return (dataMap != null) && dataMap.size() >= 1 && expected.equals(dataMap);
      }
    };
  }

  @Test
  public void testMethodChainWordcount() throws Exception
  {

    testId = "testMethodChainWordcount";

    TupleCollector<Tuple.WindowedTuple<KeyValPair<String, Long>>> collector = new TupleCollector<>();
    collector.id = testId;
    new MyStream<>((ApexStreamImpl<String>)StreamFactory.fromFolder("./src/test/resources/data"))
        .<String, MyStream<String>>flatMap(new Function.FlatMapFunction<String, String>()
        {
          @Override
          public Iterable<String> f(String input)
          {
            return Arrays.asList(input.split(" "));
          }
        }).myFilterAndMap(new Function.MapFunction<String, String>()
        {
          @Override
          public String f(String input)
          {
            return input.replace("word", "newword");
          }
        }, new Function.FilterFunction<String>()
        {
          @Override
          public boolean f(String input)
          {
            return input.startsWith("word");
          }
        }).window(new WindowOption.GlobalWindow(), new TriggerOption().accumulatingFiredPanes().withEarlyFiringsAtEvery(Duration.millis(1000)))
        .countByKey(new Function.ToKeyValue<String, String, Long>()
        {
          @Override
          public Tuple<KeyValPair<String, Long>> f(String input)
          {
            return new Tuple.PlainTuple(new KeyValPair<>(input, 1L));
          }
        }).addOperator(collector, collector.inputPort, null)
        .runEmbedded(false, 30000, exitCondition);

    Map<String, Long> dataMap = new HashMap<>();
    for (Tuple.TimestampedTuple<KeyValPair<String, Long>> entry : (List<Tuple.TimestampedTuple<KeyValPair<String, Long>>>)TupleCollector.results.get(testId)) {
      dataMap.put(entry.getValue().getKey(), entry.getValue().getValue());
    }

    Assert.assertTrue(dataMap.size() > 1);
    Assert.assertEquals(expected, dataMap);
  }

  @Test
  public void testNonMethodChainWordcount() throws Exception
  {
    testId = "testNonMethodChainWordcount";

    TupleCollector<Tuple.WindowedTuple<KeyValPair<String, Long>>> collector = new TupleCollector<>();
    collector.id = testId;
    MyStream<String> mystream = new MyStream<>((ApexStreamImpl<String>)StreamFactory
        .fromFolder("./src/test/resources/data"))
        .flatMap(new Function.FlatMapFunction<String, String>()
        {
          @Override
          public Iterable<String> f(String input)
          {
            return Arrays.asList(input.split(" "));
          }
        });
    mystream.myFilterAndMap(new Function.MapFunction<String, String>()
    {
      @Override
      public String f(String input)
      {
        return input.replace("word", "newword");
      }
    }, new Function.FilterFunction<String>()
    {
      @Override
      public boolean f(String input)
      {
        return input.startsWith("word");
      }
    }).window(new WindowOption.GlobalWindow(), new TriggerOption().accumulatingFiredPanes().withEarlyFiringsAtEvery(Duration.millis(1000)))
    .countByKey(new Function.ToKeyValue<String, String, Long>()
    {
      @Override
      public Tuple<KeyValPair<String, Long>> f(String input)
      {
        return new Tuple.PlainTuple(new KeyValPair<>(input, 1L));
      }
    }).addOperator(collector, collector.inputPort, collector.outputPort).runEmbedded(false, 30000, exitCondition);

    Map<String, Long> dataMap = new HashMap<>();
    for (Tuple.TimestampedTuple<KeyValPair<String, Long>> entry : (List<Tuple.TimestampedTuple<KeyValPair<String, Long>>>)TupleCollector.results.get(testId)) {
      dataMap.put(entry.getValue().getKey(), entry.getValue().getValue());
    }

    Assert.assertTrue(dataMap.size() > 1);
    Assert.assertEquals(expected, dataMap);
  }

}


text:
using De.Osthus.Ambeth.Service;
using System.Collections.Generic;

namespace De.Osthus.Ambeth.Cache
{
    public delegate IList<R> GetDataDelegate<V, R>(ICacheRetriever cacheRetriever, IList<V> arguments);
}


text:
package com.gusteauscuter.youyanguan.util;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ScrollView;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ScreenShotUtil {

    /**
     * 截取scrollview的屏幕
     * @param listView
     * @return
     */
    public static Bitmap getBitmapByView(ListView listView) {
        int h = 0;
        Bitmap bitmap = null;
        // 获取scrollview实际高度
        for (int i = 0; i < listView.getChildCount(); i++) {
            h += listView.getChildAt(i).getHeight();
//            listView.getChildAt(i).setBackgroundColor(
//                    Color.parseColor("#ffffff"));
        }
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(listView.getWidth(), h,
                Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        listView.draw(canvas);
        return bitmap;
    }

    public static Bitmap getBitmapByView(GridView gridView) {
        int h = 0;
        Bitmap bitmap = null;
        int num=gridView.getNumColumns();
        // 获取scrollview实际高度
        for (int i = 0; i < gridView.getChildCount(); i++) {
            if(i%num==0) {
                h += gridView.getChildAt(i).getHeight();
            }
            gridView.getChildAt(i).setBackgroundColor(
                    Color.parseColor("#ffffff"));
        }
        bitmap = Bitmap.createBitmap(gridView.getWidth(), h,
                Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        gridView.setBackgroundColor(Color.parseColor("#ffffff"));
        gridView.draw(canvas);
        return bitmap;
    }

    public static Bitmap getBitmapByView(View view) {
        Bitmap bitmap = null;
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
                Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        view.setBackgroundColor(Color.parseColor("#ffffff"));
        view.draw(canvas);
        return bitmap;
    }

    /**
     * 压缩图片
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        image.compress(Bitmap.CompressFormat.PNG, 100, baos);
        int options = 100;
        // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
        while (baos.toByteArray().length / 1024 > 100) {
            // 重置baos
            baos.reset();
            // 这里压缩options%,把压缩后的数据存放到baos中
            image.compress(Bitmap.CompressFormat.PNG, options, baos);
            // 每次都减少10
            options -= 10;
        }
        // 把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        // 把ByteArrayInputStream数据生成图片
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

    // 获取指定Activity的截屏,保存到png文件
    public static Bitmap takeScreenShot(Activity activity) {
        // View是你需要截图的View
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();
        // 获取状态栏高度
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

        int statusBarHeight = frame.top+175;
        Log.i("TAG", "" + statusBarHeight);
        // 获取屏幕长和高
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        int height = activity.getWindowManager().getDefaultDisplay()
                .getHeight();
        // 去掉标题栏
        // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
                - statusBarHeight);
        view.destroyDrawingCache();
        return b;
    }

    // 保存到sdcard

    /**
     * 保存到sdcard
     * @param b the bitmap to save by system time
     * @return
     */
    public static String savePic(Bitmap b) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss",
                Locale.US);
        File outfile = new File("/sdcard/image");
        // 如果文件不存在,则创建一个新文件
        if (!outfile.isDirectory()) {
            try {
                outfile.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String fname = outfile + "/" + sdf.format(new Date()) + ".png";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fname);
            if (null != fos) {
                b.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fname;
    }

    /**
     * 保存到sdcard
     * @param bitmap the bitmap to save by system time
     * @param strFileName file name to save the picture
     */

    public static void saveAsImg(Bitmap bitmap ,String strFileName) {

        SaveAsImage saveAsImgAsy=new ScreenShotUtil().new SaveAsImage();
        saveAsImgAsy.execute(bitmap,strFileName);
    }

    // 程序入口

    public static void shoot(String strFileName,View view) {
        ScreenShotUtil.saveAsImg(ScreenShotUtil.getBitmapByView(view), strFileName);
    }

    public static void shoot(String strFileName,ScrollView scrollView) {
        ScreenShotUtil.saveAsImg(ScreenShotUtil.getBitmapByView(scrollView), strFileName);
    }

    public static void shoot(String strFileName,GridView gridView) {
        ScreenShotUtil.saveAsImg(ScreenShotUtil.getBitmapByView(gridView), strFileName);
    }

    // 程序入口
    public static void shoot(String strFileName,Activity activity) {
        ScreenShotUtil.saveAsImg(ScreenShotUtil.takeScreenShot(activity), strFileName);
    }

    public class SaveAsImage extends AsyncTask<Object, Void, Void> {

        @Override
        protected Void doInBackground(Object... args) {

            try {
                Bitmap bitmap=(Bitmap) args[0] ;
                String strFileName=(String)args[1] ;
                File file =new File(strFileName);
                if(!file.getParentFile().exists()){
                    file.getParentFile().mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(strFileName,false);
                boolean bollean = bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
                fos.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

    }
}


text:
require_relative '../base_generator'

module Howitzer
  class PrerequisitesGenerator < BaseGenerator
    def manifest
      { files:
            [
                { source: 'factory_girl.rb', destination: 'prerequisites/factory_girl.rb'},
                { source: 'her.rb', destination: 'prerequisites/her.rb'},
                { source: 'users.rb', destination: 'prerequisites/factories/users.rb'},
                { source: 'user.rb', destination: 'prerequisites/models/user.rb'},
            ]
      }
    end

    protected
    def banner
      <<-EOS
  * Pre-requisites integration to the framework ...
      EOS
    end

  end
end


text:
import openmc

from tests.testing_harness import HashedPyAPITestHarness

class FilterMeshTestHarness(HashedPyAPITestHarness):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Initialize Meshes
        mesh_1d = openmc.Mesh(mesh_id=1)
        mesh_1d.type = 'regular'
        mesh_1d.dimension = [17]
        mesh_1d.lower_left = [-182.07]
        mesh_1d.upper_right = [182.07]

        mesh_2d = openmc.Mesh(mesh_id=2)
        mesh_2d.type = 'regular'
        mesh_2d.dimension = [17, 17]
        mesh_2d.lower_left = [-182.07, -182.07]
        mesh_2d.upper_right = [182.07, 182.07]

        mesh_3d = openmc.Mesh(mesh_id=3)
        mesh_3d.type = 'regular'
        mesh_3d.dimension = [17, 17, 17]
        mesh_3d.lower_left = [-182.07, -182.07, -183.00]
        mesh_3d.upper_right = [182.07, 182.07, 183.00]

        # Initialize the filters
        mesh_1d_filter = openmc.MeshFilter(mesh_1d)
        mesh_2d_filter = openmc.MeshFilter(mesh_2d)
        mesh_3d_filter = openmc.MeshFilter(mesh_3d)
        meshsurf_1d_filter = openmc.MeshSurfaceFilter(mesh_1d)
        meshsurf_2d_filter = openmc.MeshSurfaceFilter(mesh_2d)
        meshsurf_3d_filter = openmc.MeshSurfaceFilter(mesh_3d)

        # Initialized the tallies
        tally = openmc.Tally(name='tally 1')
        tally.filters = [mesh_1d_filter]
        tally.scores = ['total']
        self._model.tallies.append(tally)

        tally = openmc.Tally(name='tally 2')
        tally.filters = [meshsurf_1d_filter]
        tally.scores = ['current']
        self._model.tallies.append(tally)

        tally = openmc.Tally(name='tally 3')
        tally.filters = [mesh_2d_filter]
        tally.scores = ['total']
        self._model.tallies.append(tally)

        tally = openmc.Tally(name='tally 4')
        tally.filters = [meshsurf_2d_filter]
        tally.scores = ['current']
        self._model.tallies.append(tally)

        tally = openmc.Tally(name='tally 5')
        tally.filters = [mesh_3d_filter]
        tally.scores = ['total']
        self._model.tallies.append(tally)

        tally = openmc.Tally(name='tally 6')
        tally.filters = [meshsurf_3d_filter]
        tally.scores = ['current']
        self._model.tallies.append(tally)

def test_filter_mesh():
    harness = FilterMeshTestHarness('statepoint.10.h5')
    harness.main()


text:
@implementation QYShowMycircleApiManager

- (BOOL)shouldCache {

    return NO;
}
@end


text:
<?php
/**
 * Created by PhpStorm.
 * User: lihz
 * Date: 16/8/12
 * Time: 下午5:46
 */
namespace Leegoway\QyWechat\Core;

use Monolog\Handler\ErrorLogHandler;
use Monolog\Handler\NullHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;

/**
 * Class Log.
 */
class Log
{
    /**
     * Logger instance.
     *
     * @var \Psr\Log\LoggerInterface
     */
    protected static $logger;

    /**
     * Return the logger instance.
     *
     * @return \Psr\Log\LoggerInterface
     */
    public static function getLogger()
    {
        return self::$logger ?: self::$logger = self::createDefaultLogger();
    }

    /**
     * Set logger.
     *
     * @param \Psr\Log\LoggerInterface $logger
     */
    public static function setLogger(LoggerInterface $logger)
    {
        self::$logger = $logger;
    }

    /**
     * Tests if logger exists.
     *
     * @return bool
     */
    public static function hasLogger()
    {
        return self::$logger ? true : false;
    }

    /**
     * Forward call.
     *
     * @param string $method
     * @param array  $args
     *
     * @return mixed
     */
    public static function __callStatic($method, $args)
    {
        return forward_static_call_array([self::getLogger(), $method], $args);
    }

    /**
     * Forward call.
     *
     * @param string $method
     * @param array  $args
     *
     * @return mixed
     */
    public function __call($method, $args)
    {
        return call_user_func_array([self::getLogger(), $method], $args);
    }

    /**
     * Make a default log instance.
     *
     * @return \Monolog\Logger
     */
    private static function createDefaultLogger()
    {
        $log = new Logger('QyWechat');

        if (defined('PHPUNIT_RUNNING')) {
            $log->pushHandler(new NullHandler());
        } else {
            $log->pushHandler(new ErrorLogHandler());
        }

        return $log;
    }
}


text:
module Swarm
  module Storage
    class KeyValueStorage
      class AssociationKeyMissingError < StandardError; end

      attr_reader :store

      def initialize(store)
        @store = store
      end

      def trace
        self["trace"]
      end

      def trace=(traced)
        self["trace"] = traced
      end

      def regex_for_type(type)
        /^#{type}\:(.*)/
      end

      def ids_for_type(type)
        raise "Not implemented yet!"
      end

      def all_of_type(type)
        raise "Not implemented yet!"
      end

      def add_association(association_name, associated, owner:, class_name:, foreign_key: nil)
        key = :"#{association_name}_ids"
        if owner.respond_to?(key)
          ids = owner.send(key) || owner.send("#{key}=", [])
          ids << associated.id
          associated
        else
          raise AssociationKeyMissingError, key
        end
      end

      def load_associations(association_name, owner:, class_name:, foreign_key: nil)
        key = :"#{association_name}_ids"
        if owner.respond_to?(key)
          ids = owner.send(key) || []
          ids.map { |id|
            self["#{class_name.split("::").last}:#{id}"]
          }.compact
        else
          raise AssociationKeyMissingError, key
        end
      end

      def serialize(value)
        return nil if value.nil?
        value.to_json
      end

      def deserialize(value)
        return nil if value.nil?
        JSON.parse(value)
      end

      def [](key)
        deserialize(store[key])
      end

      def []=(key, value)
        store[key] = serialize(value)
      end

      def delete(key)
        raise "Not implemented yet!"
      end

      def truncate
        raise "Not implemented yet!"
      end
    end
  end
end


text:
#include <aws/sagemaker/model/DeviceDeploymentSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SageMaker
{
namespace Model
{

DeviceDeploymentSummary::DeviceDeploymentSummary() :
    m_edgeDeploymentPlanArnHasBeenSet(false),
    m_edgeDeploymentPlanNameHasBeenSet(false),
    m_stageNameHasBeenSet(false),
    m_deployedStageNameHasBeenSet(false),
    m_deviceFleetNameHasBeenSet(false),
    m_deviceNameHasBeenSet(false),
    m_deviceArnHasBeenSet(false),
    m_deviceDeploymentStatus(DeviceDeploymentStatus::NOT_SET),
    m_deviceDeploymentStatusHasBeenSet(false),
    m_deviceDeploymentStatusMessageHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_deploymentStartTimeHasBeenSet(false)
{
}

DeviceDeploymentSummary::DeviceDeploymentSummary(JsonView jsonValue) :
    m_edgeDeploymentPlanArnHasBeenSet(false),
    m_edgeDeploymentPlanNameHasBeenSet(false),
    m_stageNameHasBeenSet(false),
    m_deployedStageNameHasBeenSet(false),
    m_deviceFleetNameHasBeenSet(false),
    m_deviceNameHasBeenSet(false),
    m_deviceArnHasBeenSet(false),
    m_deviceDeploymentStatus(DeviceDeploymentStatus::NOT_SET),
    m_deviceDeploymentStatusHasBeenSet(false),
    m_deviceDeploymentStatusMessageHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_deploymentStartTimeHasBeenSet(false)
{
  *this = jsonValue;
}

DeviceDeploymentSummary& DeviceDeploymentSummary::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("EdgeDeploymentPlanArn"))
  {
    m_edgeDeploymentPlanArn = jsonValue.GetString("EdgeDeploymentPlanArn");

    m_edgeDeploymentPlanArnHasBeenSet = true;
  }

  if(jsonValue.ValueExists("EdgeDeploymentPlanName"))
  {
    m_edgeDeploymentPlanName = jsonValue.GetString("EdgeDeploymentPlanName");

    m_edgeDeploymentPlanNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("StageName"))
  {
    m_stageName = jsonValue.GetString("StageName");

    m_stageNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DeployedStageName"))
  {
    m_deployedStageName = jsonValue.GetString("DeployedStageName");

    m_deployedStageNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DeviceFleetName"))
  {
    m_deviceFleetName = jsonValue.GetString("DeviceFleetName");

    m_deviceFleetNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DeviceName"))
  {
    m_deviceName = jsonValue.GetString("DeviceName");

    m_deviceNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DeviceArn"))
  {
    m_deviceArn = jsonValue.GetString("DeviceArn");

    m_deviceArnHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DeviceDeploymentStatus"))
  {
    m_deviceDeploymentStatus = DeviceDeploymentStatusMapper::GetDeviceDeploymentStatusForName(jsonValue.GetString("DeviceDeploymentStatus"));

    m_deviceDeploymentStatusHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DeviceDeploymentStatusMessage"))
  {
    m_deviceDeploymentStatusMessage = jsonValue.GetString("DeviceDeploymentStatusMessage");

    m_deviceDeploymentStatusMessageHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Description"))
  {
    m_description = jsonValue.GetString("Description");

    m_descriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DeploymentStartTime"))
  {
    m_deploymentStartTime = jsonValue.GetDouble("DeploymentStartTime");

    m_deploymentStartTimeHasBeenSet = true;
  }

  return *this;
}

JsonValue DeviceDeploymentSummary::Jsonize() const
{
  JsonValue payload;

  if(m_edgeDeploymentPlanArnHasBeenSet)
  {
   payload.WithString("EdgeDeploymentPlanArn", m_edgeDeploymentPlanArn);

  }

  if(m_edgeDeploymentPlanNameHasBeenSet)
  {
   payload.WithString("EdgeDeploymentPlanName", m_edgeDeploymentPlanName);

  }

  if(m_stageNameHasBeenSet)
  {
   payload.WithString("StageName", m_stageName);

  }

  if(m_deployedStageNameHasBeenSet)
  {
   payload.WithString("DeployedStageName", m_deployedStageName);

  }

  if(m_deviceFleetNameHasBeenSet)
  {
   payload.WithString("DeviceFleetName", m_deviceFleetName);

  }

  if(m_deviceNameHasBeenSet)
  {
   payload.WithString("DeviceName", m_deviceName);

  }

  if(m_deviceArnHasBeenSet)
  {
   payload.WithString("DeviceArn", m_deviceArn);

  }

  if(m_deviceDeploymentStatusHasBeenSet)
  {
   payload.WithString("DeviceDeploymentStatus", DeviceDeploymentStatusMapper::GetNameForDeviceDeploymentStatus(m_deviceDeploymentStatus));
  }

  if(m_deviceDeploymentStatusMessageHasBeenSet)
  {
   payload.WithString("DeviceDeploymentStatusMessage", m_deviceDeploymentStatusMessage);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("Description", m_description);

  }

  if(m_deploymentStartTimeHasBeenSet)
  {
   payload.WithDouble("DeploymentStartTime", m_deploymentStartTime.SecondsWithMSPrecision());
  }

  return payload;
}

} // namespace Model
} // namespace SageMaker
} // namespace Aws


text:
"""Hundli: a dog height and weight simulation engine

This is not technically part of Sirepo. It demonstrates a arbitrary 3rd
party code, which Sirepo calls as an independent program.

:copyright: Copyright (c) 2018 RadiaSoft LLC.  All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import csv
import numpy
import os
import random
import sys
import time
import yaml

_MAX_AGE_BY_WEIGHT = [
    [0, 16],
    [20, 13],
    [50, 11],
    [90, 10],
]

def main():
    """Read the input yaml and write the output csv"""
    # hack support for openmpi/mpich so we can run under mpi with only one output file
    if os.environ.get('OMPI_COMM_WORLD_RANK', os.environ.get('PMI_RANK', '0')) != '0':
        sys.stderr.write('does not work with MPI\n')
        exit(0)
    if len(sys.argv) != 3:
        sys.stderr.write('usage: hundli input.yml output.csv\n')
        exit(1)
    input_yaml, output_csv = sys.argv[1:]
    with open(input_yaml, 'r') as f:
        params = yaml.load(f)

    if params['name'] == 'srunit_long_run':
        time.sleep(100)

    max_age = _max_age(params['weight'])
    years = numpy.linspace(0, max_age, int(max_age) + 1).tolist()
    heights = _points_size(params['height'], years)
    weights = _points_size(params['weight'], years)
    activity = _points_activity(years)
    with open(output_csv, 'w') as f:
        out = csv.writer(f)
        out.writerow(('Year', 'Height', 'Weight', 'Activity'))
        out.writerows(zip(years, heights, weights, activity))

def _factor(v, max_value, exp):
    return (random.random() * 0.5) * max_value / exp \
        + max_value * (exp - 1.0) / exp * (1.0 - 1.0 / (1.0 + v ** 2))

def _max_age(weight):
    """Weight affects life expectancy

    Improvement would be consider gender.
    """
    prev = None
    for bracket in _MAX_AGE_BY_WEIGHT:
        if weight <= bracket[0]:
            break
        prev = bracket[1]
    return prev

def _points_activity(years):
    """Random function"""
    max_value = 11.0
    return map(
        lambda v: max_value - _factor(v, max_value, 5.0),
        years,
    )

def _points_size(max_value, years):
    """Randomized """
    return map(
        lambda v: _factor(v, max_value, 20.0),
        years,
    )

if __name__ == '__main__':
    main()


text:
package org.wso2.carbon.registry.ws.client.registry;

import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.rampart.RampartMessageData;
import org.apache.rampart.policy.model.CryptoConfig;
import org.apache.rampart.policy.model.RampartConfig;
import org.apache.ws.security.components.crypto.Merlin;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.authenticator.stub.LogoutAuthenticationExceptionException;
import org.wso2.carbon.core.common.AuthenticationException;
import org.wso2.carbon.registry.core.*;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.config.RegistryContext;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.pagination.PaginationContext;
import org.wso2.carbon.registry.core.pagination.PaginationUtils;
import org.wso2.carbon.registry.ws.client.resource.OnDemandContentCollectionImpl;
import org.wso2.carbon.registry.ws.client.resource.OnDemandContentResourceImpl;
import org.wso2.carbon.registry.ws.stub.WSRegistryServiceStub;
import org.wso2.carbon.registry.ws.stub.xsd.*;
import org.wso2.carbon.utils.CarbonUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.xml.stream.XMLStreamException;
import java.io.*;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.*;

public class WSRegistryServiceClient implements Registry {
	private static final Log log = LogFactory.getLog(WSRegistryServiceClient.class);
	private WSRegistryServiceStub stub;
    AuthenticationAdminStub authenticationAdminStub;
	private String cookie;
	private String epr;

    public WSRegistryServiceClient(String backendServerURL, String cookie, long timeoutInMilliSeconds)
            throws RegistryException{
        initWithCookie(backendServerURL, cookie, timeoutInMilliSeconds);
    }

	public WSRegistryServiceClient(String backendServerURL, String cookie)
    	throws RegistryException{
        initWithCookie(backendServerURL, cookie, 1000000);
	}

    private void initWithCookie(String backendServerURL, String cookie, long timeOutInMilliSeconds) throws RegistryException {
        epr = backendServerURL + "WSRegistryService";
                	/*Since user provided the cookie no need to authenticate with username and password*/
        setCookie(cookie);
        try{
            if (CarbonUtils.isRunningOnLocalTransportMode()) {
                stub = new WSRegistryServiceStub(
                        WSRegistryClientUtils.getConfigurationContext(), epr);
            } else {
                stub = new WSRegistryServiceStub(epr);
            }
            ServiceClient client = stub._getServiceClient();
            Options options = client.getOptions();
            options.setManageSession(true);
            options.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
            stub._getServiceClient().getOptions().setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
            //Increase the time out when sending large attachments
            stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(timeOutInMilliSeconds);
        }catch (Exception axisFault){
            String msg = "Failed to initiate WSRegistry Service client. " + axisFault.getMessage();
            log.error(msg, axisFault);
            throw new RegistryException(msg, axisFault);
        }
    }

    public WSRegistryServiceClient(String serverURL, String username, String password, long timeOutInMilliSeconds,
                                       ConfigurationContext configContext) throws RegistryException {
        initWithUserNameAndPassword(serverURL, username, password, timeOutInMilliSeconds, configContext);
    }

    public WSRegistryServiceClient(String serverURL, String username, String password,
                                   ConfigurationContext configContext) throws RegistryException {
        initWithUserNameAndPassword(serverURL, username, password, 100000, configContext);
    }

    public void initWithUserNameAndPassword(String serverURL, String username, String password,
                                            long timeOutInMilliSeconds, ConfigurationContext configContext)
	throws RegistryException {

		epr = serverURL + "WSRegistryService";
		try {
			authenticate(configContext, serverURL, username, password);
			stub = new WSRegistryServiceStub(configContext, epr);

			ServiceClient client = stub._getServiceClient();
			Options options = client.getOptions();

			options.setManageSession(true);
			options.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);

			stub._getServiceClient().getOptions().setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
			//Increase the time out when sending large attachments
			stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(timeOutInMilliSeconds);

		} catch (Exception axisFault) {
			String msg = "Failed to initiate WSRegistry Service client. " + axisFault.getMessage();
			log.error(msg, axisFault);
			throw new RegistryException(msg, axisFault);
		}
	}

    public WSRegistryServiceClient(String serverURL, String username, String password,
                                   String backendServerURL, long timeOutInMilliSeconds,
                                   ConfigurationContext configContext) throws RegistryException {
        initWithBackendURLUserNameAndPassword(serverURL, username, password, backendServerURL, timeOutInMilliSeconds, configContext);
    }

    public WSRegistryServiceClient(String serverURL, String username, String password,
                                   String backendServerURL, ConfigurationContext configContext) throws RegistryException {
        initWithBackendURLUserNameAndPassword(serverURL, username, password, backendServerURL, 1000000, configContext);
    }

    private void initWithBackendURLUserNameAndPassword(String serverURL, String username, String password,
                                                       String backendServerURL, long timeOutInMilliSeconds,
                                                       ConfigurationContext configContext) throws RegistryException {
        epr = backendServerURL + "WSRegistryService";
        String policyPath = "META-INF/policy.xml";
        try {
            authenticate(configContext, serverURL, username, password);
            stub = new WSRegistryServiceStub(configContext, epr);

            ServiceClient client = stub._getServiceClient();
            Options options = client.getOptions();

            options.setManageSession(true);
            options.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);

            stub._getServiceClient().getOptions().setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
            //Increase the time out when sending large attachments
            stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(timeOutInMilliSeconds);

        } catch (Exception axisFault) {
            String msg = "Failed to initiate WSRegistry Service client. " + axisFault.getMessage();
            log.error(msg, axisFault);
            throw new RegistryException(msg, axisFault);
        }
    }

	public boolean authenticate(ConfigurationContext ctx, String serverURL, String username, String password)
            throws AxisFault, AuthenticationException {
		String serviceEPR = serverURL + "AuthenticationAdmin";

        authenticationAdminStub = new AuthenticationAdminStub(ctx, serviceEPR);
		ServiceClient client = authenticationAdminStub._getServiceClient();
		Options options = client.getOptions();
		options.setManageSession(true);
		try {
			boolean result = authenticationAdminStub.login(username, password, new URL(serviceEPR).getHost());
			if (result){
                setCookie((String) authenticationAdminStub._getServiceClient().getServiceContext().
                        getProperty(HTTPConstants.COOKIE_STRING));
			}
			return result;
		} catch (Exception e) {
			String msg = "Error occurred while logging in";
			throw new AuthenticationException(msg, e);
		}
	}

    public void logut () throws RemoteException, LogoutAuthenticationExceptionException {
        authenticationAdminStub.logout();
    }

	private static Policy loadPolicy(String xmlPath) throws FileNotFoundException, XMLStreamException {
		StAXOMBuilder builder = new StAXOMBuilder(xmlPath);
		return PolicyEngine.getPolicy(builder.getDocumentElement());
	}

	public void addSecurityOptions ( String policyPath, String keyStore,String userName, String password) throws AxisFault, FileNotFoundException, XMLStreamException {
		ServiceClient client = stub._getServiceClient();

		Policy policy = loadPolicy(policyPath);

		Properties merlinProp = new Properties();
		merlinProp.put("org.apache.ws.security.crypto.merlin.keystore.type", "JKS");
		merlinProp.put("org.apache.ws.security.crypto.merlin.file",
		               keyStore);

		merlinProp.put("org.apache.ws.security.crypto.merlin.keystore.password", "wso2carbon");

		CryptoConfig sigCryptoConfig = new CryptoConfig();
		sigCryptoConfig.setProvider(Merlin.class.getName());
		sigCryptoConfig.setProp(merlinProp);

		CryptoConfig encCryptoConfig = new CryptoConfig();
		encCryptoConfig.setProvider(Merlin.class.getName());
		encCryptoConfig.setProp(merlinProp);

		RampartConfig rampartConfig = new RampartConfig();
		rampartConfig.setEncryptionUser("wso2carbon");
		rampartConfig.setUserCertAlias("wso2carbon");
		rampartConfig.setPwCbClass(PWCBHandler.class.getName());
		rampartConfig.setSigCryptoConfig(sigCryptoConfig);
		rampartConfig.setEncrCryptoConfig(encCryptoConfig);

		policy.addAssertion(rampartConfig);

		Options options = client.getOptions();
		options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, policy);
		options.setUserName(userName);
		options.setPassword(password);

		client.engageModule("rampart");
	}

	public Resource newResource() {
		return new ResourceImpl();
	}

	public Collection newCollection() {
		return new CollectionImpl(new String[0]);
	}

	public Resource get(String path) throws RegistryException {
		WSResource wsResource;
		try {

			if (path.contains(";comments")) {
				String[] pathParts = path.split(";comments");
				if (pathParts.length < 2) {
					Comment[] comments = getComments(pathParts[0]);
					Resource resource = new CollectionImpl();
					resource.setContent(comments);
					return resource;
				}
				else {
					return getSingleComment(path);
				}
			} else if (path.contains(";ratings")) {
				String[] pathParts = path.split(";ratings:");
				if (pathParts.length > 1) {
					int rating = getRating(pathParts[0], pathParts[1]);
					Resource resource = getMetaData(pathParts[0]);
					resource.setContent(rating);
					return resource;
				}
			}

			wsResource =  stub.wSget(path);
			byte[] content = null;
			Resource resource;
			if (wsResource.getCollection()) {
				resource = WSRegistryClientUtils.transformWSCollectiontoCollection(this, (WSCollection) wsResource, content);
                ((OnDemandContentCollectionImpl) resource).setPathWithVersion(path);
			}
			else {
				resource = WSRegistryClientUtils.transformWSResourcetoResource(this, wsResource, content);
				((OnDemandContentResourceImpl) resource).setPathWithVersion(path);
			}
			return resource;
		} catch (Exception e) {
			String msg = "Failed to perform get operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	private Comment getSingleComment(String commentPath) throws RegistryException {
		try {
			WSComment wsComment =  stub.wSgetSingleComment(commentPath);
			return WSRegistryClientUtils.WSCommenttoRegistryComment(wsComment);

		} catch (Exception e) {
			String msg = "Failed to perform the operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

    public void setTenantId(int tenantId) throws RegistryException {
        try {
            stub.setTenantId(tenantId);
        } catch (Exception e) {
            String msg = "Failed to perform the operation.";
            log.error(msg, e);
            throw new RegistryException(msg, e);
        }
	}

	public  Resource getMetaData(String path) throws RegistryException {
		Resource resource;
		try {
			WSResource wsResource = stub.wSgetMetaData(path);
			byte[] content = null;
			resource = WSRegistryClientUtils.transformWSResourcetoResource(this, wsResource, content);
			return resource;
		} catch (Exception e) {
			String msg = "Failed to perform getMetaData operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}

	}

	public Collection get(String path, int start, int pageSize) throws RegistryException {
		Collection collection;
		try {
			WSCollection wsCollection = stub.wSgetWithPageSize(path,start,pageSize);
			byte[] content = null;
			collection = WSRegistryClientUtils.transformWSCollectiontoCollection(this, wsCollection, content);
            ((OnDemandContentCollectionImpl) collection).setPathWithVersion(path + ";start=" + start + ";pageSize=" + pageSize);
			return collection;
		} catch (Exception e) {
			String msg = "Failed to perform get operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public  boolean resourceExists(String path) throws RegistryException {
		try {
			return stub.resourceExists(path);
		} catch (Exception e) {
			String msg = "Failed to perform resourceExists operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public String put(String path, Resource resource) throws RegistryException {
		try {
            File tempFile = File.createTempFile("wsResource","tmp");
            tempFile.deleteOnExit();
            DataHandler dataHandler = WSRegistryClientUtils.makeDataHandler(resource, tempFile);
            String string;
            if (resource instanceof Collection) {
				WSResource wsCollection = WSRegistryClientUtils.transformResourceToWSResource(resource, dataHandler);
                wsCollection.setCollection(true);
				string =  stub.wSput(path,wsCollection);
			}
			else {
				WSResource wsResource = WSRegistryClientUtils.transformResourceToWSResource(resource, dataHandler);
				string =  stub.wSput(path,wsResource);
			}

			return string;
		} catch (Exception e) {
			String msg = "Failed to perform put operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

    public void delete(String path) throws RegistryException {
		try {
			stub.delete(path);
		} catch (Exception e) {
			String msg = "Failed to perform delete operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

    public String importResource(String suggestedPath, String sourceURL, Resource resource) throws RegistryException {
		try {

			DataHandler dataHandler = null;
			File tempFile = File.createTempFile("wsResource","tmp");
			tempFile.deleteOnExit();
			try {
				dataHandler = WSRegistryClientUtils.makeDataHandler(resource, tempFile);
			} catch (IOException e) {
				log.error("WSGet failed - Unable to generate temp file",e);
			}
			WSResource wsResource = WSRegistryClientUtils.transformResourceToWSResource(resource, dataHandler);
			return stub.wSimportResource(suggestedPath,sourceURL,wsResource);
		} catch (Exception e) {
			String msg = "Failed to perform importResource operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public  String rename(String currentPath, String newName) throws RegistryException {
		try {
			return stub.rename(currentPath,newName);
		} catch (Exception e) {
			String msg = "Failed to perform rename operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public  String move(String currentPath, String newPath) throws RegistryException {
		try {
			return stub.move(currentPath,newPath);
		} catch (Exception e) {
			String msg = "Failed to perform move operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public  String copy(String currentPath, String targetPath) throws RegistryException {
		try {
			return stub.copy(currentPath,targetPath);
		} catch (Exception e) {
			String msg = "Failed to perform copy operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public  void createVersion(String path) throws RegistryException {
		try {
			stub.createVersion(path);
		} catch (Exception e) {
			String msg = "Failed to perform createVersion operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public  String[] getVersions(String path) throws RegistryException {
		try {
			return stub.getVersions(path);
		} catch (Exception e) {
			String msg = "Failed to perform getVersions operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public  void restoreVersion(String path) throws RegistryException {
		try {
			stub.restoreVersion(path);
		} catch (Exception e) {
			String msg = "Failed to perform restoreVersion operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public  void addAssociation(String resourcePath, String targetPath, String associationType) throws RegistryException {
		try {
			stub.addAssociation(resourcePath,targetPath,associationType);
		} catch (Exception e) {
			String msg = "Failed to perform addAssociation operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public  void removeAssociation(String resourcePath, String targetPath, String associationType) throws RegistryException {
		try {
			stub.removeAssociation(resourcePath,targetPath,associationType);
		} catch (Exception e) {
			String msg = "Failed to perform removeAssociation operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public  Association[] getAllAssociations(String path) throws RegistryException {
		try {
            WSAssociation[] wsAssociations = stub.wSgetAllAssociations(path);
            if(null == wsAssociations) {
                return  new Association[0];
            }
            Association[] associations = new Association[wsAssociations.length];
            for (int i = 0; i < associations.length; i++) {
                associations[i] = WSRegistryClientUtils.transformWSAssociationToAssociation(
                                                            wsAssociations[i]);
            }
            return associations;
		} catch (Exception e) {
			String msg = "Failed to perform getAllAssociations operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public Association[] getAssociations(String resourcePath, String associationType) throws RegistryException {
		try {
            WSAssociation[] wsAssociations = stub.wSgetAssociations(resourcePath, associationType);
            if( null == wsAssociations) {
               return new Association[0];
            }
            Association[] associations = new Association[wsAssociations.length];
            for (int i = 0; i < associations.length; i++) {
                associations[i] = WSRegistryClientUtils.transformWSAssociationToAssociation(
                                                            wsAssociations[i]);
            }
            return associations;
		} catch (Exception e) {
			String msg = "Failed to perform getAssociations operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public  void applyTag(String resourcePath, String tag) throws RegistryException {
		try {
			stub.applyTag(resourcePath,tag);
		} catch (Exception e) {
			String msg = "Failed to perform applyTag operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public  TaggedResourcePath[] getResourcePathsWithTag(String path) throws RegistryException {
		try {
			WSTaggedResourcePath[] wsTaggedResourcePaths = stub.wSgetResourcePathsWithTag(path);
			return WSRegistryClientUtils.exchangeWSResourcePath(wsTaggedResourcePaths);
		} catch (Exception e) {
			String msg = "Failed to perform getResourcePathsWithTag operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public Tag[] getTags(String resourcePath) throws RegistryException {
		try {
            WSTag[] wsTags;
            if(PaginationContext.getInstance() == null){
                wsTags = stub.wSgetTags(resourcePath);
            }else {
                PaginationUtils.copyPaginationContext(stub._getServiceClient());
                wsTags = stub.wSgetTags(resourcePath);
                int rowCount = PaginationUtils.getRowCount(stub._getServiceClient());
            }
            if(null == wsTags) {
                return new Tag[0];
            }
            Tag[] tags = new Tag[wsTags.length];
            for (int i = 0; i < tags.length; i++) {
                tags[i] = WSRegistryClientUtils.transformWSTagToTag(wsTags[i]);
            }
            return tags;
		} catch (Exception e) {
			String msg = "Failed to perform getTags operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}finally {
            PaginationContext.destroy();
        }
    }
	public  void removeTag(String path,String tag) throws RegistryException {
		try {
			stub.removeTag(path,tag);
		} catch (Exception e) {
			String msg = "Failed to perform removeTag operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public  String addComment(String resourcePath, Comment comment) throws RegistryException {
		try {
			WSComment wsComment = WSRegistryClientUtils.RegistryCommenttoWSComment(comment);
			return stub.wSaddComment(resourcePath,wsComment);
		} catch (Exception e) {
			String msg = "Failed to perform addComment operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public  void editComment(String commentPath, String text) throws RegistryException {
		try {
			stub.editComment(commentPath,text);
		} catch (Exception e) {
			String msg = "Failed to perform editComment operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public  Comment[] getComments(String resourcePath) throws RegistryException {
		try {
            WSComment[] wsComment;
            if(PaginationContext.getInstance() == null){
                wsComment =  stub.wSgetComments(resourcePath);
            }else {
                PaginationUtils.copyPaginationContext(stub._getServiceClient());
                wsComment =  stub.wSgetComments(resourcePath);
                int rowCount = PaginationUtils.getRowCount(stub._getServiceClient());
            }
            if(null == wsComment) {
                return  new Comment[0];
            }
			Comment[] comment = new Comment[wsComment.length];
			for (int i = 0;i < wsComment.length; i++) {
				comment[i] = WSRegistryClientUtils.WSCommenttoRegistryComment(wsComment[i]);
			}
			return comment;

		} catch (Exception e) {
			String msg = "Failed to perform getComments operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public void rateResource(String resourcePath, int rating) throws RegistryException {
		try {
			stub.rateResource(resourcePath,rating);
		} catch (Exception e) {
			String msg = "Failed to perform rateResource operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public  float getAverageRating(String resourcePath) throws RegistryException {
		try {
			return stub.getAverageRating(resourcePath);
		} catch (Exception e) {
			String msg = "Failed to perform getAverageRating operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public int getRating(String path, String username) throws RegistryException {
		try {
			return stub.getRating(path,username);
		} catch (Exception e) {
			String msg = "Failed to perform getRating operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public Collection executeQuery(String path, Map parameters) throws RegistryException {
		try {
			List<String> value = new LinkedList<String>();
			List<String> key = new LinkedList<String>();
			for (Object e : parameters.entrySet()) {
				Map.Entry entry = (Map.Entry)e;
				value.add((String)entry.getValue());
				key.add((String)entry.getKey());
			}
			WSCollection wsCollection =  stub.wSexecuteQuery(path,
			                                                 key.toArray(new String[key.size()]),value.toArray(new String[value.size()]));
			byte[] content = null;
			return WSRegistryClientUtils.transformWSCollectiontoCollection(this, wsCollection, content);

		} catch (Exception e) {
			String msg = "Failed to perform executeQuery operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public LogEntry[] getLogs(String resourcePath,
	                          int action,
	                          String userName,
	                          Date from,
	                          Date to,
	                          boolean recentFirst) throws RegistryException {
		try {
            WSLogEntry[] wsLogEntries;

            if(PaginationContext.getInstance() == null){
                 wsLogEntries = stub.wSgetLogs(resourcePath, action, userName, from, to,
                        recentFirst);

            }else {
                PaginationUtils.copyPaginationContext(stub._getServiceClient());
                wsLogEntries = stub.wSgetLogs(resourcePath, action, userName, from, to,
                        recentFirst);
                int rowCount = PaginationUtils.getRowCount(stub._getServiceClient());
            }
            if(null == wsLogEntries) {
                return  new LogEntry[0];
            }
            LogEntry[] logEntries = new LogEntry[wsLogEntries.length];
            for (int i = 0; i < logEntries.length; i++) {
                logEntries[i] = WSRegistryClientUtils.transformWSLogEntryToLogEntry(wsLogEntries[i]);
            }
            return logEntries;
		} catch (Exception e) {
			String msg = "Failed to perform getLogs operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public  String[] getAvailableAspects() {
		try {
			return stub.getAvailableAspects();
		} catch (Exception e) {
			String msg = "Failed to perform getAvailableAspects operation.";
			log.error(msg, e);
            return new String[0];
		}
	}

	public void associateAspect(String resourcePath, String aspect) throws RegistryException {
		try {
			stub.associateAspect(resourcePath,aspect);
		} catch (Exception e) {
			String msg = "Failed to perform associateAspect operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public  void invokeAspect(String resourcePath, String aspectName, String action) throws RegistryException {
		try {
			stub.invokeAspectNoParam(resourcePath,aspectName,action);
		} catch (Exception e) {
			String msg = "Failed to perform invokeAspect operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public  void invokeAspect(String resourcePath, String aspectName, String action,
                              Map<String, String> parameters) throws RegistryException {
		try {
			Set<String> keys = parameters.keySet();
            java.util.Collection<String> values = parameters.values();
            stub.invokeAspectWithParam(resourcePath,aspectName,action,
                    keys.toArray(new String[keys.size()]),
                    values.toArray(new String[values.size()]));
		} catch (Exception e) {
			String msg = "Failed to perform invokeAspect operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public String[] getAspectActions(String resourcePath, String aspectName) throws RegistryException {
		try {
			return stub.getAspectActions(resourcePath,aspectName);
		} catch (Exception e) {
			String msg = "Failed to perform getAspectActions operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public Collection searchContent(String keyword) throws RegistryException {
		try {
			WSCollection wsCollection =  stub.wSsearchContent(keyword);
			byte[] content = null;
			return WSRegistryClientUtils.transformWSCollectiontoCollection(this, wsCollection, content);
		} catch (Exception e) {
			String msg = "Failed to perform searchContent operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public void createLink(String path, String target) throws RegistryException {
		try {
			stub.createLinkWithSubTarget(path, target, null);
		} catch (Exception e) {
			String msg = "Failed to perform createLink operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public void createLink(String path, String target, String subTargetPath) throws RegistryException {
		try {
			stub.createLinkWithSubTarget(path, target, subTargetPath);
		} catch (Exception e) {
			String msg = "Failed to perform createLink operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public void removeLink(String path) throws RegistryException {
		try {
			stub.removeLink(path);
		} catch (Exception e) {
			String msg = "Failed to perform removeLink operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public String getEventingServiceURL(String path) throws RegistryException {
		try {
			return stub.getEventingServiceURL(path);
		} catch (Exception e) {
			String msg = "Failed to perform getEventingServiceURL operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}
	public void setEventingServiceURL(String path, String serviceURL) throws RegistryException {
		try {
			stub.setEventingServiceURL(path,serviceURL);
		} catch (Exception e) {
			String msg = "Failed to perform setEventingServiceURL operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

	public boolean removeAspect(String name) throws RegistryException {
		try {
			return stub.removeAspect(name);
		} catch (Exception e) {
			String msg = "Failed to perform removeAspect operation.";
			log.error(msg, e);
			throw new RegistryException(msg, e);
		}
	}

    public void removeComment(String comment) throws RegistryException {
        try {
            stub.removeComment(comment);
        } catch (Exception e) {
            String msg = "Failed to perform removeComment operation.";
            log.error(msg, e);
            throw new RegistryException(msg, e);
        }
    }

    /**
     *
     * @param path                Path of the resource
     * @param regVersion          Version ID
     * @return                    Succeed or not
     * @throws RegistryException  If operation fails
     */
    public boolean removeVersionHistory(String path, long regVersion)
    		throws RegistryException {
        try {
            return stub.removeVersionHistory(path, regVersion);
        } catch (Exception e) {
            String msg = "Failed to remove version: " + regVersion + " of the resource " + path;
            log.error(msg, e);
            throw new RegistryException(msg, e);
        }
    }

    public void dumpLite(String s, Writer writer) throws RegistryException {
        // Implementation needs to be added
    }

    public void beginTransaction() throws RegistryException {
    }

    public void commitTransaction() throws RegistryException {
    }

    public void rollbackTransaction() throws RegistryException {
    }

    public String importResource(String suggestedPath, String sourceURL,
                                 org.wso2.carbon.registry.api.Resource resource)
            throws org.wso2.carbon.registry.api.RegistryException {
        return importResource(suggestedPath, sourceURL, (Resource) resource);
    }

    public String addComment(String resourcePath, org.wso2.carbon.registry.api.Comment comment)
            throws org.wso2.carbon.registry.api.RegistryException {
        return addComment(resourcePath, (org.wso2.carbon.registry.core.Comment) comment);
    }

    public String put(String suggestedPath, org.wso2.carbon.registry.api.Resource resource)
            throws org.wso2.carbon.registry.api.RegistryException {
        return put(suggestedPath, (Resource) resource);
    }

    public boolean addAspect(String s, Aspect aspect) throws RegistryException {
        throw new UnsupportedOperationException("This operation is not supported");
    }

    public void dump(String s, Writer writer) throws RegistryException {
        try {
            DataHandler dataHandler = stub.wsDump(s);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(WSRegistryClientUtils.makeBytesFromDataHandler(dataHandler));
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String inputLine;
            while ((inputLine = reader.readLine()) != null) {
                writer.append(inputLine);
            }
            writer.flush();
            reader.close();

        } catch (Exception e) {
            String msg = "Failed to perform dump operation.";
            log.error(msg, e);
            throw new RegistryException(msg, e);
        }
    }

    public void restore(String path, Reader reader) throws RegistryException {
        try {

            BufferedReader bufferedReader = new BufferedReader(reader);

            File tempFile = new File("tempFile");
            tempFile.deleteOnExit();

            FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
            Writer writer = new OutputStreamWriter(fileOutputStream);

            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null) {
                writer.append(inputLine);
            }

            writer.flush();
            fileOutputStream.close();
            writer.close();
            bufferedReader.close();

            DataHandler handler = new DataHandler(new FileDataSource(tempFile));

            stub.wsRestore(path, handler);

            @SuppressWarnings("unused")
            boolean ignored = tempFile.delete();
        } catch (Exception e) {
            String msg = "Failed to perform restore operation.";
            log.error(msg, e);
            throw new RegistryException(msg, e);
        }
    }

    public LogEntryCollection getLogCollection(String s, int i, String s1, Date date, Date date1,
                                               boolean b) throws RegistryException {
        throw new UnsupportedOperationException("This operation is not supported");
    }

    public RegistryContext getRegistryContext() {
        return RegistryContext.getBaseInstance();
    }

    // Used to fetch resource content, on-demand
	public byte[] getContent(String path) throws Exception {
		DataHandler dataHandler = stub.getContent(path);
		return WSRegistryClientUtils.makeBytesFromDataHandler(dataHandler);
	}

	public String[] getCollectionContent(String path) throws Exception {
		return stub.getCollectionContent(path);
	}

    public void setCookie(String cookie) {
        this.cookie = cookie;
    }

    public void setStub(WSRegistryServiceStub stub) {
        this.stub = stub;
    }

    public WSRegistryServiceStub getStub() {
        return stub;
    }

    public void setEpr(String epr) {
        this.epr = epr;
    }
}


text:
package com.evolveum.midpoint.client.impl.restjaxb;

import com.evolveum.midpoint.client.api.Focus;
import com.evolveum.midpoint.client.api.TaskFuture;
import com.evolveum.midpoint.client.api.exception.*;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ExecuteCredentialResetResponseType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ExecuteCredentialResetRequestType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType;

import javax.ws.rs.core.Response;

/**
 *
 * @author Jakmor
 *
 */
public class RestJaxbFocusCredentialService<O extends ObjectType>  extends AbstractObjectWebResource<O> implements Focus<O>
{
    private ExecuteCredentialResetRequestType executeCredentialResetRequest;

    public RestJaxbFocusCredentialService(final RestJaxbService service, final Class<O> type, final String oid)
    {
        super(service, type, oid);
    }

    @Override
    public Focus<O> executeResetPassword(ExecuteCredentialResetRequestType executeCredentialResetRequest)
    {
        this.executeCredentialResetRequest = executeCredentialResetRequest;

        return this;
    }

    @Override
    public TaskFuture<ExecuteCredentialResetResponseType> apost() throws CommonException
    {

        String restPath = RestUtil.subUrl(Types.findType(getType()).getRestPath(), getOid()).concat("/credential");

        Response response = getService().post(restPath, executeCredentialResetRequest);

        switch (response.getStatus()) {
            case 200:
                ExecuteCredentialResetResponseType executeCredentialResetResponse = response.readEntity(ExecuteCredentialResetResponseType.class);
                return new RestJaxbCompletedFuture<>(executeCredentialResetResponse);
            case 409:
                OperationResultType operationResultType = response.readEntity(OperationResultType.class);
                throw new PolicyViolationException(operationResultType.getMessage());
            default:
                throw new UnsupportedOperationException("Implement other status codes, unsupported return status: " + response.getStatus());
        }
    }
}