text:
FOUNDATION_EXPORT double Pods_MDAlert_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_MDAlert_TestsVersionString[];

redpajama_set_name: RedPajamaGithub


text:
(function(API, Utils, DialogWindow) {
  'use strict';

  /**
   * An 'Confirm' dialog
   *
   * @example
   *
   * OSjs.API.createDialog('Confirm', {}, fn);
   *
   * @param  {Object}          args              An object with arguments
   * @param  {String}          args.title        Dialog title
   * @param  {String}          args.message      Dialog message
   * @param  {Array}           args.buttons      Dialog buttons (default=yes,no,cancel)
   * @param  {CallbackDialog}  callback          Callback when done
   *
   * @constructor Confirm
   * @memberof OSjs.Dialogs
   */
  function ConfirmDialog(args, callback) {
    args = Utils.argumentDefaults(args, {
      buttons: ['yes', 'no', 'cancel']
    });

    DialogWindow.apply(this, ['ConfirmDialog', {
      title: args.title || API._('DIALOG_CONFIRM_TITLE'),
      icon: 'status/dialog-question.png',
      width: 400,
      height: 100
    }, args, callback]);
  }

  ConfirmDialog.prototype = Object.create(DialogWindow.prototype);
  ConfirmDialog.constructor = DialogWindow;

  ConfirmDialog.prototype.init = function() {
    var self = this;
    var root = DialogWindow.prototype.init.apply(this, arguments);

    var msg = DialogWindow.parseMessage(this.args.message);
    this.scheme.find(this, 'Message').empty().append(msg);

    var buttonMap = {
      yes: 'ButtonYes',
      no: 'ButtonNo',
      cancel: 'ButtonCancel'
    };

    var hide = [];
    (['yes', 'no', 'cancel']).forEach(function(b) {
      if ( self.args.buttons.indexOf(b) < 0 ) {
        hide.push(b);
      }
    });

    hide.forEach(function(b) {
      self.scheme.find(self, buttonMap[b]).hide();
    });

    return root;
  };

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.Dialogs.Confirm = Object.seal(ConfirmDialog);

})(OSjs.API, OSjs.Utils, OSjs.Core.DialogWindow);


text:
<?xml version="1.0"?>
<RepositoryInfo>
  <Version>1.0</Version>
  <Type>INFO</Type>
  <RepositoryVersion>1.4</RepositoryVersion>
  <GlobalPrefixName>
    <Component ccnbencoding="base64Binary">cGFyYy5jb20=</Component>
    <Component ccnbencoding="base64Binary">Y3Ns</Component>
    <Component ccnbencoding="base64Binary">Y2Nu</Component>
    <Component ccnbencoding="base64Binary">UmVwb3M=</Component>
  </GlobalPrefixName>
  <LocalName>Repository</LocalName>
</RepositoryInfo>


text:
package com.skynav.ttv.model.imsc;

import java.net.URI;
import java.util.Set;

import com.skynav.ttv.model.ttml.TTML2StandardDesignations;
import com.skynav.ttv.util.URIs;

import static com.skynav.ttv.model.imsc.IMSC11.Constants.NAMESPACE_IMSC11_EXTENSION;

public class IMSC11StandardDesignations extends TTML2StandardDesignations {

    private static final String[] extensionDesignationStrings = new String[] {
        "#activeArea",
        "#altText",
        "#aspectRatio",
        "#forcedDisplay",
        "#linePadding",
        "#multiRowAlign",
        "#progressivelyDecodable"
    };

    private Set<URI> extensionDesignations;

    protected IMSC11StandardDesignations() {
        populateExtensionDesignations();
    }

    private void populateExtensionDesignations() {
        URI extensionNamespaceUri = URIs.makeURISafely(NAMESPACE_IMSC11_EXTENSION);
        if (extensionNamespaceUri != null) {
            Set<URI> extensionDesignations = new java.util.HashSet<URI>(extensionDesignationStrings.length);
            for (String designation : extensionDesignationStrings) {
                extensionDesignations.add(extensionNamespaceUri.resolve(designation));
            }
            this.extensionDesignations = extensionDesignations;
        }
    }

    public static IMSC11StandardDesignations getInstance() {
        return new IMSC11StandardDesignations();
    }

    @Override
    public boolean isStandardExtensionDesignation(URI uri) {
        if (super.isStandardExtensionDesignation(uri))
            return true;
        else
            return (extensionDesignations != null) && extensionDesignations.contains(uri);
    }

}


text:
#ifndef __COREFOUNDATION_CFCHARACTERSET_H__
#define __COREFOUNDATION_CFCHARACTERSET_H__

#include <CoreFoundation/CFBase.h>
#include <CoreFoundation/CFData.h>

CF_EXTERN_C_BEGIN

typedef const struct __CFCharacterSet * CFCharacterSetRef;
typedef struct __CFCharacterSet * CFMutableCharacterSetRef;

typedef CFIndex CFCharacterSetPredefinedSet;
enum
{
  kCFCharacterSetControl = 1,
  kCFCharacterSetWhitespace,
  kCFCharacterSetWhitespaceAndNewline,
  kCFCharacterSetDecimalDigit,
  kCFCharacterSetLetter,
  kCFCharacterSetLowercaseLetter,
  kCFCharacterSetUppercaseLetter,
  kCFCharacterSetNonBase,
  kCFCharacterSetDecomposable,
  kCFCharacterSetAlphaNumeric,
  kCFCharacterSetPunctuation,
#if MAC_OS_X_VERSION_10_2 <= MAC_OS_X_VERSION_MAX_ALLOWED
  kCFCharacterSetCapitalizedLetter = 13,
#endif
#if MAC_OS_X_VERSION_10_3 <= MAC_OS_X_VERSION_MAX_ALLOWED
  kCFCharacterSetSymbol = 14,
#endif
#if MAC_OS_X_VERSION_10_5 <= MAC_OS_X_VERSION_MAX_ALLOWED
  kCFCharacterSetNewline = 15,
#endif
  kCFCharacterSetIllegal = 12
};

/*
 * Getting the Character Set Type Identifier
 */
CF_EXPORT CFTypeID
CFCharacterSetGetTypeID (void);

/*
 * Creating Character Sets
 */
#if MAC_OS_X_VERSION_10_3 <= MAC_OS_X_VERSION_MAX_ALLOWED
CF_EXPORT CFCharacterSetRef
CFCharacterSetCreateCopy (CFAllocatorRef alloc, CFCharacterSetRef set);
#endif

#if MAC_OS_X_VERSION_10_2 <= MAC_OS_X_VERSION_MAX_ALLOWED
CF_EXPORT CFCharacterSetRef
CFCharacterSetCreateInvertedSet (CFAllocatorRef alloc, CFCharacterSetRef set);
#endif

CF_EXPORT CFCharacterSetRef
CFCharacterSetCreateWithCharactersInRange (CFAllocatorRef alloc,
  CFRange range);

CF_EXPORT CFCharacterSetRef
CFCharacterSetCreateWithCharactersInString (CFAllocatorRef alloc,
  CFStringRef string);

CF_EXPORT CFCharacterSetRef
CFCharacterSetCreateWithBitmapRepresentation (CFAllocatorRef alloc,
  CFDataRef data);

/*
 * Getting Predefined Character Sets
 */
CF_EXPORT CFCharacterSetRef
CFCharacterSetGetPredefined (CFCharacterSetPredefinedSet setIdentifier);

/*
 * Querying Character Sets
 */
CF_EXPORT CFDataRef
CFCharacterSetCreateBitmapRepresentation (CFAllocatorRef alloc,
  CFCharacterSetRef set);

CF_EXPORT Boolean
CFCharacterSetIsCharacterMember (CFCharacterSetRef set, UniChar c);

#if MAC_OS_X_VERSION_10_2 <= MAC_OS_X_VERSION_MAX_ALLOWED
CF_EXPORT Boolean
CFCharacterSetHasMemberInPlane (CFCharacterSetRef set, CFIndex plane);

CF_EXPORT Boolean
CFCharacterSetIsLongCharacterMember (CFCharacterSetRef set, UTF32Char c);

CF_EXPORT Boolean
CFCharacterSetIsSupersetOfSet (CFCharacterSetRef set,
  CFCharacterSetRef otherSet);
#endif

/*
 * CFMutableCharacterSet
 */
CF_EXPORT CFMutableCharacterSetRef
CFCharacterSetCreateMutable (CFAllocatorRef alloc);

CF_EXPORT CFMutableCharacterSetRef
CFCharacterSetCreateMutableCopy (CFAllocatorRef alloc, CFCharacterSetRef set);

CF_EXPORT void
CFCharacterSetAddCharactersInRange (CFMutableCharacterSetRef set,
  CFRange range);

CF_EXPORT void
CFCharacterSetAddCharactersInString (CFMutableCharacterSetRef set,
  CFStringRef string);

CF_EXPORT void
CFCharacterSetRemoveCharactersInRange (CFMutableCharacterSetRef set,
  CFRange range);

CF_EXPORT void
CFCharacterSetRemoveCharactersInString (CFMutableCharacterSetRef set,
  CFStringRef string);

CF_EXPORT void
CFCharacterSetIntersect (CFMutableCharacterSetRef set,
  CFCharacterSetRef otherSet);

CF_EXPORT void
CFCharacterSetInvert (CFMutableCharacterSetRef set);

CF_EXPORT void
CFCharacterSetUnion (CFMutableCharacterSetRef set, CFCharacterSetRef otherSet);

CF_EXTERN_C_END

#endif /* __COREFOUNDATION_CFCHARACTERSET_H__ */


text:
<?php

namespace Enlighter\filter;

use Enlighter\skltn\HtmlUtil;
use Enlighter\compatibility\Crayon as CrayonCompat;
use Enlighter\compatibility\CodeColorer as CodeColorerCompat;
use Enlighter\compatibility\GenericType1 as GenericType1Compat;
use Enlighter\compatibility\GenericType2 as GenericType2Compat;

class CompatibilityModeFilter{
    // stores the plugin config
    private $_config;

    // internal fragment buffer to store code
    private $_fragmentBuffer;

    public function __construct($config, $fragmentBuffer){
        // store local plugin config
        $this->_config = $config;

        // store fragment buffer
        $this->_fragmentBuffer = $fragmentBuffer;
    }

    // strip the content
    // internal regex function to replace gfm code sections with placeholders
    public function stripCodeFragments($content){

        // generic type1 mode ?
        if ($this->_config['compat-type1']){
            $content = preg_replace_callback(GenericType1Compat::getRegex(), function($match){

                // run convert
                $code = GenericType1Compat::convert($match);

                // generate code; retrieve placeholder
                return $this->_fragmentBuffer->storeFragment($code);

            }, $content);
        }

        // generic type1 mode ?
        if ($this->_config['compat-type2']){
            $content = preg_replace_callback(GenericType2Compat::getRegex(), function($match){

                // run convert
                $code = GenericType2Compat::convert($match);

                // generate code; retrieve placeholder
                return $this->_fragmentBuffer->storeFragment($code);

            }, $content);
        }

        // crayon compat mode ?
        if ($this->_config['compat-crayon']){
            $content = preg_replace_callback(CrayonCompat::getRegex(), function($match){

                // run convert
                $code = CrayonCompat::convert($match);

                // generate code; retrieve placeholder
                return $this->_fragmentBuffer->storeFragment($code);

            }, $content);
        }

        // code colorer compat mode ?
        if ($this->_config['compat-codecolorer']){
            $content = preg_replace_callback(CodeColorerCompat::getRegex(), function($match){

                // run convert
                $code = CodeColorerCompat::convert($match);

                // generate code; retrieve placeholder
                return $this->_fragmentBuffer->storeFragment($code);

            }, $content);
        }

        return $content;
    }

}


text:
'use strict';

const common = require('../common');
if (!common.hasCrypto)
  common.skip('missing crypto');
const assert = require('assert');
const h2 = require('http2');

// Makes sure that Http2ServerResponse setHeader & removeHeader, do not throw
// any errors if the stream was destroyed before headers were sent

const server = h2.createServer();
server.listen(0, common.mustCall(function() {
  const port = server.address().port;
  server.once('request', common.mustCall(function(request, response) {
    response.on('finish', common.mustCall(() => {
      assert.strictEqual(response.headersSent, false);
      response.setHeader('test', 'value');
      response.removeHeader('test', 'value');

      process.nextTick(() => {
        response.setHeader('test', 'value');
        response.removeHeader('test', 'value');

        server.close();
      });
    }));

    response.destroy();
  }));

  const url = `http://localhost:${port}`;
  const client = h2.connect(url, common.mustCall(function() {
    const headers = {
      ':path': '/',
      ':method': 'GET',
      ':scheme': 'http',
      ':authority': `localhost:${port}`
    };
    const request = client.request(headers);
    request.on('end', common.mustCall(function() {
      client.close();
    }));
    request.end();
    request.resume();
  }));
}));


text:
module("ionic_keyboard");

//// In this test we call the example showAlert API method with an example string
//asyncTest("Attempt to show an alert with no text", 1, function() {
//	forge.ionic_keyboard.showAlert("Hello, testing world!", function () {
//		askQuestion("Did you see an alert with the message 'Hello, testing world!'?", {
//			Yes: function () {
//				ok(true, "User claims success");
//				start();
//			},
//			No: function () {
//				ok(false, "User claims failure");
//				start();
//			}
//		});
//	}, function () {
//		ok(false, "API method returned failure");
//		start();
//	});
//});

function cleanUp () {
    $('.clean-me-up').remove();
}

asyncTest("Attempt to hide form assist bar", 1, function () {
    askQuestion("Tap on the input", {
        "Nothing happened": function () {
            ok(false, "User claims failure: nothing happened");
            start();
            cleanUp();
        }
    });
    var form = $('<form class="clean-me-up"><input type="text" placeholder="tap me"/></form>').insertBefore('#qunit');

    $('input', form).on('focus', function () {
        forge.ionic_keyboard.hideKeyboardAccessoryBar(true, function () {
            askQuestion("Is the form assist bar visible?", {
                Yes: function () {
                    ok(false, "User claims failure: form assist visible");
                    start();
                    cleanUp();
                },
                No: function () {
                    ok(true, "User claims success");
                    start();
                    cleanUp();
                }
            });
        }, function (e) {
            ok(false, "User claims failure: "+JSON.stringify(e));
            start();
            cleanUp();
        });
    });
});


text:
// Protection imports
#import <MSRightsManagement/MSRightsManagement.h>
// Custom protection imports
#import <MSRightsManagement/MSCustomProtection.h>

#import <MSRightsManagementUI/MSPolicyViewer.h>
#import <MSRightsManagementUI/MSPolicyPicker.h>
#import <MSRightsManagementUI/MSEmailInputViewController.h>
#import <MSRightsManagementUI/MSResourcesUtils.h>
#import <MSRightsManagementUI/MSEmailInputDelegate.h>

#import <ADALiOS/ADAuthenticationContext.h>

// App imports
#import "MSMainViewController.h"
#import "MSErrorViewer.h"
#import "MSStringEncodingUtils.h"
#import "MSPolicyEnforcer.h"
#import "MSConsentManager.h"

@interface MSMainViewController () <MSPolicyPickerDelegate, MSPolicyViewerDelegate, MSAuthenticationCallback, MSEmailInputDelegate>

@property (strong, nonatomic) MSEmailInputViewController *emailInputViewController;
// Protection related properties
@property (strong, nonatomic) MSPolicyPicker *policyPicker;
@property (strong, nonatomic) MSUserPolicy *userPolicy;
@property (strong, nonatomic) MSPolicyViewer *policyViewer;
@property (strong, nonatomic) MSConsentManager *consentManager;
@property (strong, nonatomic) MSPolicyEnforcer *policyEnforcer;
@property (strong, nonatomic) NSArray *appSupportedRights;
@property (strong, nonatomic) NSString *userId;

// App related properties
@property (strong, nonatomic) UIBarButtonItem *lockBarButtonItem;
@property (strong, nonatomic) NSString *path;
@property (strong, nonatomic) UIBarButtonItem *mailBarButtonItem;
@property (assign) NSStringEncoding stringEncoding;

@end

@implementation MSMainViewController

// Custom Protection consts
static const NSUInteger kDeprecatedAlgAlignement = 16;

// Icon names
static NSString *sLightMailIconPath = @"mail_white.png";
static NSString *sDarkMailIconPath  = @"mail_black.png";
static NSString *sLightLockIconPath = @"lock_white.png";
static NSString *sDarkLockIconPath  = @"lock_black.png";

// Default file name
static NSString *kDefaultTextFileExtension = @"txt";
static NSString *kDefaultProtectedTextFileExtension = @"ptxt";
static NSString *kCustomFileExtension = @"txt2";
static NSString *kDefaultFileName = @"sample";

// Default email messages.
static NSString *sEmailSubject = @"Test email From RMS sample app";
static NSString *sEmailBody    = @"This is an email from the RMS sample app with an attachment";

// Text View access denied message.
static NSString *sNoViewRightsMessage = @"Access denied, Insufficient Rights to view message";

// Text View unsupported file content type.
static NSString *sContentTypeNotSupportedMessage = @"The original file extension is not supported";

static NSString *sUserCancelledAuthenticationMessage = @"Authentication operation was cancelled";

static NSInteger kProtectedFileSelected = 0;
static NSInteger kCustomProtectedFileSelected = 1;

#pragma mark - Protection related methods

// This is a protected document if a user policy exists
- (BOOL)isProtected
{
    return (self.userPolicy != nil);
}

- (void)setupAppSupportedRights
{
    // The list of rights which the application supports
    self.appSupportedRights = @[[MSCommonRights view],
                                [MSEditableDocumentRights edit],
                                [MSEditableDocumentRights extract],
                                [MSCommonRights owner]];
}

// Called by AppDelegate after "Open in..." of ptxt or txt2 attachment - Starts the consumption flow
// Works with both RMS-protected files and plaintext files.
- (void)openURL:(NSURL *)attachmentUrl
{
    NSLog(@"Opening file from url: %@",attachmentUrl);
    // Restore the app to its initial state
    [self cleanup];

    // Hide the keyboard
    [self.txtView resignFirstResponder];
    [self startAnimationAndHideButtons];

    // Dismiss the current policy viewer if it exists
    [self.policyViewer dismiss];

    // If the attachment is a custom protected file
    if ([[attachmentUrl pathExtension] isEqualToString:kCustomFileExtension])
    {
        [self handleCustomProtectedFile:[attachmentUrl path]];
    }
    //----------------------------------------------------------------------
    //
    // *** RMS-specific code ***
    //
    // Code that loads protected files into memory
    //
    //  *  create an MSProtectedData that addresses the entire contents of a file (protected or unprotected)
    //  *  See http://msdn.microsoft.com/en-us/library/windows/desktop/dn758348(v=vs.85).aspx for more details
    //

    [MSProtectedData protectedDataWithProtectedFile:[attachmentUrl path]
                                             userId:self.userId
                             authenticationCallback:self
                                    consentCallback:self.consentManager
                                            options:Default
                                    completionBlock:^(MSProtectedData *data, NSError *error)
     {
         [self updateCurrentProtectionSegmentedControl:data.userPolicy withCustomProtection:NO];
         dispatch_async(dispatch_get_main_queue(),^{
                            [self onConsumptionWithData:data error:error];
         });
     }];
    //
    // *** END RMS-specific code ***
    //
    //------------------------------------------------------------
}

- (void)startPublishingFlow
{
    [self startAnimationAndHideButtons];

    //----------------------------------------------------------------------
    //
    // *** RMS-specific code ***
    //
    //  Code that gets user's templats
    //
    //  *  See http://msdn.microsoft.com/en-us/library/windows/desktop/dn790785(v=vs.85).aspx for more details
    //

    self.policyPicker = [[MSPolicyPicker alloc] init];
    self.policyPicker.policy =  self.userPolicy;
    self.policyPicker.delegate = self;

    if (self.userId != nil)
    {
        [MSTemplateDescriptor templateListWithUserId:self.userId authenticationCallback:self completionBlock:^(NSArray *templates, NSError *error) {

            if (error != nil)
            {
                NSLog(@"Failed to get templates with error: %@", error);
                [[MSErrorViewer sharedInstance] showError:error];
                [self stopAnimationAndShowButtons];
            }
            else
            {
                [self.policyPicker pickTemplateWith:templates];
            }
        }];
    }
    else
    {
        [self showEmailInputView];
    }

    //
    // *** END RMS-specific code ***
    //
    //------------------------------------------------------------
}

#pragma mark - MSEmailInputDelegate

- (void)onEmailInputTappedWithEmail:(NSString *)email completionBlock:(void(^)(BOOL completed))completionBlock
{
    [self.emailInputViewController dismissViewControllerAnimated:YES completion:^{
        completionBlock(YES);
        self.emailInputViewController = nil;

        [MSTemplateDescriptor templateListWithUserId:email authenticationCallback:self completionBlock:^(NSArray *templates, NSError *error) {

            if (error != nil)
            {
                NSLog(@"Failed to get templates with error: %@", error);
                [[MSErrorViewer sharedInstance] showError:error];
                [self stopAnimationAndShowButtons];
            }
            else
            {
                self.userId = email;
                [self.policyPicker pickTemplateWith:templates];
            }
        }];
    }];
}

- (void)handleCustomProtectedFile:(NSString *)path
{
    NSFileHandle *irmFile = [NSFileHandle fileHandleForReadingAtPath:path];

    if (irmFile == nil)
    {
        dispatch_async(dispatch_get_main_queue(),^{
            NSLog(@"Consumption failed, unable to open handle to path %@", path);
            NSError *error = [[NSError alloc] initWithDomain:@"RMS Sample App" code:1 userInfo:nil];
            [[MSErrorViewer sharedInstance] showError:error];
        });
        return;
    }

    // Read header information from protectedData and extract the  PL
    /*-------------------------------------------
     | PL length | PL | ContetSizeLength |
     -------------------------------------------*/
    NSData *plSizeData = [irmFile readDataOfLength:sizeof(NSUInteger)];
    NSUInteger plSize;
    [plSizeData getBytes:&plSize range:NSMakeRange(0, sizeof(NSUInteger))];

    // get the PL and protectedData
    NSData *pl = [irmFile readDataOfLength:plSize];
    NSUInteger protectedContentSize;
    NSData *protectedContentSizeData = [irmFile readDataOfLength:sizeof(NSUInteger)];
    [protectedContentSizeData getBytes:&protectedContentSize range:NSMakeRange(0, sizeof(NSUInteger))];
    __block NSData *protectedData = [irmFile readDataOfLength:protectedContentSize];

    //----------------------------------------------------------------------
    //
    // *** RMS-specific code ***
    //
    // Code that loads custom PL
    //
    //  *  create an MSUserPolicy
    //  *  See http://msdn.microsoft.com/en-us/library/windows/desktop/dn790796(v=vs.85).aspx for more details
    //
    [MSUserPolicy userPolicyWithSerializedPolicy:pl
                                          userId:self.userId
                          authenticationCallback:self
                                 consentCallback:self.consentManager
                                         options:Default
                                 completionBlock:^(MSUserPolicy *userPolicy, NSError *error)
     {
         if (error != nil)
         {
             dispatch_async(dispatch_get_main_queue(),^{
                                [self onConsumptionWithData:nil error:error];
             });
         }
         if (userPolicy == nil)
         {
             dispatch_async(dispatch_get_main_queue(),^{
                 [self onConsumptionWithData:nil error:nil];
             });
         }
         else
         {
             [self updateCurrentProtectionSegmentedControl:userPolicy withCustomProtection:YES];
             // Create the MSCustomProtectedData used for decrypting the content
             // The content start position is the header length
             // The decrypted content size is NSUIntegerMax since the content ends in EOF
             [MSCustomProtectedData customProtectedDataWithPolicy:userPolicy
                                                    protectedData:protectedData
                                             contentStartPosition:0
                                                      contentSize:protectedContentSize
                                                  completionBlock:^(MSCustomProtectedData *customProtectectedData,
                                                                    NSError *error){
                                                      dispatch_async(dispatch_get_main_queue(),^{
                                                          [self onConsumptionWithData:customProtectectedData error:error];
                                                      });

                                                  }];
         }
     }];
}

- (void)onConsumptionWithData:(MSProtectedData *)data error:(NSError *)error
{
    [self stopAnimationAndShowButtons];
    // Note: Need to store the user policy in order to use it with the Policy Viewer
    if (error != nil)
    {
        dispatch_async(dispatch_get_main_queue(),^{
            NSLog(@"Consumption failed with error: %@", error);
            [[MSErrorViewer sharedInstance] showError:error];
        });
        return;
    }
    if (data == nil)
    {
        self.txtView.text = sUserCancelledAuthenticationMessage;
    }
    self.userPolicy = data.userPolicy;
    if([self isProtected])
    {
        if (![self isSupportedFileExtention:data.originalFileExtension])
        {
            self.txtView.text = sContentTypeNotSupportedMessage;
        }
        else
        {
            // Check if the user has the right to view the data
            self.txtView.text = [self.userPolicy accessCheck:[MSCommonRights view]] ?
            [self retrievePlaintextData:data.retrieveData] :
            sNoViewRightsMessage;

            // Use the policy enforcer to protect the Text View which containing the protected content
            self.policyEnforcer = [[MSPolicyEnforcer alloc] initWithProtectionPolicy:self.userPolicy];
            [self.policyEnforcer addRuleToControl:self.txtView
                                      whenNoRight:[MSEditableDocumentRights edit]
                                         doAction:MSEnforcementActionDisableEdit];
        }

        [self showPolicyViewer];
    }
};

//----------------------------------------------------------------------
// *** RMS-specific code ***
//
// Allow users to select a user policy.
//
// Every MSProtectedData has a MSUserPolicy class associated with it.
// Your code should maintain a reference to the MSUserPolicy associated with
// the currently loaded document.  This user policy will be used to enforce
// usage restrictions for the loaded content, for example:
//
//      disabling PRINT functionality if the current user doesn't have the PRINT right
//      disabling EDIT  functionality if the current user doesn't have the EDIT right
//      <...etc...>
//
// See http://msdn.microsoft.com/en-us/library/windows/desktop/dn758257(v=vs.85).aspx for more
// information on usage restrictions.
//
// RMS-aware applications should provide a clearly visible UI mechanism to allow users to initiate
// protection of the current loaded document.  Typical applications will expose this through a
// button with a lock-shaped icon, that we'll call the "ProtectionButton"
//
// This method demonstrates how to handle a user clicking on the ProtectionButton
- (void)onLockButton:(id)sender
{
    // Hide the keyboard
    [self.txtView resignFirstResponder];

    // Protection: The document is not protected and the application will show the policy picker
    // to allow the user to select the protection template to be applied to the document
    if (![self isProtected])
    {
        [self startPublishingFlow];
    }
    // Consumption: The document is already protected thus the application will show the current
    // protection associated with it.
    else
    {
        // Show the policy viewer if it is not displayed
        if (self.policyViewer == nil)
        {
            [self showPolicyViewer];
        }
        // If the policy viewer is displayed, dismiss it
        else
        {
            [self.policyViewer dismiss];
        }
    }
}

//
// *** END RMS-specific code ***
//
//------------------------------------------------------------

//-------------------------------------------------------
// onMailButton
//
// Most applications persist data.  This sample shows how to persist the current loaded content to a file for the purpose
// of "sending" it (e.g., as an attachment to an email).  Similar logic is used for other persistence mechanisms (e.g.,
// saving a file to disk).
//
// This code works with both RMS-protected files and plaintext files.
//
// Note: If the mail button is pressed after opening an attachment -
// the attachment will be published and emailed and not the default file.
- (void)onMailButton:(id)sender
{
    // Hide the keyboard
    [self.txtView resignFirstResponder];
    //------------------------------------------------------------------------------------------------
    // *** RMS-specific code ***
    //
    // Most RMS-aware applications use different file extensions depending on whether the file is protected or not.
    // EXAMPLES:
    //
    // TXT (plain text) PTXT (protected text)
    // JPG (plaintext JPG) PJPG (protected JPG)
    // CSV (plaintext CSV) PCSV (protected CSV)
    // TXT (plain text) TXT2 (custom protected text)
    // <...etc...>
    //
    // Your application should store the original file extension with the protected file so that other application
    // and tools can decrypt it later. In this example, we're protecting a TXT file, so we'll use the ".txt"
    // extension when we create the document's UserPolicy
    //
    // The protected file extension will be .ptxt/.txt2 is the document is protected or .txt if not.
    NSString *fileExtension = kDefaultTextFileExtension;
    if (self.isProtected)
    {
        fileExtension = (self.protectionTypeSegmentedControl.selectedSegmentIndex != kProtectedFileSelected) ?
            kCustomFileExtension :
        kDefaultProtectedTextFileExtension;
    }

    NSString *filePath = [[self.path stringByDeletingPathExtension] stringByAppendingPathExtension:fileExtension];

    if (self.protectionTypeSegmentedControl.selectedSegmentIndex == kProtectedFileSelected || !self.isProtected)
    {
        [self sendFile:filePath];
    }
    else
    {
        [self sendCustomFile:filePath];
    }
    //
    // *** END RMS-specific code ***
    //
    //------------------------------------------------------------
}

- (void)sendFile:(NSString *)filePath
{
    NSData *unprotectedData = [self.txtView.text dataUsingEncoding:self.stringEncoding];

    // Use NSData's category method for protecting the document
    // STEP #4: update code that persists files (e.g., save, send, share, etc)
    //
    //  *  create an MSMutableProtectedData to write content to, which works with both protected and unprotected data
    //  *  See http://msdn.microsoft.com/en-us/library/windows/desktop/dn758325(v=vs.85).aspx for more details
    //
    [unprotectedData protectedDataInFile:filePath
                   originalFileExtension:kDefaultTextFileExtension
                    withUserPolicy:self.userPolicy
                         completionBlock:^(MSMutableProtectedData *data, NSError *error)
     {
         if (error != nil)
         {
             dispatch_async(dispatch_get_main_queue(),^
                            {
                                NSLog(@"Protection failed on file: %@, error: %@", filePath, error);
                                [[MSErrorViewer sharedInstance] showError:error];
                            });
             return;
         }
         //Send the protected content
         [self sendMail:filePath];
     }];
}

// Protects the data and writes it to filePath
// If protection succeeds, attach the protected file to an email and open the email dialog
- (void)sendCustomFile:(NSString*)filePath
{
    NSMutableData *unprotectedData = [NSMutableData dataWithData:[self.txtView.text dataUsingEncoding:NSUTF8StringEncoding]];
    NSMutableData *backingData = [[NSMutableData alloc] init];
    //Get the PL from a given policy
    NSData *pl = [self.userPolicy serializedPolicy];
    NSUInteger protectedContentLength = [MSCustomProtectedData getEncryptedContentLengthWithPolicy:self.userPolicy contentLength:unprotectedData.length];

    // Write header information to backing data including the PL
    //
    // ------------------------------------
    // | PL length | PL | ContetSizeLength |
    // -------------------------------------
    //

    NSUInteger plLength = [pl length];
    [backingData appendData:[NSData dataWithBytes:&plLength length:sizeof(plLength)]];
    [backingData appendData:pl];
    [backingData appendData:[NSData dataWithBytes:&protectedContentLength length:sizeof(protectedContentLength)]];

    NSUInteger headerLength = sizeof(plLength) + plLength + sizeof(protectedContentLength);

    // Use MSMutableCustomProtectedData for protecting the document using cutom protection
    //
    //  *  create an MSMutableCustomProtectedData to write content to
    //  *  See http://msdn.microsoft.com/en-us/library/windows/desktop/dn758321(v=vs.85).aspx for more details
    //
    [MSMutableCustomProtectedData customProtectorWithUserPolicy:self.userPolicy
                                                          backingData:backingData
                                               protectedContentOffset:headerLength
                                                      completionBlock:^(MSMutableCustomProtectedData *customProtectedData, NSError *error)
     {
         if (error == nil)
         {
             [customProtectedData updateData:unprotectedData error:&error];
         }

         if (error != nil)
         {
             dispatch_async(dispatch_get_main_queue(),^
                            {
                                NSLog(@"Protection failed on file: %@, error: %@", filePath, error);
                                [[MSErrorViewer sharedInstance] showError:error];
                            });
             return;
         }
         // ---------------------------------------------------------------------------
         // *** Warning: To avoid data loss and/or corruption, close must be called after writing to your
         // MSMutableCustomProtectedData
         // ---------------------------------------------------------------------------
         [customProtectedData close:&error];
         [backingData writeToFile:filePath atomically:YES];
         [self sendMail:filePath];
     }];
}

#pragma mark - MSPolicyPickerDelegate implementation
// Called after the user selects a template
- (void)didSelectProtection:(MSTemplateDescriptor *)templateDescriptor picker:(MSPolicyPicker *)sender
{
    NSLog(@"User selected a template");
    // put in self PreferDeprecatedAlgorithms
    MSUserPolicyCreationOptions options = None;

    [MSUserPolicy userPolicyWithTemplateDescriptor:templateDescriptor userId:self.userId signedAppData:nil licenseMetadata:nil authenticationCallback:self options:options completionBlock:^(MSUserPolicy *userPolicy, NSError *error) {
        NSLog(@"User policy created");

        BOOL wasPreviouslyProtected = (self.userPolicy != nil);

        // The selected policy is saved
        self.userPolicy = userPolicy;
        [self stopAnimationAndShowButtons];

        // Check if the policy viewer is already visible and if not, display it.
        if (!wasPreviouslyProtected)
        {
            [self showPolicyViewer];
        }
    }];
}

// Called if the user canceled the Pick Policy flow - Causes the activity indicator to be hidden
- (void)didCancelProtection:(MSPolicyPicker *)sender
{
    NSLog(@"User cancelled the protection process");
    [self stopAnimationAndShowButtons];
}

// Called if an error occured in the Policy Picker flow - Log the error and hide the activity indicator
- (void)didFailWithError:(NSError *)error picker:(MSPolicyPicker *)sender
{
    NSLog(@"Failed to pick a protection policy with error: %@", error);
    [[MSErrorViewer sharedInstance] showError:error];
    [self stopAnimationAndShowButtons];
}

// Called after the user clicks the edit permissions in the Policy Viewer and before the Policy Picker is shown
- (void)willShowPolicyPickerView:(MSPolicyPicker *)sender
{
    self.lockBarButtonItem.enabled = NO;
}

// Called after the user dismisses the Policy Picker
- (void)didDismissPolicyPickerView:(MSPolicyPicker *)sender
{
    self.lockBarButtonItem.enabled = YES;
}

#pragma mark - MSPolicyViewerDelegate implementation
// Called after the policy viewer is dismissed
- (void)didDismissPolicyViewer
{
    self.policyViewer = nil;
}

// Called when edit button pressed
- (void)editPermissionsTapped
{
    // Dismiss the policy viewer
    [self.policyViewer dismiss];

    [self startPublishingFlow];
}

#pragma mark - UI methods

// When the view loads, initialize the application for publishing:
// 1. Initialize the list of rights that are supported.
// 2. The buttons need to be initialized programmatically due to two buttons being displayed on the right side of the navigation bar.
// 3. Initialize the default path to the Pfile to the device's documents directory.
// 4. Set focus on text view control to allow editing and show keyboard.
- (void)showEmailInputView
{
    NSLog(@"Presenting an instance of MSEmailInputViewController");

    if (self.emailInputViewController == nil)
    {
        self.emailInputViewController =
        [[MSResourcesUtils storyboard] instantiateViewControllerWithIdentifier:@"MSEmailInputViewController"];
        self.emailInputViewController.delegate = self;
    }

    [self.navigationController presentViewController:self.emailInputViewController animated:YES completion:nil];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setupAppSupportedRights];

    // This class implements MSConsentCallback protocol
    self.consentManager = [[MSConsentManager alloc] initWithMainVC:self];

    // The default encoding for the text is UTF8
    self.stringEncoding = NSUTF8StringEncoding;

    self.mailBarButtonItem = [self barButtonItemWithImageName:sDarkMailIconPath highlightImageName:sLightMailIconPath action:@selector(onMailButton:)];
    self.lockBarButtonItem = [self barButtonItemWithImageName:sDarkLockIconPath highlightImageName:sLightLockIconPath action:@selector(onLockButton:)];

    // Add right buttons to navigation bar
    self.navigationItem.rightBarButtonItems = @[self.lockBarButtonItem, self.mailBarButtonItem];

    // Set the path to the protected file
    self.path = [NSString stringWithFormat:@"%@/%@.%@",
                 [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],
                 kDefaultFileName,
                 kDefaultProtectedTextFileExtension];
    // Set the segmented control to auto resize, so in oreintation change the control will assume all width
    self.protectionTypeSegmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
}

- (void)viewDidAppear:(BOOL)animated
{
    // Observe keyboard show and hide notifications to resize the text view to accommodate the keyboard
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShown:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    [self.activityIndicator setCenter:self.view.center];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Handle Keyboard notifications
- (void)moveTextViewForKeyboard:(NSNotification*)aNotification up:(BOOL)up
{
    NSDictionary* userInfo = [aNotification userInfo];
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect keyboardEndFrame;

    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];

    CGRect newFrame = self.txtView.frame;
    CGRect keyboardFrame = [self.view convertRect:keyboardEndFrame toView:nil];
    newFrame.size.height -= keyboardFrame.size.height * (up ? 1 : -1);
    self.txtView.frame = newFrame;

    [UIView commitAnimations];
}

- (void)keyboardWillShown:(NSNotification*)aNotification
{
    [self moveTextViewForKeyboard:aNotification up:YES];
}

- (void)keyboardWillHide:(NSNotification*)aNotification
{
    [self moveTextViewForKeyboard:aNotification up:NO];
}

#pragma mark - UIViewController protocol
// Called when the view is rotated - used to reposition the activity indicator
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    [self.activityIndicator setCenter:self.view.center];
}

#pragma mark - MFMailComposeViewController protocol
// Called after an email is sent - Logs the result of the operation
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail sent failure: %@", [error localizedDescription]);
            break;
        default:
            break;
    }

    // Close the email Interface
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Private Methods

// Check the original file extension is ".txt" if it is not nil (as it is in custom protection)
- (BOOL)isSupportedFileExtention:(NSString *)extension
{
    return extension == nil ? YES : [extension isEqualToString:[NSString stringWithFormat:@".%@", kDefaultTextFileExtension]];
}

// Update the segemented cotrol to the current onsumed content
- (void)updateCurrentProtectionSegmentedControl:(MSUserPolicy *)userPolicy
                           withCustomProtection:(BOOL)customProtection
{
    if (!customProtection)
    {
        self.protectionTypeSegmentedControl.selectedSegmentIndex = kProtectedFileSelected;
    }
    else
    {
        self.protectionTypeSegmentedControl.selectedSegmentIndex = kCustomProtectedFileSelected;
    }
}

// attach the protected file to an email and open the email dialog
- (void)sendMail:(NSString*)attachmentFilePath
{
    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
        mc.mailComposeDelegate = self;
        [mc setSubject:sEmailSubject];
        [mc setMessageBody:sEmailBody isHTML:NO];
        // If protected file set MIME to be "application/ptext"
        if ([[attachmentFilePath pathExtension] isEqualToString:kDefaultProtectedTextFileExtension] ||
            [[attachmentFilePath pathExtension] isEqualToString:kCustomFileExtension])
        {
            // Note: The attachment needs to have a binary mimeType
            // Emailing the ptxt file with a textual mimeType can cause the file to be corrupted
            [mc addAttachmentData:[NSData dataWithContentsOfFile:attachmentFilePath] mimeType:@"application/ptext" fileName:[attachmentFilePath lastPathComponent]];
        }
        else
        {
            [mc addAttachmentData:[NSData dataWithContentsOfFile:attachmentFilePath] mimeType:@"text/plain" fileName:[attachmentFilePath lastPathComponent]];
        }
        // Dismiss the policy viewer (if it is opened) and present the mail composer view controller
        [self.policyViewer dismiss];
        [self.navigationController presentViewController:mc animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"RMS sample app"
                                                            message:@"Please configure your device to send email"
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];
    }
}

// Initializes and shows the policy viewer
- (void)showPolicyViewer
{
    self.policyViewer = [MSPolicyViewer policyViewerWithUserPolicy:self.userPolicy
                                                supportedAppRights:self.appSupportedRights];
    self.policyViewer.delegate = self;
    [self.policyViewer show];
}

// Restores the application to its original state
// Called at the start of the "Open In" consumption flow
- (void)cleanup
{
    if (self.policyEnforcer != nil)
    {
        [self.policyEnforcer removeAllRulesFromControl:self.txtView];
    }

    self.policyPicker = nil;
    self.userPolicy = nil;
    self.txtView.text = @"";
}

// Create a custom bar button item and return it
- (UIBarButtonItem *)barButtonItemWithImageName:(NSString *)imageName highlightImageName:(NSString *)highlightImageName action:(SEL)action
{
    UIImage *buttonImage = [UIImage imageNamed:imageName];
    UIImage *buttonHighlightImage = [UIImage imageNamed:highlightImageName];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:buttonImage forState:UIControlStateNormal];
    [button setImage:buttonHighlightImage forState:UIControlStateHighlighted];
    button.bounds = CGRectMake(0, 0, buttonImage.size.width + 10, buttonImage.size.height);
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *lockBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

    return lockBarButtonItem;
}

// Starts the progress activity indicator animation
// and hides the Lock and Mail buttons
- (void)startAnimationAndHideButtons
{
    self.lockBarButtonItem.customView.hidden = YES;
    self.mailBarButtonItem.customView.hidden = YES;
    self.activityIndicator.hidden = NO;
    self.txtView.editable = NO;
    [self.activityIndicator startAnimating];
}

// Stops the progress activity indicator animation
// and shows the Lock and Mail buttons
- (void)stopAnimationAndShowButtons
{
    self.lockBarButtonItem.customView.hidden = NO;
    self.mailBarButtonItem.customView.hidden = NO;
    self.protectionTypeSegmentedControl.hidden = NO;
    self.activityIndicator.hidden = YES;
    if (self.userPolicy == nil || [self.userPolicy accessCheck:[MSEditableDocumentRights edit]])
    {
        self.txtView.editable = YES;
    }
    [self.activityIndicator stopAnimating];
}

// Retrieves the decrypted data and converts it to an NSString *
- (NSString *)retrievePlaintextData:(NSData *)plainData
{
    self.stringEncoding = [MSStringEncodingUtils getStringEncoding:plainData];
    return [[NSString alloc] initWithData:plainData encoding:self.stringEncoding];
}

// Authentication Callback using ADAL
- (void)accessTokenWithAuthenticationParameters:(MSAuthenticationParameters *)authenticationParameters completionBlock:(void(^)(NSString *accessToken, NSError *error))completionBlock;
{
    ADAuthenticationError *error;
    ADAuthenticationContext* context = [
                                        ADAuthenticationContext authenticationContextWithAuthority:authenticationParameters.authority
                                        error:&error
                                        ];

    context.validateAuthority = FALSE;
    // Please change these values: appClientId, redirectURI after registering your app
    NSString *appClientId = @"com.microsoft.sampleApp";
    NSURL *redirectURI = [NSURL URLWithString:@"local://authorize"];
    // Retrieve token using ADAL
    [context acquireTokenWithResource:authenticationParameters.resource
                             clientId:appClientId
                          redirectUri:redirectURI
                               userId:self.userId == nil ? authenticationParameters.userId : nil
                      completionBlock:^(ADAuthenticationResult *result) {
                          if (result.status != AD_SUCCEEDED)
                          {
                              if (result.status == AD_USER_CANCELLED)
                              {
                                  NSLog(@"User cancelled auth");
                                  completionBlock(nil, [NSError errorWithDomain:@"sampleAppDomain" code:AUTH_CANCELED userInfo:result.error.userInfo]);
                              }
                              else
                              {
                                  NSLog(@"Auth Failed");
                                  completionBlock(nil, result.error);
                              }
                          }
                          else
                          {
                              completionBlock(result.accessToken, result.error);
                          }
                      }];
}

@end


text:
<?php

namespace Blogger\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Constraints;

/**
 * PostMeta
 *
 * @ORM\Table(name="postmeta")
 * @ORM\Entity(repositoryClass="Blogger\BlogBundle\Entity\Repository\PostMetaRepository")
 *
 */
class PostMeta {

     /**
     * {@inheritdoc}
     *
     * @ORM\Column(name="id", type="bigint", length=20)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;
    /**
     * {@inheritdoc}
     *
     * @ORM\Column(name="metaKey", type="string", length=255, nullable=false, unique=true)
     * @Constraints\NotBlank()
     */
    protected $metaKey;
    /**
     * {@inheritdoc}
     *
     * @ORM\Column(name="metaLabel", type="text", nullable=false)
     */

    protected $metaLabel;
    /**
     * {@inheritdoc}
     *
     * @ORM\Column(name="metaValue", type="text", nullable=true)
     */

    protected $metaValue;
    /**
     * {@inheritdoc}
     *
     * @ORM\ManyToOne(targetEntity="Blog", inversedBy="metas")
     * @ORM\JoinColumn(name="blog_id", referencedColumnName="id")
     */
    protected $blog;

    public function __toString()
    {
        return strval($this->getMetaKey());
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set metaValue
     *
     * @param string $metaValue
     *
     * @return PostMeta
     */
    public function setMetaValue($metaValue)
    {
        $this->metaValue = $metaValue;

        return $this;
    }

    /**
     * Get metaValue
     *
     * @return string
     */
    public function getMetaValue()
    {
        return $this->metaValue;
    }

    /**
     * Set blog
     *
     * @param \Blogger\BlogBundle\Entity\Blog $blog
     *
     * @return PostMeta
     */
    public function setBlog(\Blogger\BlogBundle\Entity\Blog $blog = null)
    {
        $this->blog = $blog;

        return $this;
    }

    /**
     * Get blog
     *
     * @return \Blogger\BlogBundle\Entity\Blog
     */
    public function getBlog()
    {
        return $this->blog;
    }

    /**
     * Set metaKey
     *
     * @param string $metaKey
     *
     * @return PostMeta
     */
    public function setMetaKey($metaKey)
    {
        $this->metaKey = $metaKey;

        return $this;
    }

    /**
     * Get metaKey
     *
     * @return string
     */
    public function getMetaKey()
    {
        return $this->metaKey;
    }

    /**
     * Set metaLabel
     *
     * @param string $metaLabel
     *
     * @return PostMeta
     */
    public function setMetaLabel($metaLabel)
    {
        $this->metaLabel = $metaLabel;

        return $this;
    }

    /**
     * Get metaLabel
     *
     * @return string
     */
    public function getMetaLabel()
    {
        return $this->metaLabel;
    }
}


text:
<?php

namespace App\View\Helper;

class IsActiveTest extends \PHPUnit_Framework_TestCase
{
    protected $_view;

    public function setUp()
    {
        global $application;
        $application->bootstrap();

        $front = \Zend_Controller_Front::getInstance();
        $request = new \Zend_Controller_Request_Http();
        $front->setRequest($request->setControllerName('foo'));

        $this->_view = \Zend_Registry::get('view');
    }

    public function testActiveController()
    {
        $this->assertTrue($this->_view->isActive('foo'));
    }

    public function testNotActiveController()
    {
        $this->assertFalse($this->_view->isActive('bar'));
    }
}


text:
import {getDateFormat, getTimeFormat} from 'src/utils/validate.js'
function createTruncatDateTime (placeholder, defaultReturn, filter) {
    let length = placeholder && placeholder.length || 0;
    return function (dateStr, format) {
        let index = -1;
        let val = (!~(index = format.indexOf(placeholder))) ? defaultReturn : parseInt(dateStr.substr(index, length));
        return typeof filter === 'function' ? filter(val) : val;
    }
}

const truncatDateTime = {
    years: createTruncatDateTime('YYYY', 1970),

    months: createTruncatDateTime('MM', 0, function (val) {
        // months is : 0 ~ 11
        return val === 0 ? 0 : val - 1
    }),
    days: createTruncatDateTime('DD', 1),
    hours: createTruncatDateTime('HH', 0),
    minutes: createTruncatDateTime('mm', 0),
    seconds: createTruncatDateTime('ss', 0)
}

/**
 * string convert to Object
 * @param  {string} val 日期字符串
 * @return {Date} 日期对象
 */
export default (val) => {
    let years, months, days, hours, minutes, seconds;
    let formatDateStr = getDateFormat(val);
    let formatTimeStr = getTimeFormat(val);
    var date = new Date();
    if (formatDateStr) {
        years = truncatDateTime.years(val, formatDateStr);
        months = truncatDateTime.months(val, formatDateStr);
        days = truncatDateTime.days(val, formatDateStr);
        date.setFullYear(years);
        date.setMonth(months);
        date.setDate(days);
    }

    if (formatTimeStr) {
        if (formatDateStr) {
            formatTimeStr = [formatDateStr, formatTimeStr].join(' ');
        }
        hours = truncatDateTime.hours(val, formatTimeStr);
        minutes = truncatDateTime.minutes(val, formatTimeStr);
        seconds = truncatDateTime.seconds(val, formatTimeStr);
        date.setHours(hours);
        date.setMinutes(minutes);
        date.setSeconds(seconds);
    }
    return date;
}


text:
#include <aws/rds/model/DescribeCustomAvailabilityZonesResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>

#include <utility>

using namespace Aws::RDS::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;

DescribeCustomAvailabilityZonesResult::DescribeCustomAvailabilityZonesResult()
{
}

DescribeCustomAvailabilityZonesResult::DescribeCustomAvailabilityZonesResult(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  *this = result;
}

DescribeCustomAvailabilityZonesResult& DescribeCustomAvailabilityZonesResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  const XmlDocument& xmlDocument = result.GetPayload();
  XmlNode rootNode = xmlDocument.GetRootElement();
  XmlNode resultNode = rootNode;
  if (!rootNode.IsNull() && (rootNode.GetName() != "DescribeCustomAvailabilityZonesResult"))
  {
    resultNode = rootNode.FirstChild("DescribeCustomAvailabilityZonesResult");
  }

  if(!resultNode.IsNull())
  {
    XmlNode markerNode = resultNode.FirstChild("Marker");
    if(!markerNode.IsNull())
    {
      m_marker = Aws::Utils::Xml::DecodeEscapedXmlText(markerNode.GetText());
    }
    XmlNode customAvailabilityZonesNode = resultNode.FirstChild("CustomAvailabilityZones");
    if(!customAvailabilityZonesNode.IsNull())
    {
      XmlNode customAvailabilityZonesMember = customAvailabilityZonesNode.FirstChild("CustomAvailabilityZone");
      while(!customAvailabilityZonesMember.IsNull())
      {
        m_customAvailabilityZones.push_back(customAvailabilityZonesMember);
        customAvailabilityZonesMember = customAvailabilityZonesMember.NextNode("CustomAvailabilityZone");
      }

    }
  }

  if (!rootNode.IsNull()) {
    XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
    m_responseMetadata = responseMetadataNode;
    AWS_LOGSTREAM_DEBUG("Aws::RDS::Model::DescribeCustomAvailabilityZonesResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
  }
  return *this;
}


text:
import React from 'react';

function clamp (n, min, max) {
    return Math.max(min, Math.min(max, n));
}

export class RadialProgress extends React.Component {

    constructor() {
        super();
        this.initialize = this.initialize.bind(this);
        this.generatePath = this.generatePath.bind(this);
        this.setInterval = this.setInterval.bind(this);
        this.state = {value: 0};
    }

    setInterval() {
        clearInterval(this.interval);
        this.interval = setInterval(() => {
            if (this.state.value < this.props.value) {
                this.setState({value: this.state.value + this.props.progressRate});
            } else {
                clearInterval(this.interval);
            }
        }, 1000/this.props.fps);
    }

    initialize() {
        if (this.props.animated) {
            this.setInterval();
        } else {
            this.setState({value: this.props.value});
        }
    }

    componentDidMount() {
        this.initialize();
    }

    componentWillUnmount() {
        if (this.props.animated) clearInterval(this.interval);
    }

    componentWillReceiveProps() {
        this.setState({value: 0}, this.initialize);
    }

    generatePath(degrees) {
        const radius = this.props.radius;
        const radians = (degrees * Math.PI / 180);
        var x = Math.sin(radians) * radius;
        var y = Math.cos(radians) * -radius;
        const halfEdgeSize = this.props.edgeSize/2;
        x += halfEdgeSize;
        y += halfEdgeSize;
        const largeArcSweepFlag = degrees > 180 ? 1 : 0;
        const startX = halfEdgeSize;
        const startY = halfEdgeSize - radius;
        return `M${startX},${startY} A${radius},${radius} 0 ${largeArcSweepFlag} 1 ${x},${y} `;
    }

    render() {

        const center = this.props.edgeSize / 2;
        const radius = this.props.radius;
        let degrees, text = '';
        if (this.props.unit === 'percent') {
            let percent = clamp(this.state.value, 0, 100);
            degrees = percent / 100  * 360;
            degrees = clamp(degrees, 0, 359.9);
            text = this.props.formatText(percent)
        } else {
            degrees = this.state.value;
            degrees = clamp(degrees, 0, 359.9);
            text = this.props.formatText(degrees)
        }

        const pathDescription = this.generatePath(degrees);

        return (
            <svg height={this.props.edgeSize} width={this.props.edgeSize}>
                <circle cx={center} cy={center} r={radius}
                        stroke={this.props.circleStroke}
                        strokeWidth={this.props.circleStrokeWidth}
                        fill={this.props.circleFill}/>
                <path d={pathDescription}
                      fill="transparent"
                      stroke={this.props.progressStroke}
                      strokeWidth={this.props.circleStrokeWidth}/>
                {
                    this.props.displayText &&
                    <text x={center} y={center} textAnchor="middle">{text}</text>
                }
            </svg>
        );
    }
}

RadialProgress.defaultProps = {
    edgeSize: 100,
    radius: 45,
    circleStrokeWidth: 4,
    circleStroke: '#D8D8D8',
    circleFill: 'transparent',
    progressStroke: 'black',
    unit: 'degrees',
    displayText: true,
    formatText: (value) => value,
    animated: true,
    fps: 60,
    progressRate: 1
};

RadialProgress.propTypes = {
    edgeSize: React.PropTypes.number.isRequired,
    radius: React.PropTypes.number.isRequired,
    circleStrokeWidth: React.PropTypes.number.isRequired,
    circleStroke: React.PropTypes.string.isRequired,
    circleFill: React.PropTypes.string.isRequired,
    progressStroke: React.PropTypes.string.isRequired,
    value: React.PropTypes.number.isRequired,
    unit: React.PropTypes.oneOf(['degrees', 'percent']).isRequired,
    displayText: React.PropTypes.bool.isRequired,
    formatText: React.PropTypes.func,
    animated: React.PropTypes.bool.isRequired,
    fps: React.PropTypes.number.isRequired,
    progressRate: React.PropTypes.number.isRequired
};

export default RadialProgress;


text:
package umbrella.map.instruction;

import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import umbrella.map.IMap;

/**
 * @author Johannes Donath <johannesd@evil-co.com>
 * @copyright Copyright (C) 2014 Evil-Co <http://www.evil-co.com>
 */
@RequiredArgsConstructor
public class GenericInvokeDynamicMethodNameInstruction implements IInvokeDynamicMethodNameMapInstruction {

	/**
	 * Stores the method name.
	 */
	@Getter
	@NonNull
	private final String name;

	/**
	 * Stores the method description.
	 */
	@Getter
	private final String description;

	/**
	 * Constructs a new GenericInvokeDynamicMethodNameInstruction instance.
	 * @param serialized The serialized instruction.
	 */
	public GenericInvokeDynamicMethodNameInstruction (String serialized) {
		int nameEnd = serialized.indexOf (':');

		// split
		this.name = serialized.substring (0, nameEnd);
		this.description = serialized.substring ((nameEnd + 1));
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public IMapInstruction getInverse (IMap map) {
		return (new GenericInvokeDynamicMethodNameInstruction (map.mapInvokeDynamicMethodName (name, description), map.mapDescription (description)));
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String serialize () {
		return this.name + ":" + this.description;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean equals (Object obj) {
		// check basics
		if (obj == null) return false;
		if (!(obj instanceof IInvokeDynamicMethodNameMapInstruction)) return false;

		// cast
		IInvokeDynamicMethodNameMapInstruction instruction = ((IInvokeDynamicMethodNameMapInstruction) obj);

		// check values
		return (
			((this.name == null && instruction.getName () == null) || this.name.equals (instruction.getName ())) &&
			(this.description == null || instruction.getDescription () == null || this.description.equals (instruction.getDescription ()))
		);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int hashCode () {
		return ((this.name != null ? this.name.hashCode () : 0) + (this.description != null ? this.description.hashCode () : 0) + 1000);
	}
}


text:
require 'httparty'

module Rlaunchpadlib
  #
  # bewitchingme: Added an option to ensure the resulting hash uses symbols for keys;
  # default behavior remains the same.
  #
  # Rlaunchpadlib::ProjectGroup.new 'group', {:fast_hash => true}
  class ProjectGroup

        include HTTParty

        attr_accessor :group
        attr_accessor :overview_data
        attr_accessor :opts

        def initialize(group, options = {})
          @opts = options
          @group = group
          @client = Rlaunchpadlib::Client.new @opts
        end

        def overview
            if @overview_data.nil?
                @overview_data = @client.get(@group)
            end
            @overview_data
        end

        def bugs
            @client.get(@group, 'searchTasks')
        end

        def merge_proposals
            @client.get(@group, 'getMergeProposals')
        end

        def branches
            @client.get(@group, 'getBranches')
        end

        # I'm nuts so lets patch method missing.
        def method_missing(name, *args, &block)
          key = @opts[:fast_hash] ? name : name.to_s
          overview.has_key?(key) ? overview[key] : super
        end

    end
end


text:
package org.apache.drill.exec.pigparser.util;

import org.apache.drill.common.logical.FormatPluginConfig;
import org.apache.drill.common.logical.PlanProperties;
import org.apache.drill.exec.store.dfs.FileSystemConfig;
import org.apache.drill.exec.store.easy.text.TextFormatPlugin;
import org.apache.pig.newplan.logical.relational.LOLoad;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PigParserUtil {
    static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(PigParserUtil.class);
    private static Map<String, String> delimMap = new HashMap<>();

    public enum PigExecType{
        LOCALFILE, HDFS
    }

    static{
        delimMap = new HashMap<>();
        delimMap.put(",", "csv");
        delimMap.put("\t", "tsv");
        delimMap.put("|", "psv");
    }

    public static PlanProperties getPlanProperties(Class caller) {
        PlanProperties planProperties = PlanProperties.builder()
                .generator(caller.getName(), "drill-pig-parser")
                .version(1)
                .type(PlanProperties.PlanType.APACHE_DRILL_LOGICAL)
                .build();
        return planProperties;
    }

    // TODO: Only handles text format from filesystem for now
    public static FileSystemConfig getStorageConfig(Map<String, FormatPluginConfig> pluginformats, PigExecType exectype) {
        FileSystemConfig config = new FileSystemConfig();

        switch(exectype){
            case LOCALFILE:config.connection = "file:///"; break;
            case HDFS: config.connection = "hdfs:///"; break; //TODO: ADD HDFS workspaces
            default: config.connection = null;
        }

        config.formats = pluginformats;
        return config;
    }

    // TODO: Only handles text format from filesystem for now
    public static FormatPluginConfig createFormatPluginConfig(String delim) {
        TextFormatPlugin.TextFormatConfig textconfig = new TextFormatPlugin.TextFormatConfig();
        List<String> extensions = new ArrayList<>();
        textconfig.delimiter = delim;
        extensions.add(delimMap.get(delim));
        textconfig.extensions = extensions;

        return textconfig;
    }

    public static String getDelimiterName(String delim){
        if(! delimMap.containsKey(delim)) {
            return "delim" + delim;
        }
        else{
            return delimMap.get(delim);
        }
    }

    public static String getDelimiterName(LOLoad op){
        String[] args = op.getFileSpec().getFuncSpec().getCtorArgs();
        if(args == null){
            return delimMap.get("\t"); // Default delim for PigStorage
        }
        else{
            return getDelimiterName(args[0]);
        }
    }

    public static String getDelimiter(LOLoad op){
        String[] args = op.getFileSpec().getFuncSpec().getCtorArgs();
        return ((args == null) ? "\t" : args[0]);
    }
}