text:
#CFile for Yii Framework.
This extension offers commonly used functions for filesystem objects (files and directories) manipulation.

Project page
[http://github.com/idlesign/ist-yii-cfile](http://github.com/idlesign/ist-yii-cfile)

Report bugs to
[http://github.com/idlesign/ist-yii-cfile/issues](http://github.com/idlesign/ist-yii-cfile/issues)

###Properties
* exists
* isdir
* isfile
* isempty
* isuploaded
* readable
* writeable
* realpath
* basename (setter available)
* filename (setter available)
* dirname
* extension (setter available)
* mimeType
* timeModified
* size
* owner (setter available)
* group (setter available)
* permissions (setter available)

###Methods
* Create
* CreateDir
* Purge
* Contents
* Copy
* Rename/Move
* Send/Download
* Delete

#Changelog

###August 3, 2011
* 0.9
  * fix: getSize() always returning formatted value (spotted by soulge)
  * fix: getSize() returning null when format set to False (spotted by iceblock)
  * fix: fail to determine mime type by extension when extension is not lowercased  (closes #4)

###August 20, 2010
* 0.8
  * new: 'serverHandled' parameter in send() & download() methods allows sending [even huge] files with great speed
  * fix: be PHP 5.1+ compatible (proposed by heyhoo)
  * fix: permissions set incorrectly (spotted by heyhoo)

###June 16, 2010
* 0.7
  * new: 'flags' argument for setContents() method (proposed by TeKi)
  * fix: parameter type checks (for 'posix_getpwuid' & 'posix_getgrgid' functions) added to getOwner and getGroup methods (spotted by Spyros)

###December 8, 2009
* 0.6
  * new: set() method now supports Yii path aliases (proposed by Spyros)
  * chg: getContents() method now has 'filter' parameter to return filtered directory contents (regexp supported)
  * fix: undefined 'uploaded' variable in set() method (spotted by jerry2801)

###November 22, 2009
* 0.5
  * new: Uploaded files support (through CUploadedFile Yii class)
  * new: 'isUploaded' property
  * chg: getContents() method now has 'recursive' parameter for directories
  * fix: always recursive dirContents() method behaviour changed to appropriate

###November 3, 2009
* 0.4
  * new: 'isFile' & 'isDir' properties
  * new: rename(), move(), copy(), delete(), getSize() and getContents() methods now are able to deal with directories
  * new: purge() method to empty filesystem object
  * new: createDir() method to create directory
  * new: 'isEmpty' property
  * chg: 'formatPrecision' param of getSize() method now changed to 'format' and accepts format pattern for 'CNumberFormatter'
  * chg: download() method is now alias for primary send() method
  * chg: now 'readable' & 'writeable' properties are loaded on set() even when in non-greedy mode
  * fix: unnecessary file availability checks when 'greedy' option is specified for set() removed

###October 27, 2009
* 0.3
  * new: setBasename() method (lazy file rename)
  * new: setFilename() method (lazy file rename)
  * new: setExtension() method (lazy file rename)
  * new: download() method
  * chg: copy() & rename() methods improved (destination file name without path is enough for them to perform actions in the current file directory)
  * fix: 'extension' key existance check (in pathInfo())

###October 26, 2009
* 0.2
  * new: getContents() and setContents() methods
  * new: create() method
  * new: 'readable' & 'writeable' properties
  * fix: posix family functions existance check (in getOwner() & getGroup())

###October 25, 2009
* 0.1 Initial release.

#Documentation

###Requirements
Yii 1.0 or above

###Installation
Extract the release file under `protected/extensions/file`

###Usage
Introduce CFile to Yii.
Add definition to CWebApplication config file (main.php)

    'components'=>array(
        ...
        'file'=>array(
            'class'=>'application.extensions.file.CFile',
        ),
        ...
    ),

Now you can access CFile properties and methods as follows:

    $myfile = Yii::app()->file->set('files/test.txt', true);
    /*
      We use set() method to link new CFile object to our file
      First set() parameter - 'files/test.txt' - is the file path (here we supply
      relative path wich is automatically converted into real file path such as
      '/var/www/htdocs/files/test.txt').
      Second set() parameter - true - tells CFile to get all file properties at the
      very beginning (it could be omitted if we don't need all of them).
      $myfile now contains CFile object, let's see what do we got there
    */
    var_dump($myfile); // you may dump object to see all its properties

    echo $myfile->size; // or get property

    $myfile->permissions=755; // or set property

    $mynewfile = $myfile->copy('test2.txt'); // or manipulate file somehow, eg. copy
    // See CFile methods for actions available.

    /*
    Now $mynewfile contains new CFile object
    In this example file 'test2.txt' created in the same directory as our first 'test.txt' file
    */

    /* The following is also valid */
    if (Yii::app()->file->set('files/test3.txt')->exists)
        echo 'Bingo-bongo!';
    else
        echo 'No-no-no.';

    /*
    Since 0.5 you can manipulate uploaded files (through CUploadedFile Yii class).

    Let's suppose that we have the following form in our html:

      <form enctype="multipart/form-data" method="post">
        <input type="file" name="myupload"/>
        <input type="submit"/>
      </form>

    After the form is submitted we can handle uploaded file as usual.
    */
    $uploaded = Yii::app()->file->set('myupload');

    // Let's copy newly uploaded file into 'files' directory with its original name.
    $newfile = $uploaded->copy('files/'.$uploaded->basename);

    /*
    Since 0.6 you can use Yii path aliases.
    See http://www.yiiframework.com/doc/guide/basics.namespace for information
    about path aliases.

    Now let's get the contents of the directory where CFile resides
    (supposing that it is in Yii extensions path in the 'file' subdirectory).
    */
    $cfileDir = Yii::app()->file->set('ext.file');
    print_r($cfileDir->contents);

    /*
    Directory contents filtering was also introduced in 0.6.

    Futher we get all php files from $cfileDir mentioned above.
    We do not need all the decendants (recursion) so we supply 'false' as the first parameter
    for getContents() method.
    The second parameter describes filter, i.e. let me see only 'php' files.
    You can supply an array of rules (eg. array('php', 'txt')).
    NB: Moreover you can define perl regular expressions as rules.
    */
    print_r($cfileDir->getContents(false, 'php'));

    /*
    Since 0.8 you can boost up file downloads.
    Feature requires 'x-sendfile' header support from server (eg. Apache with mod_xsendfile or lighttpd).
    If CFile::download() second parameter ('serverHandled') is set to True file download uses server internals.
    */
    $myfile->download('myfastfile.txt', true);

###Usage hint
The other way to use this class is to import it into Yii:

    Yii::import('application.extensions.file.CFile');

    if (CFile::set('files/test3.txt')->exists)
        echo 'Bingo-bongo!';
    else
        echo 'No-no-no.';

###Further reading
Detailed information about class properties and methods could be found in CFile.php source code.


text:
// --------------------------------------------------------------------------------------------------------------------
//
//   The related posts.
//
// --------------------------------------------------------------------------------------------------------------------

namespace App_Code.Controls
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Web;
    using System.Web.UI;

    using BlogEngine.Core;

    using Resources;

    ///
    /// The related posts.
    ///
    public class RelatedPosts : Control
    {
        #region Constants and Fields

        ///
        /// The cache.
        ///
        private static readonly Dictionary<Guid, Dictionary<Guid, string>> _RelatedPostsCache = new Dictionary<Guid, Dictionary<Guid, string>>();

        ///
        /// The description max length.
        ///
        private int descriptionMaxLength = 100;

        ///
        /// The headline.
        ///
        private string headline = labels.relatedPosts;

        ///
        /// The max results.
        ///
        private int maxResults = 3;

        #endregion

        #region Constructors and Destructors

        ///
        /// Initializes static members of the <see cref="RelatedPosts"/> class.
        ///
        static RelatedPosts()
        {
            Post.Saved += PostSaved;
        }

        #endregion

        #region Properties

        private readonly static object _SyncRoot = new object();
        private static Dictionary<Guid, string> RelatedPostsCache
        {
            get
            {
                Blog currentInstance = Blog.CurrentInstance;
                if (!_RelatedPostsCache.ContainsKey(currentInstance.Id))
                {
                    lock (_SyncRoot)
                    {
                        if (!_RelatedPostsCache.ContainsKey(currentInstance.Id))
                        {
                            _RelatedPostsCache[currentInstance.Id] = new Dictionary<Guid, string>();
                        }
                    }
                }

                return _RelatedPostsCache[currentInstance.Id];
            }
        }

        ///
        /// Gets or sets DescriptionMaxLength.
        ///
        public int DescriptionMaxLength
        {
            get
            {
                return this.descriptionMaxLength;
            }

            set
            {
                this.descriptionMaxLength = value;
            }
        }

        ///
        /// Gets or sets Headline.
        ///
        public string Headline
        {
            get
            {
                return this.headline;
            }

            set
            {
                this.headline = value;
            }
        }

        ///
        /// Gets or sets Item.
        ///
        public IPublishable Item { get; set; }

        ///
        /// Gets or sets MaxResults.
        ///
        public int MaxResults
        {
            get
            {
                return this.maxResults;
            }

            set
            {
                this.maxResults = value;
            }
        }

        ///
        /// Gets or sets a value indicating whether ShowDescription.
        ///
        public bool ShowDescription { get; set; }

        #endregion

        #region Public Methods

        ///
        /// Outputs server control content to a provided <see cref="T:System.Web.UI.HtmlTextWriter"></see> object and stores tracing information about the control if tracing is enabled.
        ///
        /// <param name="writer">
        /// The <see cref="T:System.Web.UI.HtmlTextWriter"></see> object that receives the control content.
        /// </param>
        public override void RenderControl(HtmlTextWriter writer)
        {
            if (!BlogSettings.Instance.EnableRelatedPosts || this.Item == null)
            {
                return;
            }

            if (!RelatedPostsCache.ContainsKey(this.Item.Id))
            {
                var relatedPosts = Search.FindRelatedItems(this.Item);
                if (relatedPosts.Count <= 1)
                {
                    return;
                }

                this.CreateList(relatedPosts);
            }

            writer.Write(RelatedPostsCache[this.Item.Id].Replace("+++", this.Headline));
        }

        #endregion

        #region Methods

        ///
        /// Handles the Saved event of the Post control.
        ///
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="BlogEngine.Core.SavedEventArgs"/> instance containing the event data.</param>
        private static void PostSaved(object sender, SavedEventArgs e)
        {
            if (e.Action != SaveAction.Update)
            {
                return;
            }

            var post = (Post)sender;
            if (RelatedPostsCache.ContainsKey(post.Id))
            {
                RelatedPostsCache.Remove(post.Id);
            }
        }

        ///
        /// Creates the list of related posts in HTML.
        ///
        /// <param name="relatedPosts">
        /// The related posts.
        /// </param>
        private void CreateList(IEnumerable<IPublishable> relatedPosts)
        {
            var sb = new StringBuilder();

            const string LinkFormat = "{1}";
            const string DescriptionFormat = "{0}";
            sb.Append("
");
            sb.Append("
+++
");
            sb.Append("
");

            var count = 0;
            foreach (var post in relatedPosts)
            {
                if (post != this.Item)
                {
                    sb.Append(string.Format(LinkFormat, post.RelativeLink, HttpUtility.HtmlEncode(post.Title)));
                    if (this.ShowDescription)
                    {
                        var description = post.Description;
                        if (description != null && description.Length > this.DescriptionMaxLength)
                        {
                            description = string.Format("{0}...", description.Substring(0, this.DescriptionMaxLength));
                        }

                        if (String.IsNullOrEmpty(description))
                        {
                            var content = Utils.StripHtml(post.Content);
                            description = content.Length > this.DescriptionMaxLength
                                              ? string.Format("{0}...", content.Substring(0, this.DescriptionMaxLength))
                                              : content;
                        }

                        sb.Append(string.Format(DescriptionFormat, description));
                    }

                    count++;
                }

                if (count == this.MaxResults)
                {
                    break;
                }
            }

            sb.Append("
");
            sb.Append("
");
            RelatedPostsCache[this.Item.Id] = sb.ToString();
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace MusicBox\Controller;

use MusicBox\Entity\User;
use MusicBox\Form\Type\UserType;
use Silex\Application;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;

class AdminUserController
{
    public function indexAction(Request $request, Application $app)
    {
        // Perform pagination logic.
        $limit = 10;
        $total = $app['repository.user']->getCount();
        $numPages = ceil($total / $limit);
        $currentPage = $request->query->get('page', 1);
        $offset = ($currentPage - 1) * $limit;
        $users = $app['repository.user']->findAll($limit, $offset);

        $data = array(
            'users' => $users,
            'currentPage' => $currentPage,
            'numPages' => $numPages,
            'here' => $app['url_generator']->generate('admin_users'),
        );
        return $app['twig']->render('admin_users.html.twig', $data);
    }

    public function addAction(Request $request, Application $app)
    {
        $user = new User();
        $form = $app['form.factory']->create(new UserType(), $user);

        if ($request->isMethod('POST')) {
            $form->bind($request);
            if ($form->isValid()) {
                $app['repository.user']->save($user);
                $message = 'The user ' . $user->getUsername() . ' has been saved.';
                $app['session']->getFlashBag()->add('success', $message);
                // Redirect to the edit page.
                $redirect = $app['url_generator']->generate('admin_user_edit', array('user' => $user->getId()));
                return $app->redirect($redirect);
            }
        }

        $data = array(
            'form' => $form->createView(),
            'title' => 'Add new user',
        );
        return $app['twig']->render('form.html.twig', $data);
    }

    public function editAction(Request $request, Application $app)
    {
        $user = $request->attributes->get('user');
        if (!$user) {
            $app->abort(404, 'The requested user was not found.');
        }
        $form = $app['form.factory']->create(new UserType(), $user);

        if ($request->isMethod('POST')) {
            $previousPassword = $user->getPassword();
            $form->bind($request);
            if ($form->isValid()) {
                // If an empty password was entered, restore the previous one.
                $password = $user->getPassword();
                if (!$password) {
                    $user->setPassword($previousPassword);
                }

                $app['repository.user']->save($user);
                $message = 'The user ' . $user->getUsername() . ' has been saved.';
                $app['session']->getFlashBag()->add('success', $message);
            }
        }

        $data = array(
            'form' => $form->createView(),
            'title' => 'Edit user ' . $user->getUsername(),
        );
        return $app['twig']->render('form.html.twig', $data);
    }

    public function deleteAction(Request $request, Application $app)
    {
        $user = $request->attributes->get('user');
        if (!$user) {
            $app->abort(404, 'The requested user was not found.');
        }

        $app['repository.user']->delete($user->getId());
        return $app->redirect($app['url_generator']->generate('admin_users'));
    }
}


text:
package routines.system;

public interface IPersistableComparableLookupRow<R> extends IPersistableLookupRow<R>, Comparable<R> {

}


text:
package com.painless.clock.service;

import android.os.Handler;

import com.painless.clock.Globals;

import java.io.RandomAccessFile;

public final class CpuService implements Runnable, RService {

	private static final long REFRESH_RATE = 5000;	// 5 seconds.

	private final Handler updateHandler;

	// keep these static to prevent restart
	private static long lastTotal = -1, lastIdle = -1;

	private boolean running = false;

	public CpuService() {
		updateHandler = new Handler();
	}

	@Override
	public void run() {
		try {
			final RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
			String line = reader.readLine();
			reader.close();

			line = line.split(" ", 2) [1];
			final String values[] = line.trim().split(" ");

			final long idle = Long.parseLong(values[3]);
			long total = 0;
			for (int i=0; i<values.length; i++) {
				total += Long.parseLong(values[i]);
			}

			if (lastTotal > 0) {
				final long idleD = idle - lastIdle;
				final long totalD = total - lastTotal;
				Globals.cpuUsage = (int) (1000 * (totalD - idleD) / totalD + 5) / 10;
				Globals.cpuUsageAngle = (int) (2880 * (totalD - idleD) / totalD + 5) / 10 - 144;	// angle in 288
			}
			lastIdle = idle;
			lastTotal = total;
		} catch (final Exception e) { }

		updateHandler.removeCallbacks(this);
		if (running) {
			updateHandler.postDelayed(this, REFRESH_RATE);
		}
	}

	@Override
	public void stop() {
		updateHandler.removeCallbacks(this);
		running = false;
//		Debug.log("CpuService stopped");
	}

	@Override
	public void start() {
		running = true;
//		Debug.log("CpuService started");
		run();
	}
}


text:
Test for scream support (HTML)
--INI--
xdebug.default_enable=1
xdebug.auto_trace=0
xdebug.scream=0
error_reporting(E_ALL);
html_errors=1
xdebug.file_link_format=xdebug://%f@%l
xdebug.force_error_reporting=0
--FILE--
<?php
echo @strstr(), "\n";
ini_set('xdebug.scream', 1);
echo @strstr(), "\n";
ini_set('xdebug.scream', 0);
echo @strstr(), "\n";
?>
--EXPECTF--

( ! ) SCREAM: Error suppression ignored for

( ! ) Warning: %s in %sscream_html.php on line 4

Call Stack

#	Time	Memory	Function	Location

1	%f	%d	{main}(  )	.../scream_html.php:0

2	%f	%d	strstr
(  )	.../scream_html.php:4


text:
package com.adobe.acs.commons.replication.status.impl;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

import com.adobe.acs.commons.replication.status.ReplicationStatusManager;
import com.adobe.acs.commons.util.WorkflowHelper;
import com.day.cq.workflow.WorkflowSession;
import com.day.cq.workflow.exec.WorkItem;
import com.day.cq.workflow.exec.WorkflowData;
import com.day.cq.workflow.metadata.MetaDataMap;

import junitx.util.PrivateAccessor;

public class SetReplicationStatusProcessTest {

    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    @Mock
    WorkflowHelper workflowHelper;

    @Mock
    ReplicationStatusManager replicationStatusManager;

    @Mock
    WorkItem workItem;

    @Mock
    WorkflowSession workflowSession;

    @Mock
    MetaDataMap metadataMap;

    @Mock
    ResourceResolver resourceResolver;

    @Mock
    WorkflowData workflowData;

    @Mock
    Resource payloadResource;

    String workflowPayload = "/content/workflow-payload";

    @Spy
    SetReplicationStatusProcess setReplicationStatusProcess = new SetReplicationStatusProcess();

    @Before
    public void setUp() throws Exception {
        when(workflowHelper.getResourceResolver(workflowSession)).thenReturn(resourceResolver);

        when(workItem.getWorkflowData()).thenReturn(workflowData);
        when(workflowData.getPayload()).thenReturn(workflowPayload);

        when(replicationStatusManager.getReplicationStatusResource(workflowPayload, resourceResolver)).thenReturn(payloadResource);
        when(payloadResource.getPath()).thenReturn(workflowPayload);

        PrivateAccessor.setField(setReplicationStatusProcess, "workflowHelper", workflowHelper);
        PrivateAccessor.setField(setReplicationStatusProcess, "replStatusMgr", replicationStatusManager);
    }

    @Test
    public void testUpdateStatusWithProvidedParams() throws Exception {
        String workflowParams = "replicationDate=2017-04-21T15:02" + System.lineSeparator();
        workflowParams += "replicatedBy=customUser" + System.lineSeparator();
        workflowParams += "replicationAction=ACTIVATED";

        when(metadataMap.get(WorkflowHelper.PROCESS_ARGS, "")).thenReturn(workflowParams);

        setReplicationStatusProcess.execute(workItem, workflowSession, metadataMap);

        CalendarMatcher calMatch = new CalendarMatcher("2017-04-21T15:02");

        verify(replicationStatusManager).setReplicationStatus(any(), eq("customUser"), argThat(calMatch), eq(ReplicationStatusManager.Status.valueOf("ACTIVATED")), eq(workflowPayload));
    }

    @Test
    public void testNoReplicationActionDoesNotUpdateStatus() throws Exception {
        String workflowParams = "";
        when(metadataMap.get(WorkflowHelper.PROCESS_ARGS, "")).thenReturn(workflowParams);

        setReplicationStatusProcess.execute(workItem, workflowSession, metadataMap);

        verify(replicationStatusManager, never()).setReplicationStatus(any(), any(), any(), any(), anyString());
    }

    @Test
    public void testDefaultReplicationUserAndDate() throws Exception {
        String workflowParams = "replicationAction=ACTIVATED";
        when(metadataMap.get(WorkflowHelper.PROCESS_ARGS, "")).thenReturn(workflowParams);

        Calendar now = Calendar.getInstance();

        setReplicationStatusProcess.execute(workItem, workflowSession, metadataMap);

        CalendarMatcher calMatch = new CalendarMatcher(now);

        verify(replicationStatusManager).setReplicationStatus(any(), eq("migration"), argThat(calMatch), any(), anyString());
    }

    private static class CalendarMatcher implements ArgumentMatcher<Calendar> {

        private Calendar leftCal;

        public CalendarMatcher(String date) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm", Locale.ENGLISH);
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(date));
            this.leftCal = cal;
        }

        public CalendarMatcher(Calendar cal) throws ParseException {
            this.leftCal = cal;
        }

        @Override
        public boolean matches(Calendar argument) {
            Calendar rightCal = (Calendar) argument;
            return (leftCal.get(Calendar.YEAR) == rightCal.get(Calendar.YEAR)
                    && leftCal.get(Calendar.MONTH) == rightCal.get(Calendar.MONTH)
                    && leftCal.get(Calendar.DATE) == rightCal.get(Calendar.DATE)
                    && leftCal.get(Calendar.HOUR) == rightCal.get(Calendar.HOUR)
                    && leftCal.get(Calendar.MINUTE) == rightCal.get(Calendar.MINUTE));
        }

    }

}


text:
@implementation RNNScreenTransition

- (instancetype)initWithDict:(NSDictionary *)dict {
	self = [super init];

	self.topBar = [[ElementTransitionOptions alloc] initWithDict:dict[@"topBar"]];
	self.content = [[ElementTransitionOptions alloc] initWithDict:dict[@"content"]];
	self.bottomTabs = [[ElementTransitionOptions alloc] initWithDict:dict[@"bottomTabs"]];
	self.enable = [BoolParser parse:dict key:@"enabled"];
	self.waitForRender = [BoolParser parse:dict key:@"waitForRender"];
    self.duration = [TimeIntervalParser parse:dict key:@"duration"];
    self.sharedElementTransitions = [OptionsArrayParser parse:dict key:@"sharedElementTransitions" ofClass:SharedElementTransitionOptions.class];
	self.elementTransitions = [OptionsArrayParser parse:dict key:@"elementTransitions" ofClass:ElementTransitionOptions.class];

	return self;
}

- (BOOL)hasCustomAnimation {
	return (self.topBar.hasAnimation || self.content.hasAnimation || self.bottomTabs.hasAnimation || self.sharedElementTransitions || self.elementTransitions);
}

- (BOOL)shouldWaitForRender {
    return [self.waitForRender getWithDefaultValue:NO] || self.hasCustomAnimation;
}

- (NSTimeInterval)maxDuration {
	NSTimeInterval maxDuration = 0;
	if ([self.topBar maxDuration] > maxDuration) {
		maxDuration = [self.topBar maxDuration];
	}

	if ([self.content maxDuration] > maxDuration) {
		maxDuration = [self.content maxDuration];
	}

	if ([self.bottomTabs maxDuration] > maxDuration) {
		maxDuration = [self.bottomTabs maxDuration];
	}

    for (ElementTransitionOptions* elementTransition in self.elementTransitions) {
        if (elementTransition.maxDuration > maxDuration) {
            maxDuration = elementTransition.maxDuration;
        }
    }

    for (SharedElementTransitionOptions* sharedElementTransition in self.sharedElementTransitions) {
        if (sharedElementTransition.maxDuration > maxDuration) {
            maxDuration = sharedElementTransition.maxDuration;
        }
    }

	return maxDuration;
}

@end


text:
module Momentmethod
  VERSION = "0.1.0"
end


text:
title: Overview
page_title: Server-side Programming Overview - RadFileExplorer
description: Check our Web Forms article about Overview.
slug: fileexplorer/server-side-programming/overview
tags: overview
published: True
position: 0
---

# Server-side Programming Overview

The **RadFileExplorer** control exposes a number or properties that can be used in order to change its behavior.

| Property name | Type | Description |
| ------ | ------ | ------ |
|Configuration|An inner property|

| Inner Property name | Type | Description |
| ------ | ------ | ------ |
|ViewPaths|A string array|Sets the folders that will be shown in RadFileExplorer|
|UploadPaths|A string array|This property is used in order to Assigns Upload (or write) permission for specific folders and their children folders|
|DeletePaths|A string array|This property is used in order to Assigns Delete permission for specific folders and their children (files and folders)|
|ContentProviderTypeName|System.String|Sets the AssemblyQualifiedName of a custom FileBrowserContentProvider that will be used in order to load the content in RadFileExplorer|
|MaxUploadFileSize|Int32|Sets the allowed file upload size. [This article]({%slug upload/uploading-files/uploading-large-files%}) shows how to upload large files.|
|SearchPatterns|A string array|An array of [wildcards for search ](https://msdn.microsoft.com/en-us/library/wz42302f.aspx)||
|AllowPaging|Boolean|Enables or disables paging in the embedded RadGrid|
|PageSize|Int32|Sets the PageSize of the embedded RadGrid. This property takes effect only when AllowPaging="true" is set|
|DisplayUpFolderItem|Boolean|Show or hide the folder in the embedded RadGrid|
|EnableCopy|Boolean|Allow or deny copy|
|EnableCreateNewFolder|Boolean|Allow or deny creating a new folder. If a custom provider is used, then the provider's CanCreateDirectory should be overridden as well|
|ExplorerMode|An enum of type: Telerik.Web.UI.FileExplorer.FileExplorerMode|Allows FileTree mode, where the files and folders are shown in the TreeView. The grid in this mode is not visible|
|Grid|Telerik.Web.UI.RadGrid|Exposes the embedded RadGrid object|
|TreeView|Telerik.Web.UI.RadTreeView|Exposes the embedded RadTreeView object|
|GridContextMenu|Telerik.Web.UI.RadContextMenu|Exposes the embedded Grid's context menu|
|InitialPath|String|Allows a file or folder to be selected when the RadFileExplorer is loaded. The value set to the property is case sensitive and should be in the same format as shown in the RadFileExplorer's addressbar. The provided path must point to a concrete file that is present in the currently shown file list.|
|Splitter|Telerik.Web.UI.RadSplitter|Exposes the embedded RadSplitter object|
|ToolBar|Telerik.Web.UI.RadToolBar|Exposes the embedded RadTolBar object|
|ToolTip|Telerik.Web.UI.RadToolTip|Exposes the embedded RadToolTip object|
|WindowManager|Telerik.Web.UI.RadWindowManager|Exposes the embedded RadWindowManager object|
|Telerik.Web.UI.RadUpload|Int32|Exposes the embedded RadUpload object|
|TreePaneWidth|Int32|Allows the width of the splitter's pane to be set from the server|
|VisibleControls|Telerik.Web.UI.FileExplorer.FileExplorerControls|Determines which controls to be visible|


text:
package com.cyc.model.templates;

import com.cyc.kb.exception.KbException;
import java.io.IOException;
import org.junit.Test;

/**
 *
 * @author nwinant
 */
public class InterfaceObjTemplateTest extends BaseTemplateTest {

  @Test
  public void testGenerateString() throws IOException, KbException, Exception {
    final InterfaceObjTemplate template = new InterfaceObjTemplate(InterfaceTemplateTest.createInterfaceObj());
    assertEqualsFileContents(getTestFile("result"), template.generateString());
  }
}


text:
@interface EVEPictureViewController : EVETopicViewController

@end


text:
/** */
package org.apereo.portal.layout;

import java.util.Hashtable;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apereo.portal.IUserIdentityStore;
import org.apereo.portal.IUserProfile;
import org.apereo.portal.PortalException;
import org.apereo.portal.UserProfile;
import org.apereo.portal.security.PersonFactory;
import org.apereo.portal.security.provider.RestrictedPerson;
import org.jasig.services.persondir.IPersonAttributes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 * Helper class for reset-layout based web flows.
 *
 * <p>Depends on uPortal's {@link DataSource}.
 *
 * @author Nicholas Blair, npblair@wisc.edu
 * @author Susan Bramhall, susan.bramhall@yale.edu
 */
public class UserLayoutHelperImpl extends JdbcDaoSupport implements IUserLayoutHelper {

    protected static final String DEFAULT_LAYOUT_FNAME = "default";

    protected final Log logger = LogFactory.getLog(this.getClass());
    private IUserIdentityStore userIdentityStore;

    private IUserLayoutStore userLayoutStore;

    @Autowired(required = true)
    public void setUserLayoutStore(IUserLayoutStore userLayoutStore) {
        this.userLayoutStore = userLayoutStore;
    }

    /** @param userIdentityStore the userIdentityStore to set */
    @Autowired
    public void setUserIdentityStore(IUserIdentityStore userIdentityStore) {
        this.userIdentityStore = userIdentityStore;
    }

    /**
     * Resets a users layout for all the users profiles
     *
     * @param personAttributes
     */
    public void resetUserLayoutAllProfiles(final IPersonAttributes personAttributes) {

        RestrictedPerson person = PersonFactory.createRestrictedPerson();
        person.setAttributes(personAttributes.getAttributes());
        // get the integer uid into the person object without creating any new person data
        int uid = userIdentityStore.getPortalUID(person, false);
        person.setID(uid);

        try {
            Hashtable<Integer, UserProfile> userProfileList =
                    userLayoutStore.getUserProfileList(person);
            for (Integer key : userProfileList.keySet()) {
                UserProfile userProfile = userProfileList.get(key);
                userProfile.setLayoutId(0);
                userLayoutStore.updateUserProfile(person, userProfile);
                logger.info(
                        "resetUserLayout complete for " + person + "for profile " + userProfile);
            }
        } catch (Exception e) {
            final String msg = "Exception caught during resetUserLayout for " + person;
            logger.error(msg, e);
            throw new PortalException(msg, e);
        }
        return;
    }

    /**
     * @param personAttributes
     * @see
     *     org.apereo.portal.layout.IUserLayoutHelper#resetUserLayout(org.jasig.services.persondir.IPersonAttributes)
     */
    public void resetUserLayout(final IPersonAttributes personAttributes) {
        // Create an empty RestrictedPerson object
        RestrictedPerson person = PersonFactory.createRestrictedPerson();

        // populate the person with the supplied attributes
        person.setAttributes(personAttributes.getAttributes());

        // get the integer uid into the person object without creating any new person data
        int uid = userIdentityStore.getPortalUID(person, false);
        person.setID(uid);

        try {
            // determine user profile
            IUserProfile userProfile =
                    userLayoutStore.getUserProfileByFname(person, DEFAULT_LAYOUT_FNAME);

            // Finally set the layout id to 0.  This orphans the existing layout but it will be replaced by the default
            // when the user logs in
            userProfile.setLayoutId(0);

            // persist the change
            userLayoutStore.updateUserProfile(person, userProfile);
            logger.info("resetUserLayout complete for " + person);
        } catch (Exception e) {
            final String msg = "Exception caught during resetUserLayout for " + person;
            logger.error(msg, e);
            throw new PortalException(msg, e);
        }
    }
}


text:
/**
 * Created by sargon on 7/16/16.
 */
export class ClassesFormulas {

  public static none(level: number): number {
    return 0;
  }

  public static getHighBAB(level: number): number {
    return Number(level);
  }

  public static getMediumBAB(level: number): number {
    level = Number(level);
    return level > 0
      ? (level - 1) - Math.round((level - 1) / 4.1)
      : 0;
  }

  public static getLowBAB(level: number): number {
    level = Number(level);
    return level > 0
      ? (level - 1) - Math.round((level - 1) / 2.1)
      : 0;
  }

  public static getHighSave(level: number): number {
    level = Number(level);
    return level > 0
      ? 2 + ClassesFormulas.getLowBAB(level)
      : 0;
  }

  public static getLowSave(level: number): number {
    level = Number(level);
    return level > 0
      ? Math.round(level / 3.1)
      : 0;
  }
}


text:
package org.apache.spark.sql.execution.adaptive

import java.util.concurrent.atomic.AtomicReference

import scala.concurrent.Future

import org.apache.spark.{FutureAction, MapOutputStatistics}
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.plans.logical.Statistics
import org.apache.spark.sql.catalyst.plans.physical.Partitioning
import org.apache.spark.sql.execution._
import org.apache.spark.sql.execution.exchange._
import org.apache.spark.sql.vectorized.ColumnarBatch

/**
 * A query stage is an independent subgraph of the query plan. Query stage materializes its output
 * before proceeding with further operators of the query plan. The data statistics of the
 * materialized output can be used to optimize subsequent query stages.
 *
 * There are 2 kinds of query stages:
 *   1. Shuffle query stage. This stage materializes its output to shuffle files, and Spark launches
 *      another job to execute the further operators.
 *   2. Broadcast query stage. This stage materializes its output to an array in driver JVM. Spark
 *      broadcasts the array before executing the further operators.
 */
abstract class QueryStageExec extends LeafExecNode {

  /**
   * An id of this query stage which is unique in the entire query plan.
   */
  val id: Int

  /**
   * The sub-tree of the query plan that belongs to this query stage.
   */
  val plan: SparkPlan

  /**
   * The canonicalized plan before applying query stage optimizer rules.
   */
  val _canonicalized: SparkPlan

  /**
   * Materialize this query stage, to prepare for the execution, like submitting map stages,
   * broadcasting data, etc. The caller side can use the returned [[Future]] to wait until this
   * stage is ready.
   */
  def doMaterialize(): Future[Any]

  /**
   * Cancel the stage materialization if in progress; otherwise do nothing.
   */
  def cancel(): Unit

  /**
   * Materialize this query stage, to prepare for the execution, like submitting map stages,
   * broadcasting data, etc. The caller side can use the returned [[Future]] to wait until this
   * stage is ready.
   */
  final def materialize(): Future[Any] = {
    logDebug(s"Materialize query stage ${this.getClass.getSimpleName}: $id")
    doMaterialize()
  }

  def newReuseInstance(newStageId: Int, newOutput: Seq[Attribute]): QueryStageExec

  /**
   * Returns the runtime statistics after stage materialization.
   */
  def getRuntimeStatistics: Statistics

  /**
   * Compute the statistics of the query stage if executed, otherwise None.
   */
  def computeStats(): Option[Statistics] = if (isMaterialized) {
    val runtimeStats = getRuntimeStatistics
    val dataSize = runtimeStats.sizeInBytes.max(0)
    val numOutputRows = runtimeStats.rowCount.map(_.max(0))
    val attributeStats = runtimeStats.attributeStats
    Some(Statistics(dataSize, numOutputRows, attributeStats, isRuntime = true))
  } else {
    None
  }

  @transient
  @volatile
  protected var _resultOption = new AtomicReference[Option[Any]](None)

  private[adaptive] def resultOption: AtomicReference[Option[Any]] = _resultOption
  def isMaterialized: Boolean = resultOption.get().isDefined

  override def output: Seq[Attribute] = plan.output
  override def outputPartitioning: Partitioning = plan.outputPartitioning
  override def outputOrdering: Seq[SortOrder] = plan.outputOrdering
  override def executeCollect(): Array[InternalRow] = plan.executeCollect()
  override def executeTake(n: Int): Array[InternalRow] = plan.executeTake(n)
  override def executeTail(n: Int): Array[InternalRow] = plan.executeTail(n)
  override def executeToIterator(): Iterator[InternalRow] = plan.executeToIterator()

  protected override def doExecute(): RDD[InternalRow] = plan.execute()
  override def supportsColumnar: Boolean = plan.supportsColumnar
  protected override def doExecuteColumnar(): RDD[ColumnarBatch] = plan.executeColumnar()
  override def doExecuteBroadcast[T](): Broadcast[T] = plan.executeBroadcast()
  override def doCanonicalize(): SparkPlan = _canonicalized

  protected override def stringArgs: Iterator[Any] = Iterator.single(id)

  override def simpleStringWithNodeId(): String = {
    super.simpleStringWithNodeId() + computeStats().map(", " + _.toString).getOrElse("")
  }

  override def generateTreeString(
      depth: Int,
      lastChildren: Seq[Boolean],
      append: String => Unit,
      verbose: Boolean,
      prefix: String = "",
      addSuffix: Boolean = false,
      maxFields: Int,
      printNodeId: Boolean,
      indent: Int = 0): Unit = {
    super.generateTreeString(depth,
      lastChildren,
      append,
      verbose,
      prefix,
      addSuffix,
      maxFields,
      printNodeId,
      indent)
    plan.generateTreeString(
      depth + 1, lastChildren :+ true, append, verbose, "", false, maxFields, printNodeId, indent)
  }
}

/**
 * A shuffle query stage whose child is a [[ShuffleExchangeLike]] or [[ReusedExchangeExec]].
 *
 * @param id the query stage id.
 * @param plan the underlying plan.
 * @param _canonicalized the canonicalized plan before applying query stage optimizer rules.
 */
case class ShuffleQueryStageExec(
    override val id: Int,
    override val plan: SparkPlan,
    override val _canonicalized: SparkPlan) extends QueryStageExec {

  @transient val shuffle = plan match {
    case s: ShuffleExchangeLike => s
    case ReusedExchangeExec(_, s: ShuffleExchangeLike) => s
    case _ =>
      throw new IllegalStateException(s"wrong plan for shuffle stage:\n ${plan.treeString}")
  }

  @transient private lazy val shuffleFuture = shuffle.submitShuffleJob

  override def doMaterialize(): Future[Any] = shuffleFuture

  override def newReuseInstance(newStageId: Int, newOutput: Seq[Attribute]): QueryStageExec = {
    val reuse = ShuffleQueryStageExec(
      newStageId,
      ReusedExchangeExec(newOutput, shuffle),
      _canonicalized)
    reuse._resultOption = this._resultOption
    reuse
  }

  override def cancel(): Unit = shuffleFuture match {
    case action: FutureAction[MapOutputStatistics] if !action.isCompleted =>
      action.cancel()
    case _ =>
  }

  /**
   * Returns the Option[MapOutputStatistics]. If the shuffle map stage has no partition,
   * this method returns None, as there is no map statistics.
   */
  def mapStats: Option[MapOutputStatistics] = {
    assert(resultOption.get().isDefined, s"${getClass.getSimpleName} should already be ready")
    val stats = resultOption.get().get.asInstanceOf[MapOutputStatistics]
    Option(stats)
  }

  override def getRuntimeStatistics: Statistics = shuffle.runtimeStatistics
}

/**
 * A broadcast query stage whose child is a [[BroadcastExchangeLike]] or [[ReusedExchangeExec]].
 *
 * @param id the query stage id.
 * @param plan the underlying plan.
 * @param _canonicalized the canonicalized plan before applying query stage optimizer rules.
 */
case class BroadcastQueryStageExec(
    override val id: Int,
    override val plan: SparkPlan,
    override val _canonicalized: SparkPlan) extends QueryStageExec {

  @transient val broadcast = plan match {
    case b: BroadcastExchangeLike => b
    case ReusedExchangeExec(_, b: BroadcastExchangeLike) => b
    case _ =>
      throw new IllegalStateException(s"wrong plan for broadcast stage:\n ${plan.treeString}")
  }

  override def doMaterialize(): Future[Any] = {
    broadcast.submitBroadcastJob
  }

  override def newReuseInstance(newStageId: Int, newOutput: Seq[Attribute]): QueryStageExec = {
    val reuse = BroadcastQueryStageExec(
      newStageId,
      ReusedExchangeExec(newOutput, broadcast),
      _canonicalized)
    reuse._resultOption = this._resultOption
    reuse
  }

  override def cancel(): Unit = {
    if (!broadcast.relationFuture.isDone) {
      sparkContext.cancelJobGroup(broadcast.runId.toString)
      broadcast.relationFuture.cancel(true)
    }
  }

  override def getRuntimeStatistics: Statistics = broadcast.runtimeStatistics
}


text:
namespace System.Windows.Forms
{

using System.Drawing;

// This is a special-purpose control that lays out its children in a grid.
// It is intended for use inside dialog box controls like "FileDialog".

internal class GridLayout : Control, IRecommendedSize
{
	// Internal state.
	private int columns;
	private int rows;
	private int stretchColumn;
	private int stretchRow;
	private int margin;
	private int colSpacing;
	private int rowSpacing;
	private Control[] children;

	// Constructor.
	public GridLayout(int columns, int rows)
			{
				this.columns = columns;
				this.rows = rows;
				this.stretchColumn = columns - 1;
				this.stretchRow = rows - 1;
				this.margin = 4;
				this.colSpacing = 4;
				this.rowSpacing = 4;
				this.children = new Control [columns * rows];
				this.TabStop = false;
			}

	// Get or set the column to be stretched.
	public int StretchColumn
			{
				get
				{
					return stretchColumn;
				}
				set
				{
					stretchColumn = value;
				}
			}

	// Get or set the row to be stretched.
	public int StretchRow
			{
				get
				{
					return stretchRow;
				}
				set
				{
					stretchRow = value;
				}
			}

	// Get or set the margin.
	public int Margin
			{
				get
				{
					return margin;
				}
				set
				{
					margin = value;
				}
			}

	// Get or set the spacing between columns.
	public int ColumnSpacing
			{
				get
				{
					return colSpacing;
				}
				set
				{
					colSpacing = value;
				}
			}

	// Get or set the spacing between rows.
	public int RowSpacing
			{
				get
				{
					return rowSpacing;
				}
				set
				{
					rowSpacing = value;
				}
			}

	// Get the child control at a particular location.
	public Control GetControl(int column, int row)
			{
				return children[column * rows + row];
			}

	// Set the child control at a particular location.  Locations can be blank.
	public void SetControl(int column, int row, Control child)
			{
				if(child.Parent != this)
				{
					Controls.Add(child);
				}
				children[column * rows + row] = child;
			}

	// Get the recommended client size for this control.
	public Size RecommendedSize
			{
				get
				{
					int width = 0;
					int height = 0;
					int maxWidth;
					int maxHeight;
					int xextra, yextra;
					Size childSize;
					int x, y;
					Control child;

					// Scan the columns, looking for maximums.
					for(x = 0; x < columns; ++x)
					{
						maxWidth = 0;
						for(y = 0; y < rows; ++y)
						{
							child = GetControl(x, y);
							if(child != null && child.visible)
							{
								childSize =
									HBoxLayout.GetRecommendedSize(child);
								if(childSize.Width > maxWidth)
								{
									maxWidth = childSize.Width;
								}
							}
						}
						width += maxWidth;
					}

					// Scan the rows, looking for maximums.
					for(y = 0; y < rows; ++y)
					{
						maxHeight = 0;
						for(x = 0; x < columns; ++x)
						{
							child = GetControl(x, y);
							if(child != null && child.visible)
							{
								childSize =
									HBoxLayout.GetRecommendedSize(child);
								if(childSize.Height > maxHeight)
								{
									maxHeight = childSize.Height;
								}
							}
						}
						height += maxHeight;
					}

					// Add the margins and return the final size.
					xextra = margin * 2;
					if(columns >= 2)
					{
						xextra += (columns - 1) * colSpacing;
					}
					yextra = margin * 2;
					if(rows >= 2)
					{
						yextra += (rows - 1) * rowSpacing;
					}
					return new Size(width + xextra, height + yextra);
				}
			}

	// Lay out the children in this control.
	protected override void OnLayout(LayoutEventArgs e)
			{
				int[] columnOffsets = new int [columns];
				int[] columnWidths = new int [columns];
				int[] rowOffsets = new int [rows];
				int[] rowHeights = new int [rows];
				int x, y;
				Control child;
				int posnLower, posnUpper;
				Size childSize;

				// Compute the offset and width of all columns.
				posnLower = margin;
				posnUpper = ClientSize.Width - margin;
				for(x = 0; x < stretchColumn; ++x)
				{
					columnOffsets[x] = posnLower;
					columnWidths[x] = 0;
					for(y = 0; y < rows; ++y)
					{
						child = GetControl(x, y);
						if(child != null && child.visible)
						{
							childSize = HBoxLayout.GetRecommendedSize(child);
							if(childSize.Width > columnWidths[x])
							{
								columnWidths[x] = childSize.Width;
							}
						}
					}
					posnLower += columnWidths[x] + colSpacing;
				}
				for(x = columns - 1; x > stretchColumn; --x)
				{
					columnWidths[x] = 0;
					for(y = 0; y < rows; ++y)
					{
						child = GetControl(x, y);
						if(child != null && child.visible)
						{
							childSize = HBoxLayout.GetRecommendedSize(child);
							if(childSize.Width > columnWidths[x])
							{
								columnWidths[x] = childSize.Width;
							}
						}
					}
					posnUpper -= columnWidths[x];
					columnOffsets[x] = posnUpper;
					posnUpper -= colSpacing;
				}
				columnOffsets[stretchColumn] = posnLower;
				columnWidths[stretchColumn] = posnUpper - posnLower;

				// Compute the offset and height of all rows.
				posnLower = margin;
				posnUpper = ClientSize.Height - margin;
				for(y = 0; y < stretchRow; ++y)
				{
					rowOffsets[y] = posnLower;
					rowHeights[y] = 0;
					for(x = 0; x < columns; ++x)
					{
						child = GetControl(x, y);
						if(child != null && child.visible)
						{
							childSize = HBoxLayout.GetRecommendedSize(child);
							if(childSize.Height > rowHeights[y])
							{
								rowHeights[y] = childSize.Height;
							}
						}
					}
					posnLower += rowHeights[y] + rowSpacing;
				}
				for(y = rows - 1; y > stretchRow; --y)
				{
					rowHeights[y] = 0;
					for(x = 0; x < columns; ++x)
					{
						child = GetControl(x, y);
						if(child != null && child.visible)
						{
							childSize = HBoxLayout.GetRecommendedSize(child);
							if(childSize.Height > rowHeights[y])
							{
								rowHeights[y] = childSize.Height;
							}
						}
					}
					posnUpper -= rowHeights[y];
					rowOffsets[y] = posnUpper;
					posnUpper -= rowSpacing;
				}
				rowOffsets[stretchRow] = posnLower;
				rowHeights[stretchRow] = posnUpper - posnLower;

				// Place the controls in their final locations.
				for(y = 0; y < rows; ++y)
				{
					for(x = 0; x < columns; ++x)
					{
						child = GetControl(x, y);
						if(child != null && child.visible)
						{
							child.SetBounds
								(columnOffsets[x], rowOffsets[y],
								 columnWidths[x], rowHeights[y]);
						}
					}
				}
			}

}; // class GridLayout

}; // namespace System.Windows.Forms


text:
<!-- BEGIN MUNGE: UNVERSIONED_WARNING -->

<!-- END MUNGE: UNVERSIONED_WARNING -->

## kubectl create secret

Create a secret using specified subcommand.

### Synopsis

Create a secret using specified subcommand.

```
kubectl create secret
```

### Options inherited from parent commands

```
      --alsologtostderr[=false]: log to standard error as well as files
      --certificate-authority="": Path to a cert. file for the certificate authority.
      --client-certificate="": Path to a client certificate file for TLS.
      --client-key="": Path to a client key file for TLS.
      --cluster="": The name of the kubeconfig cluster to use
      --context="": The name of the kubeconfig context to use
      --insecure-skip-tls-verify[=false]: If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure.
      --kubeconfig="": Path to the kubeconfig file to use for CLI requests.
      --log-backtrace-at=:0: when logging hits line file:N, emit a stack trace
      --log-dir="": If non-empty, write log files in this directory
      --log-flush-frequency=5s: Maximum number of seconds between log flushes
      --logtostderr[=true]: log to standard error instead of files
      --match-server-version[=false]: Require server version to match client version
      --namespace="": If present, the namespace scope for this CLI request.
      --password="": Password for basic authentication to the API server.
  -s, --server="": The address and port of the Kubernetes API server
      --stderrthreshold=2: logs at or above this threshold go to stderr
      --token="": Bearer token for authentication to the API server.
      --user="": The name of the kubeconfig user to use
      --username="": Username for basic authentication to the API server.
      --v=0: log level for V logs
      --vmodule=: comma-separated list of pattern=N settings for file-filtered logging
```

### SEE ALSO

* [kubectl create](kubectl_create.md)	 - Create a resource by filename or stdin
* [kubectl create secret docker-registry](kubectl_create_secret_docker-registry.md)	 - Create a secret for use with a Docker registry.
* [kubectl create secret generic](kubectl_create_secret_generic.md)	 - Create a secret from a local file, directory or literal value.

###### Auto generated by spf13/cobra on 2-Mar-2016

<!-- BEGIN MUNGE: IS_VERSIONED -->
<!-- TAG IS_VERSIONED -->
<!-- END MUNGE: IS_VERSIONED -->

<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_create_secret.md?pixel)]()
<!-- END MUNGE: GENERATED_ANALYTICS -->


text:
<!-- For usage of this file, see: https://msdn.microsoft.com/en-us/library/bb514188.aspx -->
<Dictionary>
  <Words>
    <Unrecognized>
      <Word></Word>
    </Unrecognized>
    <Recognized>
      <Word>Accpac</Word>
      <Word>additivize</Word>
      <Word>additivized</Word>
      <Word>additivization</Word>
      <Word>anonymized</Word>
      <Word>AppVeyor</Word>
      <Word>Aspose</Word>
      <Word>Bson</Word>
      <Word>bool</Word>
      <Word>Coop</Word>
      <Word>Dist</Word>
      <Word>FY</Word>
      <Word>json</Word>
      <Word>Loggly</Word>
      <Word>Naos</Word>
      <Word>nullable</Word>
      <Word>OBeautifulCode</Word>
      <Word>pathed</Word>
      <Word>pdf</Word>
      <Word>pluralization</Word>
      <Word>tearsheet</Word>
      <Word>tearsheets</Word>
      <Word>whitespace</Word>
      <Word>Zendesk</Word>
    </Recognized>
    <Deprecated>
      <Term PreferredAlternate=""></Term>
    </Deprecated>
    <Compound>
      <Term CompoundAlternate="CellPhone">cellphone</Term>
      <Term CompoundAlternate="OBeautifulCode">obeautifulcode</Term>
      <Term CompoundAlternate="RollUp">rollup</Term>
      <Term CompoundAlternate="YearEnd">yearend</Term>
    </Compound>
    <DiscreteExceptions>
      <Term></Term>
    </DiscreteExceptions>
  </Words>
  <Acronyms>
    <CasingExceptions>
      <Acronym>Co</Acronym>
      <Acronym>Etl</Acronym>
    </CasingExceptions>
  </Acronyms>
</Dictionary>


text:
#pragma once
/*
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include "frame/Registry.h"
#include "frame/Mask.h"

namespace frame
{
    class Diagram;
    class DiagramNode;
    class DiagramInputSocket;
    class DiagramOutputSocket;

    /// \class DiagramChannelBase
    class DiagramChannelBase {
    public:
        DiagramChannelBase() {}
        virtual ~DiagramChannelBase() {};
        virtual std::size_t get_index() const = 0;
    };

    /// \brief TODO: Write this.
    typedef Registry<DiagramChannelBase> ChannelRegistry;

    /// \class DiagramChannel
    template <typename Type>
    class DiagramChannel : public DiagramChannelBase {
    public:
        DiagramChannel() {}
        virtual ~DiagramChannel() {}
        std::size_t get_index() const { return Type::index(); }
        static std::size_t index() { return ChannelRegistry::index<Type>(); }
    };

    /// \class DiagramSocketBase
    class DiagramSocketBase {
    public:
        DiagramSocketBase(DiagramNode* node, std::size_t channel_type_index) : _node(node), _channel_type_index(channel_type_index) {}
        virtual ~DiagramSocketBase() {}

    public:
        const DiagramNode* node() const { return _node; }
        std::size_t channel_type_index() const { return _channel_type_index; }
        const std::string& channel_type_name() const { return ChannelRegistry::name(_channel_type_index); }
        const Mask& channel_type_mask() const { return ChannelRegistry::mask(_channel_type_index); }

    private:
        DiagramNode* _node;
        std::size_t _channel_type_index;
    };

    /// \class DiagramInputSocket
    class DiagramInputSocket : public DiagramSocketBase {
        friend class Diagram;

    public:
        DiagramInputSocket(DiagramNode* node, std::size_t channel_type_index) : DiagramSocketBase(node, channel_type_index), _connection(nullptr) {}
        ~DiagramInputSocket() {}

    public:
        DiagramOutputSocket* connection() const { return _connection; }
        //DiagramChannelBase* channel() const { return _connection ? _connection->channel() : nullptr; }

    private:
        void set_connection(DiagramOutputSocket* socket) { _connection = socket; }

    private:
        DiagramOutputSocket* _connection;
    };

    /// \class DiagramOutputSocket
    class DiagramOutputSocket : public DiagramSocketBase {
        friend class Diagram;

    public:
        DiagramOutputSocket(DiagramNode* node, std::size_t channel_type_index) : DiagramSocketBase(node, channel_type_index) {
            _channel = ChannelRegistry::factory(channel_type_index)();
        }

        ~DiagramOutputSocket() {}

    public:
        const std::vector<DiagramInputSocket*>& connections() const { return _connections; }
        DiagramChannelBase* channel() { return _channel; _changed = true; }
        bool changed() const { return _changed; }

    private:
        void add_connection(DiagramInputSocket* socket) { _connections.push_back(socket); }
        bool remove_connection(const DiagramInputSocket* socket) {
            auto it = std::find(_connections.begin(), _connections.end(), socket);
            if (it == _connections.end()) return false;
            _connections.erase(it);
            return true;
        }

    private:
        DiagramChannelBase* _channel;
        std::vector<DiagramInputSocket*> _connections;
        bool _changed;
    };

    class NullChannel;

    /// \class DiagramNode
    class DiagramNode {
    public:
        DiagramNode() {}
        virtual ~DiagramNode() {}

    public:
        template <typename ChannelType=NullChannel>
        DiagramInputSocket* add_input() { return add_input(ChannelType::index()); }
        DiagramInputSocket* add_input(std::size_t channel_type) {
            DiagramInputSocket* socket = new DiagramInputSocket(this, channel_type);
            _inputs.push_back(socket);
            return socket;
        }

        template <typename ChannelType=NullChannel>
        DiagramOutputSocket* add_output() { return add_output(ChannelType::index()); }
        DiagramOutputSocket* add_output(std::size_t channel_type) {
            DiagramOutputSocket* socket = new DiagramOutputSocket(this, channel_type);
            _outputs.push_back(socket);
            return socket;
        }

    public:
        const std::vector<DiagramInputSocket*>& inputs() const { return _inputs; }
        const std::vector<DiagramOutputSocket*>& outputs() const { return _outputs; }

    private:
        std::vector<DiagramInputSocket*> _inputs;
        std::vector<DiagramOutputSocket*> _outputs;
    };

    /// \class Diagram
    class Diagram {
    public:
        Diagram() {}
        Diagram(const Diagram& diagram) { copy(diagram); }
        ~Diagram() { clear(); }
        const Diagram& operator=(const Diagram& diagram) { copy(diagram); return *this; }

    public:
        void copy(const Diagram& diagram) {
            clear();

            //
            // TODO
            //
        }

        template <typename NodeType=DiagramNode>
        NodeType* add_node() {
            NodeType* node = new NodeType();
            _nodes.push_back(static_cast<DiagramNode*>(node));
            return node;
        }

        template <typename NodeType>
        bool remove_node(const NodeType* node) {

            // Find this node... return false if we don't own it
            auto it = std::find(_nodes.begin(), _nodes.end(), static_cast<const DiagramNode*>(node));
            if (it == _nodes.end()) return false;

            // Disconnect the node from everything
            std::set< std::pair<DiagramOutputSocket*, DiagramInputSocket*> > connections;
            for (DiagramOutputSocket* socket_out : node->outputs())
                for (DiagramInputSocket* socket_in : socket_out->connections())
                    connections.insert(std::pair<DiagramOutputSocket*, DiagramInputSocket*>(socket_out, socket_in));
            for (DiagramInputSocket* socket_in : node->inputs())
                if (socket_in->connection())
                    connections.insert(std::pair<DiagramOutputSocket*, DiagramInputSocket*>(socket_in->connection(), socket_in));
            for (auto connection : connections)
                disconnect(connection.first, connection.second);

            // Erase the node
            _nodes.erase(it);
            delete node;
            return true;
        }

        void clear() {
            for (DiagramNode* node : std::vector<DiagramNode*>(_nodes))
                remove_node(node);
            _nodes.clear();
        }

        const std::vector<DiagramNode*>& nodes() const { return _nodes; }
        //const std::vector<DiagramChannelBase*>& channels() const { return _channels; }

    public:

        static bool valid(DiagramOutputSocket* from, DiagramInputSocket* to) {
            return from->channel_type_index() == to->channel_type_index();
        }

        static bool connect(DiagramOutputSocket* from, DiagramInputSocket* to) {
            if (!valid(from, to))
                return false;

            if (to->connection()) {
                if (to->connection() == from) return false;
                else disconnect(to->connection(), to);
            }

            from->add_connection(to);
            to->set_connection(from);

            //return channel;
            return true;
        }

        static bool disconnect(DiagramOutputSocket* from, DiagramInputSocket* to) {

            if (to->connection() != from) return false;
            to->set_connection(nullptr);
            from->remove_connection(to);
            return true;
        }

    private:
        std::vector<DiagramNode*> _nodes;
        //std::vector<DiagramChannelBase*> _channels;
    };
}

#define FRAME_STR(str) #str
#define FRAME_CHANNEL(Name) \
    class Name; \
    namespace { const std::string& Name##_NAME = frame::ChannelRegistry::create<Name>(FRAME_STR(Name)); } \
    class Name : public frame::DiagramChannel<Name>

namespace frame
{
    FRAME_CHANNEL(NullChannel) {};
}
*/


text:
"""Helper classes and functions for the Legrand Home+ Control integration."""
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_oauth2_flow

from .const import CONF_SUBSCRIPTION_KEY, DOMAIN, OAUTH2_AUTHORIZE, OAUTH2_TOKEN

class HomePlusControlOAuth2Implementation(
    config_entry_oauth2_flow.LocalOAuth2Implementation
):
    """OAuth2 implementation that extends the HomeAssistant local implementation.

    It provides the name of the integration and adds support for the subscription key.

    Attributes:
        hass (HomeAssistant): HomeAssistant core object.
        client_id (str): Client identifier assigned by the API provider when registering an app.
        client_secret (str): Client secret assigned by the API provider when registering an app.
        subscription_key (str): Subscription key obtained from the API provider.
        authorize_url (str): Authorization URL initiate authentication flow.
        token_url (str): URL to retrieve access/refresh tokens.
        name (str): Name of the implementation (appears in the HomeAssistant GUI).
    """

    def __init__(
        self,
        hass: HomeAssistant,
        config_data: dict,
    ) -> None:
        """HomePlusControlOAuth2Implementation Constructor.

            Initialize the authentication implementation for the Legrand Home+ Control API.

        Args:
            hass (HomeAssistant): HomeAssistant core object.
            config_data (dict): Configuration data that complies with the config Schema
                                of this component.
        """
        super().__init__(
            hass=hass,
            domain=DOMAIN,
            client_id=config_data[CONF_CLIENT_ID],
            client_secret=config_data[CONF_CLIENT_SECRET],
            authorize_url=OAUTH2_AUTHORIZE,
            token_url=OAUTH2_TOKEN,
        )
        self.subscription_key = config_data[CONF_SUBSCRIPTION_KEY]

    @property
    def name(self) -> str:
        """Name of the implementation."""
        return "Home+ Control"


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.betaminus.fitbitsample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".AuthenticationActivity"
            android:label="@string/title_activity_authentication" >
        </activity>
    </application>

</manifest>


text:
ActiveRecord::Schema.define(version: 20140902144616) do

  create_table "categories", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "categories", ["name"], name: "index_categories_on_name", using: :btree

  create_table "posts", force: true do |t|
    t.text     "message",    null: false
    t.integer  "topic_id",   null: false
    t.integer  "user_id",    null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "posts", ["topic_id"], name: "index_posts_on_topic_id", using: :btree
  add_index "posts", ["updated_at"], name: "index_posts_on_updated_at", using: :btree
  add_index "posts", ["user_id"], name: "index_posts_on_user_id", using: :btree

  create_table "topics", force: true do |t|
    t.string   "name",        null: false
    t.integer  "category_id", null: false
    t.integer  "user_id",     null: false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.text     "message",     null: false
  end

  add_index "topics", ["category_id"], name: "index_topics_on_category_id", using: :btree
  add_index "topics", ["updated_at"], name: "index_topics_on_updated_at", using: :btree
  add_index "topics", ["user_id"], name: "index_topics_on_user_id", using: :btree

  create_table "users", force: true do |t|
    t.string   "email",                           null: false
    t.string   "encrypted_password",              null: false
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",       default: 0, null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "name",                            null: false
    t.integer  "user_type",           default: 2, null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
  add_index "users", ["name"], name: "index_users_on_name", unique: true, using: :btree
  add_index "users", ["user_type"], name: "user_type", using: :btree

end


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=head1 NAME

Bio::EnsEMBL::Funcgen::Storable

=head1 SYNOPSIS

  my $dbID = $storable_object->dbID();
  my $adaptor = $storable_object->adaptor();
  if($storable_object->is_stored($db_adaptor))) {

  }
=head1 DESCRIPTION

This is a simple wrapper class to provide convenience methods for the StorableAdaptor.
Only get type methods have been implemented here to avoid obfuscating DB writes which
should only be done by the specific 'Storable'Adaptors.

=head1 SEE ALSO

Bio::EnsEMBL::Funcgen::DBSQL::BaseAdaptor

=cut

package Bio::EnsEMBL::Funcgen::Storable;

use strict;
use warnings;
use Bio::EnsEMBL::Registry;
use Bio::EnsEMBL::Utils::Exception qw( throw );
use Bio::EnsEMBL::Utils::Argument  qw( rearrange );
use Bio::EnsEMBL::Utils::Scalar    qw( assert_ref check_ref );

use base qw( Bio::EnsEMBL::Storable );

=head2 new

  Arg [-STATES]  : Arrayref of states
  Arg [-dbID]    : database internal id
  Example        : none
  Caller         : internal calls
  Description    : create a new Storable object
  Returntype     : Bio::EnsEMBL::Storable
  Exceptions     : Adaptor not a Bio::EnsEMBL::Funcgen::DBSQL::BaseAdaptor
  Status         : Stable

=cut

sub new {
  my $caller = shift;
  my $class = ref($caller) || $caller;
  my $self = $class->SUPER::new(@_);

  my ($assoc_ftypes) = rearrange(['ASSOCIATED_FEATURE_TYPES'] ,@_);
  $self->associated_feature_types($assoc_ftypes) if(defined $assoc_ftypes);

  return $self;
}

=head2 get_all_UnmappedObjects

  Example    : my @uos = @{$storable->get_all_UnmappedObjects };
  Description: Retrieves UnamappedObjects for this Storable.
  Returntype : arrayref of Bio::EnsEMBL::UnmappedObject objects
  Exceptions : none
  Caller     : general
  Status     : At risk - move to Bio::Ensembl::Storable?

=cut

sub get_all_UnmappedObjects{
  my $self = shift;
  #Do we want to add external_db or analysis param here?

  my $class = ref($self);
  $class =~ s/.*:://;

  return $self->adaptor->db->get_UnmappedObjectAdaptor->fetch_all_by_object_type_id($class, $self->dbID);
}

# =head2 add_DBEntry
#
#   Arg [1]    : Bio::EnsEMBL::DBEntry $dbe
#                The dbEntry to be added
#   Example    : my $dbe = Bio::EnsEMBL::DBEntry->new(...);
#                $transcript->add_DBEntry($dbe);
#   Description: Associates a DBEntry with this object. Note that adding
#                DBEntries will prevent future lazy-loading of DBEntries for this
#                storable (see get_all_DBEntries).
#   Returntype : none
#   Exceptions : thrown on incorrect argument type
#   Caller     : general
#   Status     : Stable
#
# =cut
#
# sub add_DBEntry {
#   my $self = shift;
#   my $dbe = shift;
#
#   unless($dbe && ref($dbe) && $dbe->isa('Bio::EnsEMBL::DBEntry')) {
#     throw('Expected DBEntry argument');
#   }
#
#   $self->{'dbentries'} ||= [];
#   push @{$self->{'dbentries'}}, $dbe;
# }

=head2 associated_feature_types

  Example    : my @associated_ftypes = @{$feature->associated_feature_types()};
  Description: Getter/Setter for other associated FeatureTypes.
  Returntype : ARRAYREF of Bio::EnsEMBL::Funcgen:FeatureType objects
  Exceptions : None
  Caller     : General
  Status     : At risk

=cut

sub associated_feature_types{
  my ($self, $ftypes) = @_;

  #Lazy load as we don't want to have to do a join on all features when most will not have any

  if(defined $ftypes){

	if(ref($ftypes) eq 'ARRAY'){

	  foreach my $ftype(@$ftypes){

		if( ! $ftype->isa('Bio::EnsEMBL::Funcgen::FeatureType') ){
		  throw('You must pass and ARRAYREF of stored Bio::EnsEMBL::Funcgen::FeatureType objects');
		}
		#test is stored in adaptor
	  }

	  if(defined $self->{'associated_feature_types'}){
		warn('You are overwriting associated feature types');
		#we could simply add the new ones and make them NR.
	  }

	  $self->{'associated_feature_types'} = $ftypes;
	}
	else{
	  throw('You must pass and ARRAYREF of stored Bio::EnsEMBL::Funcgen::FeatureType objects');
	}
  }

  if(! defined $self->{'associated_feature_types'}){
	#This will fail if we have not stored yet

	if(defined $self->adaptor){
	  $self->{'associated_feature_types'} = $self->adaptor->db->get_FeatureTypeAdaptor->fetch_all_by_association($self);
	}

  }

  #This has the potential to return undef, or an arrayref which may be empty.
  return $self->{'associated_feature_types'};
}

=head2 compare_scalar_methods

  Arg [1]    : Object to compare to, not necessarily stored.
  Arg [2]    : Arrayref - Method names which return a Scalar, or an Array/Arrayref
               of Scalars.
  Example    : my %diffs = %{$self->compare_to($other_obj,
                                               [qw(name, get_scalars_method)]);
  Description: Compares the returned string values of the specified methods
               between this object and the object passed.
  Returntype : Hashref of method name keys error string values which show
               the differences between self and the other object (in that order)
  Exceptions : Throws if arguments not defined and valid.
               Throws if this Storable or the object passed cannot call the
               specified methods.
               Throws if methods do not return scalars.
  Caller     : Storable::compare_to
  Status     : At risk

=cut

sub compare_scalar_methods {
  my ($self, $obj, $methods) = @_;

  if(! (defined $methods &&
        ref($methods) &&
        ref($methods) eq 'ARRAY')){
    throw('You must pass an Arrayref of methods to compare');
  }

  my $diffs = {};

  foreach my $method(@$methods){

    if ( ! $self->can($method) ) {
      throw(ref($self)." cannot call method '".$method."' to compare");
    }

    my ($these_scls, $other_scls, $diff, $multi) =
      @{$self->_compare_method_return_types($obj, $method)};

    if($diff){
      $diffs->{$method} = $diff;
      next;
    }

    foreach my $i(0..$#{$these_scls}){
      #Check all are scalar
      if (ref(\($these_scls->[$i])) ne 'SCALAR'){
        throw("$method does not return a SCALAR value or an ARRAY or ARRAYREF ".
              "of SCALAR values:\t".$these_scls->[$i]);
      }

      #equating strings with == results in all strings evaling as 0, therefore
      #would match any string (unless prefixed with numbers in which case it uses those).
      #ne/eq converts numbers into strings accurately, so this is safe.
      if($these_scls->[$i] ne $other_scls->[$i]){
        $diffs->{$method} = $these_scls->[$i].' - '.$other_scls->[$i];
      }
    }
  }

  return $diffs;
}

=head2 compare_storable_methods

  Arg [1]    : Storable to compare to. (Mandatory)
  Arg [2]    : Arrayref - Method names which return a Storable or an Array
               or Arrayref of Storables. (Mandatory)
  Example    : my %diffs = %{$self->compare_to($other_obj,
                                               [qw(get_storable, get_storables)]);
  Description: Compares the returned Storable(s) of the specified methods. This is
               done checking whether the are stored in the same DB as this Storable,
               and have matching dbIDs.
  Returntype : Hashref of method name keys and error string values which show
               the differences between self and the other Storable (in that order)
  Exceptions : Throws if arguments not defined and valid.
               Throws if this Storable or the object passed cannot call the
               specified methods.
               Throws if methods do not return stored Bio::EnsEMBL::Storables with an adptor
  Caller     : Storable::compare_to
  Status     : At risk

=cut

#removed deep mode from here as this was only valid for storing between DBs
#As it is not possible to equivalently sort multiple storables from
#different DBs based on their dbIDs, hence this comparison would fail.
#Would need to be done with unique key values, which are not generically accessibly here
#Deep inter-DB comparisons need to be done by iterative shallow comparisons
#through an object hierarchy in a wrapper method i.e. the wrapper method will know
#the appropriate unique keys to sort on.
#This also removes the need to track previous comparisons to prevent deep recursion
#Does this mean we can now add missing object methods which would have caused circular refs?
#Not need to do this in either inter/intraDB comparison

#Could remove require ment for them being storables if we can call compare_to on the
#returned objects. This would require some 'Role' definition as we can't guarantee what
#another object compare method might be name or in fact do.

#TODO Make test names (value string prefixes) accessable for validation?

sub compare_storable_methods {
  my ($self, $obj, $methods) = @_;
  my $diffs = {};

  if(! (defined $methods &&
        ref($methods) &&
        ref($methods) eq 'ARRAY')){
    throw('You must pass an Arrayref of methods to compare');
  }

  foreach my $method(@$methods){
    my $obj_diffs = {};

    my ($these_objs, $other_objs, $diff, $multi) =
      @{$self->_compare_method_return_types($obj, $method, 1)};
    #1 is 'storable' flag

    if(! (@$these_objs && @$other_objs)){
      next;
    }
    elsif($diff){
      $diffs->{$method} = $diff;
      next;
    }
    #else we have same number of storables

    #Need to account for a single undef value, here?

    for my $i (0..$#{$these_objs}){
      #We can't alter $method key here for test discrimination
      #else we won't be able to easily identify what method gave the error
      #TP ID specific test result, have to pattern match
      #the start of the error string

      #These always have to be stored, so can use DB from either object
      if(! $other_objs->[$i]->adaptor){
        throw('Could not access DBAdaptor from self('.ref($other_objs->[$i]).
          ") for $method is_stored check");
      }

      if(! $these_objs->[$i]->is_stored($other_objs->[$i]->adaptor->db)){
        $diffs->{$method} = 'DBs are not the same for '.ref($other_objs);
        last if $multi;
      }
      elsif(ref($these_objs->[$i]) ne ref($other_objs->[$i])){ #Different return types
        #As there is not requirement for $self and $obj to be the same class
        #there is no guarantee they will return the same object
        $diffs->{$method} = "Namespace mismatch:\n\t".
            ref($these_objs->[$i]).' - '.ref($other_objs->[$i]);
        last if $multi;
      }
      elsif($these_objs->[$i]->dbID != $other_objs->[$i]->dbID){
          $diffs->{$method} = "dbID mismatch:\t".
            join(', ', (map $_->dbID, @$these_objs))."\t-\t".
            join(', ', (map $_->dbID, @$other_objs));
          last if $multi;
      }
    }
  }

  return $diffs;
}

#We don't enforce that $self and $obj are the same class, just that they have the
#same method

sub _compare_method_return_types{
  my ($self, $obj, $method, $storable) = @_;

  if ( ! $self->can($method) ) {
      throw(ref($self).' cannot call method '.$method);
  }
    elsif ( ! $obj->can($method) ) {
      throw(ref($obj).' cannot call method '.$method);
  }

  my ($diff, $multi, @these_values, @other_values);

  #|| () avoids handing a array of a single undef value
  @these_values = $self->$method || ();
  @other_values = $obj->$method  || ();

  #Handle return types
  if( (scalar(@these_values) == 1) &&
      (scalar(@other_values) == 1) ){

    if( ref($these_values[0]) ){
      #This is allowed to be an Arrayref for scalar or Arrayref and Storable for storable

      #Storable test done in compare_storable_methods

      if(ref($these_values[0]) eq 'ARRAY'){
        @these_values = @{$these_values[0]};
        @other_values = @{$other_values[0]};
      }
    }
  }

  #Compare sizes and sort
  if(scalar(@these_values) != scalar(@other_values) ) {
    $diff = "Return size mismatch:\t".
              scalar(@these_values).', '.scalar(@other_values);
  }
  elsif(scalar(@these_values)){
    $multi = 1;

    if($storable){
        # Do storable check here as this is required for dbID sort. adds iteration
        # Move to compare_storable_methods?

        if(! eval { map { die() if ! $_->isa('Bio::EnsEMBL::Storable') }
                     (@these_values, @other_values);
                    1;}){
          throw($method.' method does not return Storable(s)');
        }

        @these_values = sort {$a->dbID <=> $b->dbID} @these_values;
        @other_values = sort {$a->dbID <=> $b->dbID} @other_values;
    }
    else{
      #scalar check done in compare_scalar_methods (for speed)
      @these_values = sort @these_values;
      @other_values = sort @other_values;
    }
  }

  return [\@these_values, \@other_values, $diff, $multi];
}

=head2 compare_to

  Args[1]    : Bio::EnsEMBL::Funcgen::Storable (mandatory)
  Args[2]    : Boolean - Optional 'shallow' - no object methods compared
  Args[3]    : Arrayref - Mandatory list of Storable method names each
               returning a Scalar or an Array or Arrayref of Scalars.
  Args[4]    : Arrayref - Mandatory ist of Storable method names each
               returning a Storable or an Array or Arrayref of Storables.
  Example    : my %shallow_diffs = %{$rset->compare_to($other_rset,
                                                       1,
                                                       [qw(get_scalar get_scalars)],
                                                       [qw(get_storable get_storables)]
                                                       )};
  Description: Compare this Storable to another based on the defined scalar
               and storable methods.
  Example    : my %shallow_diffs = %{$rset->compare_to($other_rset, 1)};
  Description: Compare this Storable to another.
  Returntype : Hashref of key attribute/method name keys and values which differ.
               Keys will always be the method which has been compared.
               Values can either be a error string, a hashref of diffs from a
               nested object, or an arrayref of error strings or hashrefs where
               a particular method returns more than one object.
  Exceptions : Throws if object class does not match self.
               Throws if depth level invalid.
  Caller     : Storables with compare_to wrapper defining method arguments
  Status     : At Risk

=cut

#We could potentially allow compare_to between different classes
#But this would require some Role definition i.e. we can guarantee
#that methods with the same name between classes will return the same types

sub compare_to {
  my ($self, $obj, $shallow, $scl_methods, $obj_methods) = @_;

  if(! (defined $obj &&
        ref($obj)    &&
        $obj->isa(ref($self))) ){
      throw('You must pass a valid '.ref($obj).' to compare_to '.ref($self));
  }

  my $diffs = $self->compare_scalar_methods($obj, $scl_methods);

  if(! $shallow){
    %$diffs = (
        %$diffs,
        %{$self->compare_storable_methods (
          $obj,
          $obj_methods
          )
        }
      );
  }

  return $diffs;
}
1;


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

namespace Microsoft.Identity.Client
{
    /// <summary>
    /// Represents log level in MSAL.
    /// For details, see <see href="https://aka.ms/msal-net-logging">MSAL logging</see>.
    /// </summary>
    public enum LogLevel
    {
        /// <summary>
        /// Includes logs of important health metrics to help with diagnostics of MSAL operations.
        /// </summary>
        Always = -1,

        /// <summary>
        /// Includes logs when something has gone wrong and an error was generated. Used for debugging and identifying problems.
        /// </summary>
        Error = 0,

        /// <summary>
        /// Includes logs in scenarios when there hasn't necessarily been an error or failure, but are intended for diagnostics and pinpointing problems.
        /// </summary>
        Warning = 1,

        /// <summary>
        /// Default. Includes logs of general events intended for informational purposes, not necessarily intended for debugging.
        /// </summary>
        Info = 2,

        /// <summary>
        /// Includes logs of the full details of library behavior.
        /// </summary>
        Verbose = 3
    }
}


text:
<?php
use \AframeVR\Tests\CommonHelper;

class SoundComponentTest extends PHPUnit_Framework_TestCase
{
    use CommonHelper;

    protected $component;

    // Setup function to instantiate de object to $this->scrap
    protected function setUp()
    {
        $aframe = new \AframeVR\Aframe();
        $this->component = $aframe->scene()
            ->entity()
            ->sound();
    }

    const A_INSTANCE = '\AframeVR\Core\Components\Sound\SoundComponent';

    public function a_get_instance()
    {
        return $this->component;
    }

    public function test_general()
    {
        $aframe = new \AframeVR\Aframe();

        $aframe->scene()
            ->entity()
            ->sound()
            ->autoplay();

        $this->assertInternalType('string', $aframe->scene()
            ->entity()
            ->sound()
            ->getDomAttributeString()
        );
        $this->assertInternalType('array', $this->component->getDOMAttributesArray());

    }

    public function test_props()
    {
        $this->component->autoplay(true);
        $this->component->on('move');
        $this->component->loop(true);
        $this->component->src('path');
        $this->component->volume(.5);

        $attrs = $this->component->getDOMAttributesArray();

        $this->assertArrayHasKey('autoplay', $attrs);
        $this->assertArrayHasKey('on', $attrs);
        $this->assertArrayHasKey('loop', $attrs);
        $this->assertArrayHasKey('src', $attrs);
        $this->assertArrayHasKey('volume', $attrs);
    }
}


text:
#include "TTHighpassButterworth2.h"

#define thisTTClass			TTHighpassButterworth2
#define thisTTClassName		"highpass.butterworth.2"
#define thisTTClassTags		"dspFilterLib, audio, processor, filter, highpass, butterworth"

TT_AUDIO_CONSTRUCTOR
{
	// register attributes
	addAttributeWithSetter(Frequency,	kTypeFloat64);
	addAttributeProperty(Frequency,			range,			TTValue(10.0, sr*0.475));
	addAttributeProperty(Frequency,			rangeChecking,	TT("clip"));

	// register for notifications from the parent class so we can allocate memory as required
	addUpdates(MaxNumChannels);
	// register for notifications from the parent class so we can recalculate coefficients as required
	addUpdates(SampleRate);
	// make the clear method available to the outside world
	addMessage(clear);

	// Set Defaults...
	setAttributeValue(kTTSym_maxNumChannels,	arguments);			// This attribute is inherited
	setAttributeValue(TT("frequency"),		1000.0);
	setProcessMethod(processAudio);
	setCalculateMethod(calculateValue);
}

TTHighpassButterworth2::~TTHighpassButterworth2()
{
	;
}

TTErr TTHighpassButterworth2::updateMaxNumChannels(const TTValue& oldMaxNumChannels, TTValue&)
{
	mX1.resize(mMaxNumChannels);
	mX2.resize(mMaxNumChannels);
	mY1.resize(mMaxNumChannels);
	mY2.resize(mMaxNumChannels);
	clear();
	return kTTErrNone;
}

TTErr TTHighpassButterworth2::updateSampleRate(const TTValue& oldSampleRate, TTValue&)
{
	TTValue	v(mFrequency);
	return setFrequency(v);
}

TTErr TTHighpassButterworth2::clear()
{
	mX1.assign(mMaxNumChannels, 0.0);
	mX2.assign(mMaxNumChannels, 0.0);
	mY1.assign(mMaxNumChannels, 0.0);
	mY2.assign(mMaxNumChannels, 0.0);
	return kTTErrNone;
}

TTErr TTHighpassButterworth2::setFrequency(const TTValue& newValue)
{
	mFrequency = newValue;

	mC = tan( kTTPi*(mFrequency/sr ) );
	mCSquared = mC * mC;
	calculateCoefficients();
	return kTTErrNone;
}

void TTHighpassButterworth2::calculateCoefficients()
{
	mA0 = 1 / (1 + kTTSqrt2*mC + mCSquared);
	mA1 = -2*mA0;
	//mA2 = mA0;
	mB1 = 2*mA0*( mCSquared - 1 );
	mB2 = mA0 * (1 - kTTSqrt2*mC + mCSquared);
}

inline TTErr TTHighpassButterworth2::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt channel)
{
	//y = TTAntiDenormal(mA0*x + mA1*mX1[channel] + mA2*mX2[channel] - mB1*mY1[channel] - mB2*mY2[channel]);
	// since mA0 = mA2, one can optimize to:
	y = mA0*(x + mX2[channel])+ mA1*mX1[channel] - mB1*mY1[channel] - mB2*mY2[channel];
	TTZeroDenormal(y);
	mX2[channel] = mX1[channel];
	mX1[channel] = x;
	mY2[channel] = mY1[channel];
	mY1[channel] = y;
	return kTTErrNone;
}

TTErr TTHighpassButterworth2::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(calculateValue);
}


text:
package org.apache.rampart.saml;

/**
 * Creates SAML assertion handlers based on assertion type.
 */
public class SAMLAssertionHandlerFactory {

    public static SAMLAssertionHandler createAssertionHandler(Object samlAssertion) {

        if (samlAssertion instanceof org.opensaml.saml2.core.Assertion) {
            SAMLAssertionHandler saml2AssertionHandler
                    = new SAML2AssertionHandler((org.opensaml.saml2.core.Assertion) samlAssertion);

            return saml2AssertionHandler;
        } else {
            SAML1AssertionHandler saml1AssertionHandler
                    = new SAML1AssertionHandler((org.opensaml.saml1.core.Assertion) samlAssertion);
            return saml1AssertionHandler;
        }
    }
}


text:
_.templateSettings.variable = "data";

// setup our initial object literal to pass to the templates.
var specials = {
    today:      new Date(),
    template:   _.template($("#specials-template").html())
};

var month   = ("0" + (specials.today.getMonth() + 1)).slice(-2);
var day     = ("0" + specials.today.getDate()).slice(-2);

specials.comparator = parseInt(month + day);

if (specials.comparator >= 321 && specials.comparator < 621) {
    // special is for spring of this year
    specials.season     = "Spring";
    specials.endMonth   = "June";
    specials.endDay     = "20";
    specials.endYear    = parseInt(specials.today.getFullYear());
}
else if (specials.comparator >= 621 && specials.comparator < 921) {
    // special is for summer of this year
    specials.season     = "Summer";
    specials.endMonth   = "September";
    specials.endDay     = "20";
    specials.endYear    = parseInt(specials.today.getFullYear());
}
else if (specials.comparator >= 921 && specials.comparator < 1221) {
    // special is for fall of this year
    specials.season     = "Fall";
    specials.endMonth   = "December";
    specials.endDay     = "20";
    specials.endYear    = parseInt(specials.today.getFullYear());
}
else if (specials.comparator >= 1221 || specials.comparator < 321) {
    // special is for winter - we need to bump the expiration year to this year + 1
    specials.season     = "Winter";
    specials.endMonth   = "March";
    specials.endDay     = "20";
    if (specials.comparator >= 1221) {
        specials.endYear    = parseInt(specials.today.getFullYear()) + 1;
    } else {
        specials.endYear = parseInt(specials.today.getFullYear());
    }
}

$('#specials .heading-block').html(
    _.template(specials.template(specials))
);


text:
<!-- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX -->
##Warm.toasts.Simple !!$Warm.toasts.Simple!!

###*Props (optional)*

- toast: Object

> An object containing the toast parameters.
> Default value is the info toast in the example below.

- dismissAction: Function

> A function to be triggered when...
> Default value is an empty function.

- customClasses: String

> A string of classes you want to apply (ex : "toto foo bar")
> Default value is "".

####*Example*
```
var Warm = require('warm-react');

var toast = {
    'type' : 'api-reconnected',
    'canStack' : true,
    'template' : 'info',
    'canDismiss' : false,
    'message' : "Toast info"
}
<Warm.toasts.Simple
    toast={toast}/>
```


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>CSP Test: referrer set "no-referrer-when-downgrade"/"default"</title>
<link rel="author" title="Intel" href="http://www.intel.com">
<link rel="author" title="Chunyan Wang" href="mailto:chunyanx.wang@intel.com">
<link rel="help" href="http://w3c.github.io/webappsec/specs/content-security-policy/csp-specification.dev.html#referrer">
<meta http-equiv="content-security-policy" content="referrer no-referrer-when-downgrade">


text:
require 'parsley/paths'

describe Parsley::Path::ArchiveRelative do
  describe '#initialize' do
    it 'sets the root and the path' do
      path = Parsley::Path::ArchiveRelative.new('orsr/2013/413.html', '/archive')
      path.full_path.should == '/archive/orsr/2013/413.html'
    end
  end

  describe '#dirname' do
    it 'returns parent archive-relative directory' do
      path = Parsley::Path::ArchiveRelative.new('orsr/2013/413.html', '/archive')
      path.dirname.should == Parsley::Path::ArchiveRelative.new('orsr/2013', '/archive')
    end
  end

  describe '#append' do
    it 'creates new archive-relative path by appending' do
      path = Parsley::Path::ArchiveRelative.new('orsr/2013/', '/archive')
      path.append('subdir').should == Parsley::Path::ArchiveRelative.new('orsr/2013/subdir', '/archive')
    end
  end
end

describe Parsley::Path::Full do
  describe '#initialize' do
    it 'uses the provided path' do
      path = Parsley::Path::Full.new('/tmp/foo')
      path.full_path.should == '/tmp/foo'
    end
  end

  describe '#dirname' do
    it 'returns parent full-path directory' do
      path = Parsley::Path::Full.new('/tmp/foo/raw.zip')
      path.dirname.should == Parsley::Path::Full.new('/tmp/foo')
    end
  end

  describe '#append' do
    it 'creates new full-path  by appending' do
      path = Parsley::Path::Full.new('/tmp/foo/')
      path.append('subdir').should == Parsley::Path::Full.new('/tmp/foo/subdir')
    end
  end
end


text:
<?php

/**
 * I'm still unclear on how to implement lights. This will do for now...
 */
abstract class Light {

}


text:
package com.boyuyun.base.sys.entity;

import java.io.Serializable;

import com.dhcc.common.db.page.Page;

/**
 * @author happyss
 * @fileName com.boyuyun.base.sys.entity.SysParam.java
 * @version 1.0
 * @createTime 2017-4-6 上午11:26:21
 * @description 类说明
 */
public class SysParam extends Page implements Serializable{
    private String paramKey;
    private String paramValue;

	public String getParamKey() {
		return paramKey;
	}
	public void setParamKey(String paramKey) {
		this.paramKey = paramKey;
	}
	public String getParamValue() {
		return paramValue;
	}
	public void setParamValue(String paramValue) {
		this.paramValue = paramValue;
	}
}