text:
'use strict';

angular.module('inspectionReport').controller('controllerInspectionReportDisplayEdit', ['$scope', '$filter', 'InspectionReportModel', 'InspectionReportDetailModel', '$state', 'PROVINCES', 'COMPANY_TYPES',
    function ($scope, $filter, InspectionReportModel, InspectionReportDetailModel, $state, PROVINCES, COMPANY_TYPES ) {
        var displayEdit = this;
        displayEdit.details = [];
        displayEdit.detailsToDelete = [];
        displayEdit.inspectionReportId = $scope.inspectionReportId;
        displayEdit.mode = $scope.mode;

        $scope.$watch('mode', function(newMode) {
            if (newMode) {
                displayEdit.mode = newMode;
            }
        });
        $scope.$watch('inspectionReportId', function(newInspectionReportId) {
            if (newInspectionReportId) {
                displayEdit.inspectionReportId = newInspectionReportId;
            }
        });

        displayEdit.provs = PROVINCES;
        displayEdit.companyTypes = COMPANY_TYPES;

        // Is this a new entry? If so, let's create it...
        if (displayEdit.mode === "add") {
            InspectionReportModel.getNew().then(
                function(res) {
                    displayEdit.inspectionReport = res;
                    $scope.$apply();
                }
            );
        } else
        // If this isn't a new entry,
        {
            InspectionReportModel.getModel(displayEdit.inspectionReportId).then(
                function(res) {
                    // console.log(res);

                    displayEdit.inspectionReport = res;
                    //displayEdit.details = displayEdit.inspectionReport.inspectionDetails;
                    $scope.$apply();
                },
                // If the ID is wrong let's go back to the list.
                function(data) {
                    $state.go('inspectionReport.list');
                }
            );
        }

        displayEdit.submit = function() {
            InspectionReportModel.saveModel(displayEdit.inspectionReport).then( function(res) {
                // console.log("======== HERE WE ARE", res);
                // $state.go('inspectionReport.view', { inspectionReportId: res._id});
            });
        };

        displayEdit.cancel = function() {
            if (displayEdit.mode === "add") {
                $state.go('inspectionReport.list');
            } else {
                $state.go('inspectionReport.view', {inspectionReportId: displayEdit.inspectionReport._id});
            }
        };

        displayEdit.remove = function() {
            if (confirm('Are you sure you want to delete this inspectionReport?')) {
                InspectionReportModel.delete(displayEdit.inspectionReportId).then(
                    function (res) {
                        $state.go('inspectionReport.list');
                    }
                );
            }
        };

        displayEdit.addDetail = function() {
            InspectionReportDetailModel.getNew().then(
                function(res) {
                    displayEdit.inspectionReport.inspectionDetails.push(res);

                    $scope.$apply();
                }
            );
        };

        displayEdit.removeDetail = function(detail) {
            // Add this to a list of details to delete from the DB on submit...
            //displayEdit.detailsToDelete.push(detail._id);

            // Remove it from the list we're displaying
            var index;
            //index = displayEdit.details.indexOf(detail);
            //displayEdit.details.splice(index, 1);

            // Remove it from the array in our inspectionReport object
            index = displayEdit.inspectionReport.inspectionDetails.indexOf(detail._id);
            displayEdit.inspectionReport.inspectionDetails.splice(index,1);

        };

    }
]);


text:
require 'renegade/branch_name'

module Xambassador
  # Update manifest after merge complete
  class UpdateManifest
    def initialize(pull_request)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
javascript-introduction
=======================

An introduction to javascript for newbies


text:
This is a simple React Redux Starter boilerplate. You can use it to start
working directly on your app code that matters, saving a lot of setup time.

This comes with Webpack 2 as module bundler, Babel to compile ES6 to vanilla
javascript and Bootstrap css and js.

## Getting started

```
git clone https://github.com/anuragaryan/webpack-react-redux-starter.git MyApp
cd MyApp
npm install
```

It comes with developement and production mode.

For Developement use: `npm run dev`
For Production use: `npm run prod`

### Resources

I'm using Stephen Grider's [ReduxSimpleStarter](https://github.com/StephenGrider/ReduxSimpleStarter)'s
directory structure for this boilerplate.


text:
var util = require('util'),
    exec = require('child_process').exec,
    applescript = require('applescript');

// Apple scripts
// ----------------------------------------------------------------------------
/*

 */
var scripts = {
    state: {
        file: 'get_state.applescript'
    },
    track: {
        file: 'get_track.applescript'
    },
    volumeUp: {
        file: 'volume_up.applescript'
    },
    volumeDown: {
        file: 'volume_down.applescript'
    },
    setVolume:
        'tell application "Spotify" to set sound volume to %s',
    play:
        'tell application "Spotify" to play',
    playTrack:
        'tell application "Spotify" to play track "%s"',
    playTrackInContext:
        'tell application "Spotify" to play track "%s" in context "%s"',
    playPause:
        'tell application "Spotify" to playpause',
    pause:
        'tell application "Spotify" to pause',
    next:
        'tell application "Spotify" to next track',
    previous:
        'tell application "Spotify" to previous track',
    jumpTo:
        'tell application "Spotify" to set player position to %s',
    isRunning:
        'get running of application "Spotify"',
    isRepeating:
        'tell application "Spotify" to return repeating',
    isShuffling:
        'tell application "Spotify" to return shuffling',
    setRepeating:
        'tell application "Spotify" to set repeating to %s',
    setShuffling:
        'tell application "Spotify" to set shuffling to %s',
    toggleRepeating: {
        file: 'toggle_repeating.applescript'
    },
    toggleShuffling: {
        file: 'toggle_shuffling.applescript'
    }
};

// Apple script execution
// ----------------------------------------------------------------------------

var scriptsPath = __dirname + '/scripts/';

var execScript = function(scriptName, params, callback){
    if (arguments.length === 2 && typeof params === 'function'){
        // second argument is the callback
        callback = params;
        params = undefined;
    }

    // applescript lib needs a callback, but callback is not always useful
    if (!callback) callback = function(){};

    if (typeof params !== 'undefined' && !Array.isArray(params)){
        params = [params];
    }

    var script = scripts[scriptName];

    if (typeof script === 'string'){
        if (typeof params !== 'undefined') script = util.format.apply(util, [script].concat(params));
        return applescript.execString(script, callback);
    } else if (script.file){
        return applescript.execFile(scriptsPath + script.file, callback);
    }
};

var createJSONResponseHandler = function(callback, flag){
    if (!callback) return null;
    return function(error, result){
        if (!error){
            try {
                result = JSON.parse(result);
            } catch(e){
                console.log(flag, result);
                return callback(e);
            }
            return callback(null, result);
        } else {
            return callback(error);
        }
    };
};

var createBooleanResponseHandler = function(callback){
    return function(error, response) {
        if (!error) {
            return callback(null, response === 'true');
        } else {
            return callback(error);
        }
    }
};

// API
// ----------------------------------------------------------------------------

// Open track

exports.open = function(uri, callback){
    return exec('open "'+uri+'"', callback);
};

exports.playTrack = function(track, callback){
    return execScript('playTrack', track, callback);
};

exports.playTrackInContext = function(track, context, callback){
    return execScript('playTrackInContext', [track, context], callback);
};

// Playback control

exports.play = function(callback){
    return execScript('play', callback);
};

exports.pause = function(callback){
    return execScript('pause', callback);
};

exports.playPause = function(callback){
    return execScript('playPause', callback);
};

exports.next = function(callback){
    return execScript('next', callback);
};

exports.previous = function(callback){
    return execScript('previous', callback);
};

exports.jumpTo = function(position, callback){
    return execScript('jumpTo', position, callback);
};

exports.setRepeating = function(repeating, callback){
    return execScript('setRepeating', repeating, callback);
};

exports.setShuffling = function(shuffling, callback){
    return execScript('setShuffling', shuffling, callback);
};

exports.toggleRepeating = function(callback){
    return execScript('toggleRepeating', callback);
};

exports.toggleShuffling = function(callback){
    return execScript('toggleShuffling', callback);
};

// Volume control

var mutedVolume = null;

exports.volumeUp = function(callback){
    mutedVolume = null;
    return execScript('volumeUp', callback);
};

exports.volumeDown = function(callback){
    mutedVolume = null;
    return execScript('volumeDown', callback);
};

exports.setVolume = function(volume, callback){
    mutedVolume = null;
    return execScript('setVolume', volume, callback);
};

exports.muteVolume = function(callback){
    return execScript('state', createJSONResponseHandler(function(err, state){
        exports.setVolume(0, callback);
        mutedVolume = state.volume;
    }));
};

exports.unmuteVolume = function(callback){
    if (mutedVolume !== null) {
        return exports.setVolume(mutedVolume, callback);
    }
};

// State retrieval

exports.getTrack = function(callback){
    return execScript('track', createJSONResponseHandler(callback, 'track'));
};

exports.getState = function(callback){
    return execScript('state', createJSONResponseHandler(callback, 'state'));
};

exports.isRunning = function(callback) {
    return execScript('isRunning', createBooleanResponseHandler(callback));
};

exports.isRepeating = function(callback){
    return execScript('isRepeating', createBooleanResponseHandler(callback));
};

exports.isShuffling = function(callback){
    return execScript('isShuffling', createBooleanResponseHandler(callback));
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
             xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="casebook_db" transaction-type="RESOURCE_LOCAL">
        <!-- Persistence provider -->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <!-- Entity classes -->
        <properties>
            <!-- The JDBC driver of your database -->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <!-- The JDBC URL to the database instance -->
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/casebook_db?useSSL=false&createDatabaseIfNotExist=true"/>
            <!-- The database username -->
            <property name="javax.persistence.jdbc.user" value="root"/>
            <!-- The database password -->
            <property name="javax.persistence.jdbc.password" value="1234"/>
            <!-- To create the Tables dynamically -->
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.enable_lazy_load_no_trans" value="true"/>
        </properties>
    </persistence-unit>
</persistence>


text:
Using the [Tool - O2 Cmd SpringMVC v1.0.exe](https://dl.dropbox.com/u/81532342/O2Platform%20Tools/Spring%20MVC/Tool%20-%20O2%20Cmd%20SpringMVC%20v1.0.exe)  (see more details on this post: [Tool - O2 Cmd SpringMVC v1.0.exe - as standalone exe](http://diniscruz.blogspot.co.uk/2012/10/tool-o2-cmd-springmvc-v10exe-as.html)) here is how to start using it on [ThreadFix ](http://code.google.com/p/threadfix/) from Denim Group (_"ThreadFix is a software vulnerability aggregation and management system that helps organizations aggregate vulnerability data, generate virtual patches, and interact with software defect tracking systems."_)

I downloaded the ThreadFix binaries from the [download page](http://code.google.com/p/threadfix/downloads/list) : [ThreadFix_1_0_1.zip](http://code.google.com/p/threadfix/downloads/detail?name=ThreadFix_1_0_1.zip&can=2&q=)
And since I couldn't find a download for the source code, I used git by executing:**_ $ git clone https://code.google.com/p/threadfix/_**

Then I unzipped the [ThreadFix_1_0_1.zip](http://code.google.com/p/threadfix/downloads/detail?name=ThreadFix_1_0_1.zip&can=2&q=)  files into a local folder and executed 'threadfix.bat'

![](images/CropperCapture_5B71_5D1.jpg)

This will start tomcat, and more importantly extract the threadfix.war file into the webapps folder, where I zipped the classes folder:

![](images/CropperCapture_5B72_5D.jpg)

which I then dropped into the O2 Spring MVC tool:

![](images/CropperCapture_5B70_5D.jpg)

The first time there is a source code to be opened in the document viewer area, you will be asked to resolve the files, which in this case it points to here:

![](images/CropperCapture_5B73_5D1.jpg)

Interestingly there is quite a lot meat here. For example, if you look for the ModelAttribute mappings there is quite a lot cases where they use this dangerous coding technique:

![](images/CropperCapture_5B74_5D1.jpg)

With some of the model classes looking quite big, there could be a number of spring [mvc autobinding issues](http://diniscruz.blogspot.co.uk/2011/07/two-security-vulnerabilities-in-spring.html) here:

![](images/CropperCapture_5B75_5D.jpg)


text: export { foo as bar } from './empty.js';


text:
#ifndef EVENTOS_SCHEDULER_H_
#define EVENTOS_SCHEDULER_H_
#ifdef __cplusplus
extern "C" {
#endif

/**
 * \file eventOS_scheduler.h
 * \ingroup nanostack-eventloop
 * \brief Event scheduler's control functions.
 */

#include "ns_types.h"

/* Compatibility with older ns_types.h */
#ifndef NS_NORETURN
#define NS_NORETURN
#endif

/**
 * \brief Initialise event scheduler.
 *
 */
extern void eventOS_scheduler_init(void);

/**
 * Process one event from event queue.
 * Do not call this directly from application. Requires to be public so that simulator can call this.
 * Use eventOS_scheduler_run() or eventOS_scheduler_run_until_idle().
 * \return true If there was event processed, false if the event queue was empty.
 */
bool eventOS_scheduler_dispatch_event(void);

/**
 * \brief Process events until no more events to process.
 */
extern void eventOS_scheduler_run_until_idle(void);

/**
 * \brief Start Event scheduler.
 * Loops forever processing events from the queue.
 * Calls eventOS_scheduler_idle() whenever event queue is empty.
 */
NS_NORETURN extern void eventOS_scheduler_run(void);
/**
 * \brief Disable Event scheduler Timers
 *
 * \return 0 Timer Stop OK
 * \return -1 Timer Stop Fail
 *
 * */
int eventOS_scheduler_timer_stop(void);

/**
 * \brief Synch Event scheduler timer after sleep
 *
 * \param sleep_ticks time in milli seconds
 *
 * \return 0 Timer Synch OK
 * \return -1 Timer Synch & Start Fail
 *
 * */
int eventOS_scheduler_timer_synch_after_sleep(uint32_t sleep_ticks);

/**
 * \brief Read current active Tasklet ID
 *
 * This function not return valid information called inside interrupt
 *
 * \return curret active tasklet id
 *
 * */
extern int8_t eventOS_scheduler_get_active_tasklet(void);

/**
 * \brief Set manually Active Tasklet ID
 *
 * \param tasklet requested tasklet ID
 *
 * */
extern  void eventOS_scheduler_set_active_tasklet(int8_t tasklet);

/**
 * \brief Event scheduler loop idle Callback.

 * Note! This method is called only by eventOS_scheduler_run, needs to be
 * ported for the platform only if you are using eventOS_scheduler_run().
 */
extern void eventOS_scheduler_idle(void);

/**
 * \brief This function will be called when stack enter idle state and start
 *  waiting signal.
 *
 * Note! This method is called only by reference implementation of idle. Needs
 * to be ported for the platform only if you are using reference implementation.
 */
extern void eventOS_scheduler_wait(void);

/**
 * \brief This function will be called when stack receives an event.
 */
extern void eventOS_scheduler_signal(void);

/**
 * \brief This function will be called when stack can enter deep sleep state in detected time.
 *
 * Note! This method is called only by reference implementation of idle. Needs to be
 * ported for the platform only if you are using reference implementation.
 *
 * \param sleep_time_ms Time in milliseconds to sleep
 * \return time slept in milliseconds
 */
extern uint32_t eventOS_scheduler_sleep(uint32_t sleep_time_ms);

/**
 * \brief Lock a thread against the event loop thread
 *
 * This method can be provided by multi-threaded platforms to allow
 * mutual exclusion with the event loop thread, for cases where
 * code wants to work with both the event loop and other threads.
 *
 * A typical platform implementation would claim the same mutex
 * before calling eventOS_scheduler_run() or
 * eventOS_scheduler_dispatch(), and release it during
 * eventOS_scheduler_idle().
 *
 * The mutex must count - nested calls from one thread return
 * immediately. Thus calling this from inside an event callback
 * is harmless.
 */
extern void eventOS_scheduler_mutex_wait(void);

/**
 * \brief Release the event loop mutex
 *
 * Release the mutex claimed with eventOS_scheduler_mutex_wait(),
 * allowing the event loop to continue processing.
 */
extern void eventOS_scheduler_mutex_release(void);

/**
 * \brief Check if the current thread owns the event mutex
 *
 * Check if the calling thread owns the scheduler mutex.
 * This allows the ownership to be asserted if a function
 * requires the mutex to be locked externally.
 *
 * The function is only intended as a debugging aid for
 * users of eventOS_scheduler_mutex_wait() - it is not
 * used by the event loop core itself.
 *
 * If the underlying mutex system does not support it,
 * this may be implemented to always return true.
 *
 * \return true if the current thread owns the mutex
 */
extern bool eventOS_scheduler_mutex_am_owner(void);

#ifdef __cplusplus
}
#endif

#endif /* EVENTOS_SCHEDULER_H_ */


text:
#pragma once
#include <aws/kafkaconnect/KafkaConnect_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace KafkaConnect
{
namespace Model
{

  /**
   *
The location of an object in Amazon S3.

See Also:
   AWS
   * API Reference

   */
  class AWS_KAFKACONNECT_API S3Location
  {
  public:
    S3Location();
    S3Location(Aws::Utils::Json::JsonView jsonValue);
    S3Location& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The Amazon Resource Name (ARN) of an S3 bucket.

     */
    inline const Aws::String& GetBucketArn() const{ return m_bucketArn; }

    /**
     *
The Amazon Resource Name (ARN) of an S3 bucket.

     */
    inline bool BucketArnHasBeenSet() const { return m_bucketArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of an S3 bucket.

     */
    inline void SetBucketArn(const Aws::String& value) { m_bucketArnHasBeenSet = true; m_bucketArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of an S3 bucket.

     */
    inline void SetBucketArn(Aws::String&& value) { m_bucketArnHasBeenSet = true; m_bucketArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of an S3 bucket.

     */
    inline void SetBucketArn(const char* value) { m_bucketArnHasBeenSet = true; m_bucketArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of an S3 bucket.

     */
    inline S3Location& WithBucketArn(const Aws::String& value) { SetBucketArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of an S3 bucket.

     */
    inline S3Location& WithBucketArn(Aws::String&& value) { SetBucketArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of an S3 bucket.

     */
    inline S3Location& WithBucketArn(const char* value) { SetBucketArn(value); return *this;}

    /**
     *
The file key for an object in an S3 bucket.

     */
    inline const Aws::String& GetFileKey() const{ return m_fileKey; }

    /**
     *
The file key for an object in an S3 bucket.

     */
    inline bool FileKeyHasBeenSet() const { return m_fileKeyHasBeenSet; }

    /**
     *
The file key for an object in an S3 bucket.

     */
    inline void SetFileKey(const Aws::String& value) { m_fileKeyHasBeenSet = true; m_fileKey = value; }

    /**
     *
The file key for an object in an S3 bucket.

     */
    inline void SetFileKey(Aws::String&& value) { m_fileKeyHasBeenSet = true; m_fileKey = std::move(value); }

    /**
     *
The file key for an object in an S3 bucket.

     */
    inline void SetFileKey(const char* value) { m_fileKeyHasBeenSet = true; m_fileKey.assign(value); }

    /**
     *
The file key for an object in an S3 bucket.

     */
    inline S3Location& WithFileKey(const Aws::String& value) { SetFileKey(value); return *this;}

    /**
     *
The file key for an object in an S3 bucket.

     */
    inline S3Location& WithFileKey(Aws::String&& value) { SetFileKey(std::move(value)); return *this;}

    /**
     *
The file key for an object in an S3 bucket.

     */
    inline S3Location& WithFileKey(const char* value) { SetFileKey(value); return *this;}

    /**
     *
The version of an object in an S3 bucket.

     */
    inline const Aws::String& GetObjectVersion() const{ return m_objectVersion; }

    /**
     *
The version of an object in an S3 bucket.

     */
    inline bool ObjectVersionHasBeenSet() const { return m_objectVersionHasBeenSet; }

    /**
     *
The version of an object in an S3 bucket.

     */
    inline void SetObjectVersion(const Aws::String& value) { m_objectVersionHasBeenSet = true; m_objectVersion = value; }

    /**
     *
The version of an object in an S3 bucket.

     */
    inline void SetObjectVersion(Aws::String&& value) { m_objectVersionHasBeenSet = true; m_objectVersion = std::move(value); }

    /**
     *
The version of an object in an S3 bucket.

     */
    inline void SetObjectVersion(const char* value) { m_objectVersionHasBeenSet = true; m_objectVersion.assign(value); }

    /**
     *
The version of an object in an S3 bucket.

     */
    inline S3Location& WithObjectVersion(const Aws::String& value) { SetObjectVersion(value); return *this;}

    /**
     *
The version of an object in an S3 bucket.

     */
    inline S3Location& WithObjectVersion(Aws::String&& value) { SetObjectVersion(std::move(value)); return *this;}

    /**
     *
The version of an object in an S3 bucket.

     */
    inline S3Location& WithObjectVersion(const char* value) { SetObjectVersion(value); return *this;}

  private:

    Aws::String m_bucketArn;
    bool m_bucketArnHasBeenSet;

    Aws::String m_fileKey;
    bool m_fileKeyHasBeenSet;

    Aws::String m_objectVersion;
    bool m_objectVersionHasBeenSet;
  };

} // namespace Model
} // namespace KafkaConnect
} // namespace Aws


text:
<?php

namespace Doctrine\Bundle\DoctrineCacheBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * Cache Bundle Extension
 *
 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author Fabio B. Silva <fabio.bat.silva@gmail.com>
 * @author Danilo Cabello <danilo.cabello@gmail.com>
 */
class DoctrineCacheExtension extends Extension
{
    /**
     * @var \Doctrine\Bundle\DoctrineCacheBundle\DependencyInjection\CacheProviderLoader
     */
    private $loader;

    /**
     * @param \Doctrine\Bundle\DoctrineCacheBundle\DependencyInjection\CacheProviderLoader $loader
     */
    public function __construct(CacheProviderLoader $loader = null)
    {
        $this->loader = $loader ?: new CacheProviderLoader;
    }

    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $rootConfig    = $this->processConfiguration($configuration, $configs);

        $locator = new FileLocator(__DIR__ . '/../Resources/config/');
        $loader  = new XmlFileLoader($container, $locator);

        $loader->load('services.xml');

        $this->loadAcl($rootConfig, $container);
        $this->loadCustomProviders($rootConfig, $container);
        $this->loadCacheProviders($rootConfig, $container);
        $this->loadCacheAliases($rootConfig, $container);
    }

    /**
     * @param array                                                     $rootConfig
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder   $container
     */
    protected function loadAcl(array $rootConfig, ContainerBuilder $container)
    {
        if ( ! isset($rootConfig['acl_cache']['id'])) {
            return;
        }

        $aclCacheDefinition = new Definition(
            $container->getParameter('doctrine_cache.security.acl.cache.class'),
            array(
                new Reference($rootConfig['acl_cache']['id']),
                new Reference('security.acl.permission_granting_strategy'),
            )
        );

        $aclCacheDefinition->setPublic(false);

        $container->setDefinition('doctrine_cache.security.acl.cache', $aclCacheDefinition);
        $container->setAlias('security.acl.cache', 'doctrine_cache.security.acl.cache');
    }

    /**
     * @param array                                                     $rootConfig
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder   $container
     */
    protected function loadCacheProviders(array $rootConfig, ContainerBuilder $container)
    {
        foreach ($rootConfig['providers'] as $name => $config) {
            $this->loader->loadCacheProvider($name, $config, $container);
        }
    }

    /**
     * @param array                                                     $rootConfig
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder   $container
     */
    protected function loadCacheAliases(array $rootConfig, ContainerBuilder $container)
    {
        foreach ($rootConfig['aliases'] as $alias => $name) {
            $container->setAlias($alias, 'doctrine_cache.providers.' . $name);
        }
    }

    /**
     * @param array                                                     $rootConfig
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder   $container
     */
    protected function loadCustomProviders(array $rootConfig, ContainerBuilder $container)
    {
        foreach ($rootConfig['custom_providers'] as $type => $rootConfig) {
            $providerParameterName   = $this->loader->getCustomProviderParameter($type);
            $definitionParameterName = $this->loader->getCustomDefinitionClassParameter($type);

            $container->setParameter($providerParameterName, $rootConfig['prototype']);

            if ($rootConfig['definition_class']) {
                $container->setParameter($definitionParameterName, $rootConfig['definition_class']);
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getAlias()
    {
        return 'doctrine_cache';
    }

    /**
     * {@inheritDoc}
     */
    public function getXsdValidationBasePath()
    {
        return __DIR__ . '/../Resources/config/schema';
    }

    /**
     * {@inheritDoc}
     **/
    public function getNamespace()
    {
        return 'http://doctrine-project.org/schemas/symfony-dic/cache';
    }
}


text:
#include <aws/events/model/Rule.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

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

namespace Aws
{
namespace CloudWatchEvents
{
namespace Model
{

Rule::Rule() :
    m_nameHasBeenSet(false),
    m_arnHasBeenSet(false),
    m_eventPatternHasBeenSet(false),
    m_state(RuleState::NOT_SET),
    m_stateHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_scheduleExpressionHasBeenSet(false),
    m_roleArnHasBeenSet(false)
{
}

Rule::Rule(JsonView jsonValue) :
    m_nameHasBeenSet(false),
    m_arnHasBeenSet(false),
    m_eventPatternHasBeenSet(false),
    m_state(RuleState::NOT_SET),
    m_stateHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_scheduleExpressionHasBeenSet(false),
    m_roleArnHasBeenSet(false)
{
  *this = jsonValue;
}

Rule& Rule::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Name"))
  {
    m_name = jsonValue.GetString("Name");

    m_nameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Arn"))
  {
    m_arn = jsonValue.GetString("Arn");

    m_arnHasBeenSet = true;
  }

  if(jsonValue.ValueExists("EventPattern"))
  {
    m_eventPattern = jsonValue.GetString("EventPattern");

    m_eventPatternHasBeenSet = true;
  }

  if(jsonValue.ValueExists("State"))
  {
    m_state = RuleStateMapper::GetRuleStateForName(jsonValue.GetString("State"));

    m_stateHasBeenSet = true;
  }

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

    m_descriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ScheduleExpression"))
  {
    m_scheduleExpression = jsonValue.GetString("ScheduleExpression");

    m_scheduleExpressionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("RoleArn"))
  {
    m_roleArn = jsonValue.GetString("RoleArn");

    m_roleArnHasBeenSet = true;
  }

  return *this;
}

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

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_arnHasBeenSet)
  {
   payload.WithString("Arn", m_arn);

  }

  if(m_eventPatternHasBeenSet)
  {
   payload.WithString("EventPattern", m_eventPattern);

  }

  if(m_stateHasBeenSet)
  {
   payload.WithString("State", RuleStateMapper::GetNameForRuleState(m_state));
  }

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

  }

  if(m_scheduleExpressionHasBeenSet)
  {
   payload.WithString("ScheduleExpression", m_scheduleExpression);

  }

  if(m_roleArnHasBeenSet)
  {
   payload.WithString("RoleArn", m_roleArn);

  }

  return payload;
}

} // namespace Model
} // namespace CloudWatchEvents
} // namespace Aws


text:
package org.familysearch.platform.ct;

import org.gedcomx.common.URI;
import org.gedcomx.rt.EnumUtil;

/**
 * Enumeration of FamilySearch-specific identifier types.
 */
/*
@XmlQNameEnum (
  base = XmlQNameEnum.BaseType.URI
)
*/
public enum FamilySearchIdentifierType
{

  /**
   * The identifier for the parent relationship pair for a given relationship.
   */
  ChildAndParentsRelationship,

  //  @XmlUnknownQNameEnumValue
  OTHER;

  /**
   * Return the QName value for this enum.
   *
   * @return The QName value for this enum.
   */
  public URI toQNameURI() {
    return URI.create( EnumUtil.toURIValue( this ));
  }

  /**
   * Get the enumeration from the QName.
   *
   * @param qname The qname.
   * @return The enumeration.
   */
  public static FamilySearchIdentifierType fromQNameURI( URI qname ) {
    return EnumUtil.fromURIValue( qname.toString(), FamilySearchIdentifierType.class );
  }
}


text:
/**
 * Console Wrapper Create function
 */
var console_wrapper_create = function(){

	var before_enabled 	= false;
	var maxlogcnt 		= 5;
	var recent_logs = [];
	var before_console = {
		log :function(){},
		warn : function() {},
		error : function() {},
		info : function(){}
	};

	/**
	 * Console Log Wrapping Object
	 *
	 * @constructor
	 * @type {Object}
	 */
	var ConsoleLogWrapper = {};

	/**
	 * Log Pushing
	 * @param  {string} type log type ( wran, info, log, err )
	 * @param  {string} msg  log message
	 */
	var push_log = function( type, _arguments ){

		var args = Array.prototype.slice.call(_arguments);

		// log type
		// 		datetime	type	msg
		var now = new Date();
		var datetime = now.format("yyyy-mm-dd HH:MM:ss");

		var msg = args.join(', ').replace(/[\r|\n]/g, ' ');

		if( msg.length > 100 ){
			msg = msg.substring( 0, 100 );	// cut msg one line maximum is 100
		}

		var log = datetime + "\t" + type + "\t" + msg;

		recent_logs.push( log );

		if( recent_logs.length > maxlogcnt ){
			recent_logs.splice( 0, recent_logs.length - maxlogcnt );
		}

	};

	/**
	 * log
	 */
	ConsoleLogWrapper.log = function( ){

		push_log( "log", arguments );
		//Function.prototype.apply.call( before_console.log, console, [arguments.toString()] );
		Function.prototype.apply.call( before_console.log, console, arguments );
	};

	/**
	 * warn
	 */
	ConsoleLogWrapper.warn = function( ){
		push_log( "warn", arguments );
		Function.prototype.apply.call( before_console.warn, console, arguments );
	};

	/**
	 * error
	 */
	ConsoleLogWrapper.error = function( ){
		push_log( "error", arguments );
		Function.prototype.apply.call( before_console.error, console, arguments );
	};

	/**
	 * info
	 */
	ConsoleLogWrapper.info = function(){
		push_log( "info", arguments );
		Function.prototype.apply.call( before_console.info, console, arguments );
	};

	/**
	 * get recently logs
	 * @return {string array} stored logs
	 */
	ConsoleLogWrapper.getLogs = function(){
		return recent_logs;
	}

	/**
	 * Copy log object
	 * @param  {object} src console or console wrapper
	 * @param  {[object]} dst console wrapper
	 */
	function logcopyer( src, dst ){
		dst.log = src.log;
		dst.warn = src.warn;
		dst.error = src.error;
		dst.info = src.info;
	}

	/**
	 * enable or disable function
	 *
	 * @param  {boolean} enabled true : enable, false : disable
	 */
	ConsoleLogWrapper.enable = function( enabled ){

		console.loglog = console.log;

		if( !enabled && before_enabled ){

			if( console ){
				logcopyer( before_console, console );
			}
			else if( window.console ){
				logcopyer( before_console, window.console );
			}

		}else{

			if( console ){
				logcopyer( console, before_console );
				logcopyer( ret, console );
			}
			else if( window.console ){
				logcopyer( window.console, before_console );
				logcopyer( ret, window.console );
			}else{
				// ie or not supported browser mode
				console = ret;
				window.console = ret;
			}

		}

		before_enabled = enabled;
	}

	urqa.setConsoleLogObj( ret );

	// test code
	//ret.init();

	//console.log("test", 'aaaa', 1234 );
	//console.warn("test", 'aaaa', 1234 );
	//console.error("test", 'aaaa', 1234 );
	//console.info("test", 'aaaa', 1234 );

};
console_wrapper_create();


text:
The basic idea behind the {{\luya\web\Element}} component is based on a behavior known from **AngularJS Directives**. In a huge web project you have several HTML parts you may have to use in several locations but with different contents.
Lets assume you have a teaser box which contains a title and a picture. So variables are the picture and the title, but the HTML base will be the same on all pages.

Basic example of a HTML partial wich will be reused in different pages with different contents:

```html
<div class="teaser-box">
    <h1>Title</h1>
    <p>Description</p>
    <a class="btn btn-primary" href="https://luya.io">Read more</a>
</div>
```

Now you can create a HTML element component for this.

## Create HTML element component and use it

The default path for the file which contains all configured elements is `@app/views/elements.php` defined by {{luya\web\Element::$configFile}}. An element is defined by a *name* and a corresponding *closure*. Below, an example setup for the `elements.php` file:

```php
<?php
return [
    'button' => function($href, $name) {
        return "<a class=\"btn btn-primary\" href=\"{$href}\">{$name}</a>";
    },
    'teaserbox' => function($title, $description, $buttonHref, $buttonName) {
        return '<div class="teaser-box"><h1>'.$title.'</h1><p>'.$description.'</p>'.$this->button($buttonHref, $buttonName).'</div>';
    },
];
```

> Elements can also be added in a more dynamic way, e.g. by accessing the *element* component in your controller:
`Yii::$app->element->addElement('elementName', function() { });`

To use a defined element you can access the `element` component which is registered to any LUYA project by default, `Yii::$app->element`.

You can directly call the name of your element:

```php
echo Yii::$app->element->button('https://luya.io', 'Go to website');
```

Where `button` is the name of the element closure defined in your elements.php file.

## Render a view file

When you have a more complex HTML element, the possibility to concate all the HTML parts looks a bit ugly, therefore you can also render a view file with the function `render()`. This method will render a defined PHP template which is located in *@app/views/elements/__NAME__.php*.

```php
'myElementButton' => function($href, $name) {
    return $this->render('button', ['href' => $href, 'name' => $name ]);
}
```

The above example will render the element file, e.g. `button.php` with the parameters `['href' => $href, 'name' => $name ]`.
The view file for the button must be stored in the folder `@app/views/elements` with the name `button.php`. An example content of `@app/views/elements/button.php` could look like this:

```php
<a href="<?= $href; ?>" class="btn btn-primary"><?= $name; ?></a>
```

### Recursive rendering

Perhaps you need to render another element component inside another template, therefore just use the global element component  (`Yii::$app->element`) for recursive rendering, e.g.:

```php
<div class="teaser-box">
    <h1><?= $title; ?></h1>
    <p><?= $description; ?></p>
    <?= Yii::$app->element->button($buttonHref, $buttonName); ?>
</div>
```

Of course the above example requires as well that the variables `title`, `description`, `buttonHref` and `buttonName` have been passed to the recursiv element rendering of the button.

# Automatic styleguide from elements

LUYA provides a styleguide module which renders all the available elements with example content, so you can share all the elements with other designer to discuss and test changes based on elements instead on a finished web page.
This gives you the ability to make more specific changes and test them properly before the final implementation.

First adding the LUYA styleguide module to your Composer json:

```sh
composer require luyadev/luya-module-styleguide
```

Then configure the module in your project config file, the password is protecting the styleguide page by default:

```php
return [
    // ...
    'modules' => [
        // ...
        'styleguide' => [
            'class' => 'luya\styleguide\Module',
            'password' => 'myguide',
            'assetFiles' => [
                'app\assets\ResourcesAsset',
            ],
        ]
    ]
]
```

If the styleguide module is successfully configured it is accesible it trough the url: `yourwebsite.com/styleguide`

## Mocking arguments

The styleguide will automatically use default values for each element. Assuming you have an element argument `$foo` this argument will recieve the value `$foo` inside the styleguide.

```php
'test' => function($foo) {
    return '<p>'.$foo.'</p>';
}
```

The styleguide would print the element as:

```php
<p>$foo</p>
```

In order to mock the arguments with more meaning full values you can pass them when creating the element inside the `elements.php` file:

```php
<?php
return [
    'test' => [function($foo) {
        return '<p>'.$foo.'</p>';
    }, [
        'foo' => 'Mocking value for $foo',
    ]],
];
```

As now the element `test` has a mocked $foo parameter and will return the following rendered content in the styleguide:

```php
<p>Mocking value for $foo</p>
```

> The mocking element options will not affect your elements in any way when using them in your application and is only used in the styleguide


text:
namespace Microsoft.Azure.Management.Sql.Fluent.Models
{
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime;
    using System.Runtime.Serialization;

    /// <summary>
    /// Defines values for AutomaticTuningDisabledReason.
    /// </summary>
    [JsonConverter(typeof(StringEnumConverter))]
    public enum AutomaticTuningDisabledReason
    {
        [EnumMember(Value = "Default")]
        Default,
        [EnumMember(Value = "Disabled")]
        Disabled,
        [EnumMember(Value = "AutoConfigured")]
        AutoConfigured,
        [EnumMember(Value = "InheritedFromServer")]
        InheritedFromServer,
        [EnumMember(Value = "QueryStoreOff")]
        QueryStoreOff,
        [EnumMember(Value = "QueryStoreReadOnly")]
        QueryStoreReadOnly,
        [EnumMember(Value = "NotSupported")]
        NotSupported
    }
    internal static class AutomaticTuningDisabledReasonEnumExtension
    {
        internal static string ToSerializedValue(this AutomaticTuningDisabledReason? value)
        {
            return value == null ? null : ((AutomaticTuningDisabledReason)value).ToSerializedValue();
        }

        internal static string ToSerializedValue(this AutomaticTuningDisabledReason value)
        {
            switch( value )
            {
                case AutomaticTuningDisabledReason.Default:
                    return "Default";
                case AutomaticTuningDisabledReason.Disabled:
                    return "Disabled";
                case AutomaticTuningDisabledReason.AutoConfigured:
                    return "AutoConfigured";
                case AutomaticTuningDisabledReason.InheritedFromServer:
                    return "InheritedFromServer";
                case AutomaticTuningDisabledReason.QueryStoreOff:
                    return "QueryStoreOff";
                case AutomaticTuningDisabledReason.QueryStoreReadOnly:
                    return "QueryStoreReadOnly";
                case AutomaticTuningDisabledReason.NotSupported:
                    return "NotSupported";
            }
            return null;
        }

        internal static AutomaticTuningDisabledReason? ParseAutomaticTuningDisabledReason(this string value)
        {
            switch( value )
            {
                case "Default":
                    return AutomaticTuningDisabledReason.Default;
                case "Disabled":
                    return AutomaticTuningDisabledReason.Disabled;
                case "AutoConfigured":
                    return AutomaticTuningDisabledReason.AutoConfigured;
                case "InheritedFromServer":
                    return AutomaticTuningDisabledReason.InheritedFromServer;
                case "QueryStoreOff":
                    return AutomaticTuningDisabledReason.QueryStoreOff;
                case "QueryStoreReadOnly":
                    return AutomaticTuningDisabledReason.QueryStoreReadOnly;
                case "NotSupported":
                    return AutomaticTuningDisabledReason.NotSupported;
            }
            return null;
        }
    }
}


text:
import { elt, range, removeChildren, removeChildrenAndAdd } from "./dom"
import { ie, ie_version } from "./browser"

// Detect drag-and-drop
export var dragAndDrop = function() {
  // There is *some* kind of drag-and-drop support in IE6-8, but I
  // couldn't get it to work yet.
  if (ie && ie_version < 9) return false
  var div = elt('div')
  return "draggable" in div || "dragDrop" in div
}()

var zwspSupported
export function zeroWidthElement(measure) {
  if (zwspSupported == null) {
    var test = elt("span", "\u200b")
    removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]))
    if (measure.firstChild.offsetHeight != 0)
      zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8)
  }
  var node = zwspSupported ? elt("span", "\u200b") :
    elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px")
  node.setAttribute("cm-text", "")
  return node
}

// Feature-detect IE's crummy client rect reporting for bidi text
var badBidiRects
export function hasBadBidiRects(measure) {
  if (badBidiRects != null) return badBidiRects
  var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"))
  var r0 = range(txt, 0, 1).getBoundingClientRect()
  var r1 = range(txt, 1, 2).getBoundingClientRect()
  removeChildren(measure)
  if (!r0 || r0.left == r0.right) return false // Safari returns null in some cases (#2780)
  return badBidiRects = (r1.right - r0.right < 3)
}

// See if "".split is the broken IE version, if so, provide an
// alternative way to split lines.
export var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function(string) {
  var pos = 0, result = [], l = string.length
  while (pos <= l) {
    var nl = string.indexOf("\n", pos)
    if (nl == -1) nl = string.length
    var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl)
    var rt = line.indexOf("\r")
    if (rt != -1) {
      result.push(line.slice(0, rt))
      pos += rt + 1
    } else {
      result.push(line)
      pos = nl + 1
    }
  }
  return result
} : function(string){return string.split(/\r\n?|\n/)}

export var hasSelection = window.getSelection ? function(te) {
  try { return te.selectionStart != te.selectionEnd }
  catch(e) { return false }
} : function(te) {
  try {var range = te.ownerDocument.selection.createRange()}
  catch(e) {}
  if (!range || range.parentElement() != te) return false
  return range.compareEndPoints("StartToEnd", range) != 0
}

export var hasCopyEvent = (function() {
  var e = elt("div")
  if ("oncopy" in e) return true
  e.setAttribute("oncopy", "return;")
  return typeof e.oncopy == "function"
})()

var badZoomedRects = null
export function hasBadZoomedRects(measure) {
  if (badZoomedRects != null) return badZoomedRects
  var node = removeChildrenAndAdd(measure, elt("span", "x"))
  var normal = node.getBoundingClientRect()
  var fromRange = range(node, 0, 1).getBoundingClientRect()
  return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
}


text:
function Get-RubrikSetting
{
  <#
      .SYNOPSIS
      Connects to Rubrik and retrieves the current Rubrik cluster settings

      .DESCRIPTION
      The Get-RubrikSetting cmdlet will retrieve the cluster settings actively running on the system. This does require authentication.

      .NOTES
      Adapted by Adam Shuttleworth from scripts by Chris Wahl for community usage

      .LINK
      https://rubrik.gitbook.io/rubrik-sdk-for-powershell/command-documentation/reference/get-rubriksetting

      .EXAMPLE
      Get-RubrikSetting
      This will return the running cluster settings on the currently connected Rubrik cluster
  #>

  [CmdletBinding()]
  Param(
    # ID of the Rubrik cluster or me for self
    [String]$id = 'me',
    # Rubrik server IP or FQDN
    [String]$Server = $global:RubrikConnection.server,
    # API version
    [String]$api = $global:RubrikConnection.api
  )

  Begin {

    # The Begin section is used to perform one-time loads of data necessary to carry out the function's purpose
    # If a command needs to be run with each iteration or pipeline input, place it in the Process section

    # Check to ensure that a session to the Rubrik cluster exists and load the needed header data for authentication
    Test-RubrikConnection

    # API data references the name of the function
    # For convenience, that name is saved here to $function
    $function = $MyInvocation.MyCommand.Name

    # Retrieve all of the URI, method, body, query, result, filter, and success details for the API endpoint
    Write-Verbose -Message "Gather API Data for $function"
    $resources = Get-RubrikAPIData -endpoint $function
    Write-Verbose -Message "Load API data for $($resources.Function)"
    Write-Verbose -Message "Description: $($resources.Description)"

  }

  Process {

    $uri = New-URIString -server $Server -endpoint ($resources.URI) -id $id
    $uri = Test-QueryParam -querykeys ($resources.Query.Keys) -parameters ((Get-Command $function).Parameters.Values) -uri $uri
    $body = New-BodyString -bodykeys ($resources.Body.Keys) -parameters ((Get-Command $function).Parameters.Values)
    $result = Submit-Request -uri $uri -header $Header -method $($resources.Method) -body $body
    $result = Test-ReturnFormat -api $api -result $result -location $resources.Result
    $result = Test-FilterObject -filter ($resources.Filter) -result $result

    return $result

  } # End of process
} # End of function


text:
<?php

namespace Platformsh\Cli\ApiToken;

use Platformsh\Cli\Service\Config;
use Symfony\Component\Filesystem\Filesystem as SymfonyFilesystem;

/**
 * Stores API tokens using a hidden file.
 */
class FileStorage implements StorageInterface {
    private $config;
    private $fs;

    public function __construct(Config $config, SymfonyFilesystem $fs = null)
    {
        $this->config = $config;
        $this->fs = $fs ?: new SymfonyFilesystem();
    }

    /**
     * Loads the API token.
     *
     * @return string
     */
    public function getToken() {
        return $this->load();
    }

    /**
     * Stores an API token.
     *
     * @param string $value
     */
    public function storeToken($value) {
        $this->save($value);
    }

    /**
     * Deletes the saved token.
     */
    public function deleteToken() {
        $this->save('');
    }

    /**
     * @param string $token
     */
    private function save($token) {
        $filename = $this->getFilename();
        if (empty($token)) {
            if (file_exists($filename)) {
                $this->fs->remove($filename);
            }
            return;
        }

        // Avoid overwriting an already configured token file.
        if (file_exists($filename) && $this->config->has('api.token_file') && $this->resolveTokenFile($this->config->get('api.token_file')) === $filename) {
            throw new \RuntimeException('Failed to save API token: it would conflict with the existing api.token_file configuration.');
        }

        $this->fs->dumpFile($filename, $token);
        $this->fs->chmod($filename, 0600);
    }

    /**
     * @return string
     */
    private function load() {
        $filename = $this->getFilename();
        if (file_exists($filename)) {
            return trim((string) file_get_contents($filename));
        }

        return '';
    }

    /**
     * @return string
     */
    private function getFilename() {
        return $this->config->getSessionDir(true) . DIRECTORY_SEPARATOR . 'api-token';
    }

    /**
     * Makes a relative path absolute, based on the user config dir.
     *
     * @param string $tokenFile
     *
     * @return string
     */
    private function resolveTokenFile($tokenFile) {
        if (strpos($tokenFile, '/') !== 0 && strpos($tokenFile, '\\') !== 0) {
            $tokenFile = $this->config->getUserConfigDir() . '/' . $tokenFile;
        }

        return $tokenFile;
    }
}


text:
module EasyPost
  class PickupRate < Resource

  end
end


text:
namespace Microsoft.Azure.Management.WebSites.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Non versioned Container App configuration properties that define the
    /// mutable settings of a Container app
    /// </summary>
    public partial class Configuration
    {
        /// <summary>
        /// Initializes a new instance of the Configuration class.
        /// </summary>
        public Configuration()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the Configuration class.
        /// </summary>
        /// <param name="secrets">Collection of secrets used by a Container
        /// app</param>
        /// <param name="activeRevisionsMode">ActiveRevisionsMode controls how
        /// active revisions are handled for the Container app:
        /// <list><item>Multiple: multiple revisions can be active.
        /// If no value if provided, this is the
        /// default</item><item>Single: Only one revision can be
        /// active at a time. Revision weights can not be used in this
        /// mode</item></list>. Possible values include:
        /// 'multiple', 'single'</param>
        /// <param name="ingress">Ingress configurations.</param>
        /// <param name="registries">Collection of private container registry
        /// credentials for containers used by the Container app</param>
        public Configuration(IList<Secret> secrets = default(IList<Secret>), string activeRevisionsMode = default(string), Ingress ingress = default(Ingress), IList<RegistryCredentials> registries = default(IList<RegistryCredentials>))
        {
            Secrets = secrets;
            ActiveRevisionsMode = activeRevisionsMode;
            Ingress = ingress;
            Registries = registries;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets collection of secrets used by a Container app
        /// </summary>
        [JsonProperty(PropertyName = "secrets")]
        public IList<Secret> Secrets { get; set; }

        /// <summary>
        /// Gets or sets activeRevisionsMode controls how active revisions are
        /// handled for the Container app:
        /// &lt;list&gt;&lt;item&gt;Multiple: multiple
        /// revisions can be active. If no value if provided, this is the
        /// default&lt;/item&gt;&lt;item&gt;Single: Only one
        /// revision can be active at a time. Revision weights can not be used
        /// in this mode&lt;/item&gt;&lt;/list&gt;. Possible
        /// values include: 'multiple', 'single'
        /// </summary>
        [JsonProperty(PropertyName = "activeRevisionsMode")]
        public string ActiveRevisionsMode { get; set; }

        /// <summary>
        /// Gets or sets ingress configurations.
        /// </summary>
        [JsonProperty(PropertyName = "ingress")]
        public Ingress Ingress { get; set; }

        /// <summary>
        /// Gets or sets collection of private container registry credentials
        /// for containers used by the Container app
        /// </summary>
        [JsonProperty(PropertyName = "registries")]
        public IList<RegistryCredentials> Registries { get; set; }

    }
}


text:
"""
network.py

Created by Thomas Mangin on 2009-09-06.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""

import random
import socket
import select
from struct import unpack

from exabgp.configuration.environment import environment

from exabgp.util.errstr import errstr

from exabgp.logger import Logger
from exabgp.logger import FakeLogger
from exabgp.logger import LazyFormat

from exabgp.bgp.message import Message

from exabgp.reactor.network.error import error
from exabgp.reactor.network.error import errno
from exabgp.reactor.network.error import NetworkError
from exabgp.reactor.network.error import TooSlowError
from exabgp.reactor.network.error import NotConnected
from exabgp.reactor.network.error import LostConnection
from exabgp.reactor.network.error import NotifyError

from .error import *

class Connection (object):
	direction = 'undefined'
	identifier = 0

	def __init__ (self, afi, peer, local):
		# peer and local are strings of the IP

		try:
			self.defensive = environment.settings().debug.defensive
			self.logger = Logger()
		except RuntimeError:
			self.defensive = True
			self.logger = FakeLogger()

		self.afi = afi
		self.peer = peer
		self.local = local

		self._buffer = ''
		self.io = None
		self.established = False

		self.identifier += 1
		self.id = self.identifier

	# Just in case ..
	def __del__ (self):
		if self.io:
			self.logger.network("%s connection to %s closed" % (self.name(),self.peer),'info')
			self.close()

	def name (self):
		return "session %d %s" % (self.id,self.direction)

	def close (self):
		try:
			self.logger.wire("%s, closing connection from %s to %s" % (self.name(),self.local,self.peer))
			if self.io:
				self.io.close()
				self.io = None
		except KeyboardInterrupt,exc:
			raise exc
		except:
			pass

	def reading (self):
		while True:
			try:
				r,_,_ = select.select([self.io,],[],[],0)
			except select.error,exc:
				if exc.args[0] not in error.block:
					self.close()
					self.logger.wire("%s %s errno %s on socket" % (self.name(),self.peer,errno.errorcode[exc.args[0]]))
					raise NetworkError('errno %s on socket' % errno.errorcode[exc.args[0]])
				return False
			return r != []

	def writing (self):
		while True:
			try:
				_,w,_ = select.select([],[self.io,],[],0)
			except select.error,exc:
				if exc.args[0] not in error.block:
					self.close()
					self.logger.wire("%s %s errno %s on socket" % (self.name(),self.peer,errno.errorcode[exc.args[0]]))
					raise NetworkError('errno %s on socket' % errno.errorcode[exc.args[0]])
				return False
			return w != []

	def _reader (self, number):
		# The function must not be called if it does not return with no data with a smaller size as parameter
		if not self.io:
			self.close()
			raise NotConnected('Trying to read on a closed TCP conncetion')
		if number == 0:
			yield ''
			return

		while not self.reading():
			yield ''
		data = ''
		reported = ''
		while True:
			try:
				while True:
					if self.defensive and random.randint(0,2):
						raise socket.error(errno.EAGAIN,'raising network error in purpose')

					read = self.io.recv(number)
					if not read:
						self.close()
						self.logger.wire("%s %s lost TCP session with peer" % (self.name(),self.peer))
						raise LostConnection('the TCP connection was closed by the remote end')
					data += read

					number -= len(read)
					if not number:
						self.logger.wire(
							LazyFormat(
								"%s %-32s RECEIVED " % (
									self.name(),
									'%s / %s' % (self.local,self.peer)
								),
								read
							)
						)
						yield data
						return

					yield ''
			except socket.timeout,exc:
				self.close()
				self.logger.wire("%s %s peer is too slow" % (self.name(),self.peer))
				raise TooSlowError('Timeout while reading data from the network (%s)' % errstr(exc))
			except socket.error,exc:
				if exc.args[0] in error.block:
					message = "%s %s blocking io problem mid-way through reading a message %s, trying to complete" % (self.name(),self.peer,errstr(exc))
					if message != reported:
						reported = message
						self.logger.wire(message,'debug')
					yield ''
				elif exc.args[0] in error.fatal:
					self.close()
					raise LostConnection('issue reading on the socket: %s' % errstr(exc))
				# what error could it be !
				else:
					self.logger.wire("%s %s undefined error reading on socket" % (self.name(),self.peer))
					raise NetworkError('Problem while reading data from the network (%s)' % errstr(exc))

	def writer (self, data):
		if not self.io:
			# XXX: FIXME: Make sure it does not hold the cleanup during the closing of the peering session
			yield True
			return
		while not self.writing():
			yield False
		self.logger.wire(LazyFormat("%s %-32s SENDING " % (self.name(),'%s / %s' % (self.local,self.peer)),data))
		# The first while is here to setup the try/catch block once as it is very expensive
		while True:
			try:
				while True:
					if self.defensive and random.randint(0,2):
						raise socket.error(errno.EAGAIN,'raising network error in purpose')

					# we can not use sendall as in case of network buffer filling
					# it does raise and does not let you know how much was sent
					number = self.io.send(data)
					if not number:
						self.close()
						self.logger.wire("%s %s lost TCP connection with peer" % (self.name(),self.peer))
						raise LostConnection('lost the TCP connection')

					data = data[number:]
					if not data:
						yield True
						return
					yield False
			except socket.error,exc:
				if exc.args[0] in error.block:
					self.logger.wire(
						"%s %s blocking io problem mid-way through writing a message %s, trying to complete" % (
							self.name(),
							self.peer,
							errstr(exc)
						),
						'debug'
					)
					yield False
				elif exc.errno == errno.EPIPE:
					# The TCP connection is gone.
					self.close()
					raise NetworkError('Broken TCP connection')
				elif exc.args[0] in error.fatal:
					self.close()
					self.logger.wire("%s %s problem sending message (%s)" % (self.name(),self.peer,errstr(exc)))
					raise NetworkError('Problem while writing data to the network (%s)' % errstr(exc))
				# what error could it be !
				else:
					self.logger.wire("%s %s undefined error writing on socket" % (self.name(),self.peer))
					yield False

	def reader (self):
		# _reader returns the whole number requested or nothing and then stops
		for header in self._reader(Message.HEADER_LEN):
			if not header:
				yield 0,0,'','',None

		if not header.startswith(Message.MARKER):
			report = 'The packet received does not contain a BGP marker'
			yield 0,0,header,'',NotifyError(1,1,report)
			return

		msg = ord(header[18])
		length = unpack('!H',header[16:18])[0]

		if length < Message.HEADER_LEN or length > Message.MAX_LEN:
			report = '%s has an invalid message length of %d' % (Message.CODE.name(msg),length)
			yield length,0,header,'',NotifyError(1,2,report)
			return

		validator = Message.Length.get(msg,lambda _: _ >= 19)
		if not validator(length):
			# MUST send the faulty length back
			report = '%s has an invalid message length of %d' % (Message.CODE.name(msg),length)
			yield length,0,header,'',NotifyError(1,2,report)
			return

		number = length - Message.HEADER_LEN

		if not number:
			yield length,msg,header,'',None
			return

		for body in self._reader(number):
			if not body:
				yield 0,0,'','',None

		yield length,msg,header,body,None


text:
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET FOREIGN_KEY_CHECKS=0 */;

DROP PROCEDURE IF EXISTS `sp_GetHighestLocationId`;
DELIMITER //
CREATE PROCEDURE `sp_GetHighestLocationId`()
BEGIN
	IF ((SELECT max(id) + 1 FROM planetmap) IS NULL) THEN
		SELECT 999999681;
	ELSE
		SELECT max(id) + 1 FROM planetmap;
	END IF;
END//
DELIMITER ;
/*!40014 SET FOREIGN_KEY_CHECKS=1 */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;


text:
require("mocha");
var should = require("should");
var rest = require("../lib/restless");
var http = require("http");
var makeServer = require("./makeServer");
var behavesLike = {
   aRequest: require("./behaviors/request"),
   aDeserializer: require("./behaviors/deserializer"),
   aCustomMimiHandler: require("./behaviors/customMimiHandler")
}

var xml2js, yaml, zlib, iconv;
loadOptionalLibraries();

describe("Restless", function () {
   beforeEach(makeServer);

   describe("#get()", function () {
      behavesLike.aRequest(rest.get);
      behavesLike.aDeserializer(rest.get, xml2js, yaml, zlib, iconv);
      behavesLike.aCustomMimiHandler(rest, rest.get);

      it("should make a GET request", function (done) {
         var context = this;
         rest.get(this.host, function (error, data, res) {
            context.request.method.should.equal("GET");
            done();
         });
      });
   });

   describe("#post()", function () {
      behavesLike.aRequest(rest.post);
      behavesLike.aDeserializer(rest.post, xml2js, yaml, zlib, iconv);
      behavesLike.aCustomMimiHandler(rest, rest.post);

      it("should make a POST request", function (done) {
         var context = this;
         rest.post(this.host, function (error, data, res) {
            context.request.method.should.equal("POST");
            done();
         });
      });
   });

   describe("#patch()", function () {
      behavesLike.aRequest(rest.patch);
      behavesLike.aDeserializer(rest.patch, xml2js, yaml, zlib, iconv);
      behavesLike.aCustomMimiHandler(rest, rest.patch);

      it("should make a PATCH request", function (done) {
         var context = this;
         rest.patch(this.host, function (error, data, res) {
            context.request.method.should.equal("PATCH");
            done();
         });
      });
   });

   describe("#del()", function () {
      behavesLike.aRequest(rest.del);
      behavesLike.aDeserializer(rest.del, xml2js, yaml, zlib, iconv);
      behavesLike.aCustomMimiHandler(rest, rest.del);

      it("should make a DELETE request", function (done) {
         var context = this;
         rest.del(this.host, function (error, data, res) {
            context.request.method.should.equal("DELETE");
            done();
         });
      });
   });

   describe("#put()", function () {
      behavesLike.aRequest(rest.put);
      behavesLike.aDeserializer(rest.put, xml2js, yaml, zlib, iconv);
      behavesLike.aCustomMimiHandler(rest, rest.put);

      it("should make a PUT request", function (done) {
         var context = this;
         rest.put(this.host, function (error, data, res) {
            context.request.method.should.equal("PUT");
            done();
         });
      });
   });

   describe("#head()", function () {
      behavesLike.aRequest(rest.head);

      it("should make a HEAD request", function (done) {
         var context = this;
         rest.head(this.host, function (error, data, res) {
            context.request.method.should.equal("HEAD");
            done();
         });
      });
   });
});

function loadOptionalLibraries () {
   try {
      xml2js = require("xml2js");
   } catch (err) {
      printWarning("Couldn't load xml2js: " + err.message);
   }
   try {
      yaml = require("yaml");
   } catch (err) {
      printWarning("Couldn't load yaml: " + err.message);
   }
   try {
      zlib = require("zlib");
   } catch (err) {
      printWarning("Couldn't load zlib: " + err.message);
   }
   try {
      iconv = require("iconv").Iconv;
   } catch (err) {
      printWarning("Couldn't load iconv: " + err.message);
   }
}

function printWarning (message) {
   var yellow = "\u001b[33m";
   var reset = "\u001b[0m";
   console.log(yellow + "  Warning: " + message + reset);
};


text:
<?php

/**
 * Composer auto-loader
 */
$loader = require_once DOCROOT.'vendor'.DIRECTORY_SEPARATOR.'autoload.php';

$aliases = array(
		'\Kohana\Core\URL' => 'URL',
		'\Kohana\Core\Core' => 'Kohana'
);

foreach($aliases as $original => $alias)
{
	class_alias($original, $alias);
}

$app = new Kohana();

/**
 * Attach a file reader to config. Multiple readers are supported.
 */
$app->registerService(new \Kohana\Core\Config\ConfigServiceProvider);
$app->registerService(new \Kohana\Core\Log\LogServiceProvider);

// -- Configuration and initialization -----------------------------------------
use Kohana\Core\HTTP;
use Kohana\Core\Core as Kohana;
use Kohana\Core\I18n as I18n;
use Kohana\Core\Cookie as Cookie;
use Kohana\Core\Route as Route;

// -- Environment setup --------------------------------------------------------

/**
 * Set the default time zone.
 *
 * @link http://kohanaframework.org/guide/using.configuration
 * @link http://www.php.net/manual/timezones
 */
date_default_timezone_set('America/Chicago');

/**
 * Set the default locale.
 *
 * @link http://kohanaframework.org/guide/using.configuration
 * @link http://www.php.net/manual/function.setlocale
 */
setlocale(LC_ALL, 'en_US.utf-8');

/**
 * @deprecated
 *
 * We now use the composer autoloader
 * Enable the Kohana auto-loader.
 *
 * @link http://kohanaframework.org/guide/using.autoloading
 * @link http://www.php.net/manual/function.spl-autoload-register
 */

/**
 * Optionally, you can enable a compatibility auto-loader for use with
 * older modules that have not been updated for PSR-0.
 *
 * It is recommended to not enable this unless absolutely necessary.
 */
spl_autoload_register(array('Kohana', 'auto_load_lowercase'));

/**
 * Enable the Kohana auto-loader for unserialization.
 *
 * @link http://www.php.net/manual/function.spl-autoload-call
 * @link http://www.php.net/manual/var.configuration#unserialize-callback-func
 */
ini_set('unserialize_callback_func', 'spl_autoload_call');

/**
 * Set the mb_substitute_character to "none"
 *
 * @link http://www.php.net/manual/function.mb-substitute-character.php
 */
mb_substitute_character('none');

/**
 * Set the default language
 */
I18n::lang('en-us');

/**
 * alias __() in global namespace.  This is needed primarily for Views and other includes.
 */
require APPPATH . 'functions.php';

if (isset($_SERVER['SERVER_PROTOCOL']))
{
	// Replace the default protocol.
	HTTP::$protocol = $_SERVER['SERVER_PROTOCOL'];
}

/**
 * Set Kohana::$environment if a 'KOHANA_ENV' environment variable has been supplied.
 *
 * Note: If you supply an invalid environment name, a PHP warning will be thrown
 * saying "Couldn't find constant Kohana::<INVALID_ENV_NAME>"
 */
if (isset($_SERVER['KOHANA_ENV']))
{
	Kohana::$environment = constant('Kohana::'.strtoupper($_SERVER['KOHANA_ENV']));
}

/**
 * Initialize Kohana, setting the default options.
 *
 * The following options are available:
 *
 * - string   base_url    path, and optionally domain, of your application   NULL
 * - string   index_file  name of your index file, usually "index.php"       index.php
 * - string   charset     internal character set used for input and output   utf-8
 * - string   cache_dir   set the internal cache directory                   APPPATH/cache
 * - integer  cache_life  lifetime, in seconds, of items cached              60
 * - boolean  errors      enable or disable error handling                   TRUE
 * - boolean  profile     enable or disable internal profiling               TRUE
 * - boolean  caching     enable or disable internal caching                 FALSE
 * - boolean  expose      set the X-Powered-By header                        FALSE
 */
$app->init(array(
	'base_url'   => (DIRECTORY_SEPARATOR == '/' ? dirname($_SERVER['SCRIPT_NAME']): str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']))),
	'index_file' => FALSE,
	'profile'    => Kohana::$environment !== Kohana::PRODUCTION,
	'caching'    => TRUE,
));

/**
 * Enable modules. Modules are referenced by a relative or absolute path.
 */
Kohana::modules(array(
	//'kohana' => DOCROOT.'vendor'.DIRECTORY_SEPARATOR.'cohana/core',
	// 'auth'       => MODPATH.'auth',       // Basic authentication
	// 'cache'      => MODPATH.'cache',      // Caching with multiple backends
	// 'codebench'  => MODPATH.'codebench',  // Benchmarking tool
	// 'database'   => MODPATH.'database',   // Database access
	// 'image'      => MODPATH.'image',      // Image manipulation
	// 'minion'     => MODPATH.'minion',     // CLI Tasks
	// 'orm'        => MODPATH.'orm',        // Object Relationship Mapping
	// 'unittest'   => MODPATH.'unittest',   // Unit testing
	// 'userguide'  => MODPATH.'userguide',  // User guide and API documentation
	));

Cookie::$salt = 'foo';

/**
 * Set the routes. Each route must have a minimum of a name, a URI and a set of
 * defaults for the URI.
 */

Route::set('subdirectory_example', 'welcome/<controller>(/<action>(/<id>))')
	->defaults(array(
		'namespace' => '\\App\\Controller\\Welcome\\',
		'controller' => 'Home',
		'action'     => 'index',
	));

Route::set('default', '(<controller>(/<action>(/<id>)))')
	->defaults(array(
		'namespace' => '\\App\\Controller\\',
		'controller' => 'Welcome',
		'action'     => 'index',
	));


text:
package io.fabric8.maven.docker.config;

import org.junit.Test;

/**
 * Tests the health check configuration
 */
public class HealthCheckConfigTest {

    @Test
    public void testGoodHealthCheck1() {
        new HealthCheckConfiguration.Builder()
                .cmd(new Arguments("exit 0"))
                .build()
                .validate();
    }

    @Test
    public void testGoodHealthCheck2() {
        new HealthCheckConfiguration.Builder()
                .cmd(new Arguments("exit 0"))
                .retries(1)
                .build()
                .validate();
    }

    @Test
    public void testGoodHealthCheck3() {
        new HealthCheckConfiguration.Builder()
                .cmd(new Arguments("exit 0"))
                .retries(1)
                .interval("2s")
                .build()
                .validate();
    }

    @Test
    public void testGoodHealthCheck4() {
        new HealthCheckConfiguration.Builder()
                .cmd(new Arguments("exit 0"))
                .retries(1)
                .interval("2s")
                .timeout("3s")
                .build()
                .validate();
    }

    @Test
    public void testGoodHealthCheck5() {
        new HealthCheckConfiguration.Builder()
                .mode(HealthCheckMode.cmd)
                .cmd(new Arguments("exit 0"))
                .retries(1)
                .interval("2s")
                .timeout("3s")
                .startPeriod("30s")
                .build()
                .validate();
    }

    @Test
    public void testGoodHealthCheck6() {
        new HealthCheckConfiguration.Builder()
                .mode(HealthCheckMode.cmd)
                .cmd(new Arguments("exit 0"))
                .retries(1)
                .interval("2s")
                .timeout("3s")
                .startPeriod("4s")
                .build()
                .validate();
    }

    @Test
    public void testGoodHealthCheck7() {
        new HealthCheckConfiguration.Builder()
                .mode(HealthCheckMode.none)
                .build()
                .validate();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testBadHealthCheck1() {
        new HealthCheckConfiguration.Builder()
                .mode(HealthCheckMode.none)
                .interval("2s")
                .build()
                .validate();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testBadHealthCheck2() {
        new HealthCheckConfiguration.Builder()
                .mode(HealthCheckMode.none)
                .retries(1)
                .build()
                .validate();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testBadHealthCheck3() {
        new HealthCheckConfiguration.Builder()
                .mode(HealthCheckMode.none)
                .timeout("3s")
                .build()
                .validate();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testBadHealthCheck4() {
        new HealthCheckConfiguration.Builder()
                .mode(HealthCheckMode.none)
                .startPeriod("30s")
                .cmd(new Arguments("echo a"))
                .build()
                .validate();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testBadHealthCheck5() {
        new HealthCheckConfiguration.Builder()
                .mode(HealthCheckMode.none)
                .cmd(new Arguments("echo a"))
                .build()
                .validate();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testBadHealthCheck6() {
        new HealthCheckConfiguration.Builder()
                .build()
                .validate();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testBadHealthCheck7() {
        new HealthCheckConfiguration.Builder()
                .mode(HealthCheckMode.cmd)
                .build()
                .validate();
    }

}


text:
package bufpluginconfig

import (
	"context"
	"math"
	"os"
	"path/filepath"
	"sort"
	"testing"

	"github.com/bufbuild/buf/private/bufpkg/bufplugin/bufpluginref"
	"github.com/bufbuild/buf/private/pkg/storage/storageos"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gopkg.in/yaml.v3"
)

func TestGetConfigForBucket(t *testing.T) {
	t.Parallel()
	storageosProvider := storageos.NewProvider()
	readWriteBucket, err := storageosProvider.NewReadWriteBucket(filepath.Join("testdata", "success", "go"))
	require.NoError(t, err)
	pluginConfig, err := GetConfigForBucket(context.Background(), readWriteBucket)
	require.NoError(t, err)
	pluginIdentity, err := bufpluginref.PluginIdentityForString("buf.build/library/go-grpc")
	require.NoError(t, err)
	pluginDependency, err := bufpluginref.PluginReferenceForString("buf.build/library/go:v1.28.0", 1)
	require.NoError(t, err)
	require.Equal(
		t,
		&Config{
			Name:          pluginIdentity,
			PluginVersion: "v1.2.0",
			SourceURL:     "https://github.com/grpc/grpc-go",
			Description:   "Generates Go language bindings of services in protobuf definition files for gRPC.",
			Dependencies: []bufpluginref.PluginReference{
				pluginDependency,
			},
			OutputLanguages: []string{"go"},
			Registry: &RegistryConfig{
				Go: &GoRegistryConfig{
					MinVersion: "1.18",
					Deps: []*GoRegistryDependencyConfig{
						{
							Module:  "google.golang.org/grpc",
							Version: "v1.32.0",
						},
					},
				},
				Options: map[string]string{
					"separate_package": "true",
				},
			},
			SPDXLicenseID: "Apache-2.0",
			LicenseURL:    "https://github.com/grpc/grpc-go/blob/master/LICENSE",
		},
		pluginConfig,
	)
}

func TestParsePluginConfigGoYAML(t *testing.T) {
	t.Parallel()
	pluginConfig, err := ParseConfig(filepath.Join("testdata", "success", "go", "buf.plugin.yaml"))
	require.NoError(t, err)
	pluginIdentity, err := bufpluginref.PluginIdentityForString("buf.build/library/go-grpc")
	require.NoError(t, err)
	pluginDependency, err := bufpluginref.PluginReferenceForString("buf.build/library/go:v1.28.0", 1)
	require.NoError(t, err)
	require.Equal(
		t,
		&Config{
			Name:          pluginIdentity,
			PluginVersion: "v1.2.0",
			SourceURL:     "https://github.com/grpc/grpc-go",
			Description:   "Generates Go language bindings of services in protobuf definition files for gRPC.",
			Dependencies: []bufpluginref.PluginReference{
				pluginDependency,
			},
			OutputLanguages: []string{"go"},
			Registry: &RegistryConfig{
				Go: &GoRegistryConfig{
					MinVersion: "1.18",
					Deps: []*GoRegistryDependencyConfig{
						{
							Module:  "google.golang.org/grpc",
							Version: "v1.32.0",
						},
					},
				},
				Options: map[string]string{
					"separate_package": "true",
				},
			},
			SPDXLicenseID: "Apache-2.0",
			LicenseURL:    "https://github.com/grpc/grpc-go/blob/master/LICENSE",
		},
		pluginConfig,
	)
}

func TestParsePluginConfigGoYAMLOverrideRemote(t *testing.T) {
	t.Parallel()
	pluginConfig, err := ParseConfig(filepath.Join("testdata", "success", "go", "buf.plugin.yaml"), WithOverrideRemote("buf.mydomain.com"))
	require.NoError(t, err)
	pluginIdentity, err := bufpluginref.PluginIdentityForString("buf.mydomain.com/library/go-grpc")
	require.NoError(t, err)
	pluginDependency, err := bufpluginref.PluginReferenceForString("buf.mydomain.com/library/go:v1.28.0", 1)
	require.NoError(t, err)
	assert.Equal(t, pluginIdentity, pluginConfig.Name)
	require.Len(t, pluginConfig.Dependencies, 1)
	assert.Equal(t, pluginDependency, pluginConfig.Dependencies[0])
}

func TestParsePluginConfigNPMYAML(t *testing.T) {
	t.Parallel()
	pluginConfig, err := ParseConfig(filepath.Join("testdata", "success", "npm", "buf.plugin.yaml"))
	require.NoError(t, err)
	pluginIdentity, err := bufpluginref.PluginIdentityForString("buf.build/protocolbuffers/js")
	require.NoError(t, err)
	require.Equal(
		t,
		&Config{
			Name:            pluginIdentity,
			PluginVersion:   "v1.0.0",
			OutputLanguages: []string{"typescript"},
			Registry: &RegistryConfig{
				NPM: &NPMRegistryConfig{
					ImportStyle: "commonjs",
					Deps: []*NPMRegistryDependencyConfig{
						{
							Package: "grpc-web",
							Version: "^1.3.1",
						},
						{
							Package: "@types/google-protobuf",
							Version: "^3.15.6",
						},
					},
				},
			},
			SPDXLicenseID: "BSD-3-Clause",
		},
		pluginConfig,
	)
}

func TestParsePluginConfigOptionsYAML(t *testing.T) {
	t.Parallel()
	pluginConfig, err := ParseConfig(filepath.Join("testdata", "success", "options", "buf.plugin.yaml"))
	require.NoError(t, err)
	pluginIdentity, err := bufpluginref.PluginIdentityForString("buf.build/protocolbuffers/java")
	require.NoError(t, err)
	require.Equal(
		t,
		&Config{
			Name:          pluginIdentity,
			PluginVersion: "v2.0.0",
		},
		pluginConfig,
	)
}

func TestParsePluginConfigMultipleRegistryConfigsYAML(t *testing.T) {
	t.Parallel()
	_, err := ParseConfig(filepath.Join("testdata", "failure", "invalid-multiple-registries.yaml"))
	require.Error(t, err)
}

func TestParsePluginConfigEmptyVersionYAML(t *testing.T) {
	t.Parallel()
	_, err := ParseConfig(filepath.Join("testdata", "failure", "invalid-empty-version.yaml"))
	require.Error(t, err)
}

func TestParsePluginConfigGoNoDepsOrMinVersion(t *testing.T) {
	t.Parallel()
	cfg, err := ParseConfig(filepath.Join("testdata", "success", "go-empty-registry", "buf.plugin.yaml"))
	require.NoError(t, err)
	assert.NotNil(t, cfg.Registry)
	assert.NotNil(t, cfg.Registry.Go)
	assert.Equal(t, &GoRegistryConfig{}, cfg.Registry.Go)
}

func TestPluginOptionsRoundTrip(t *testing.T) {
	assertPluginOptionsRoundTrip(t, nil)
	assertPluginOptionsRoundTrip(t, map[string]string{})
	assertPluginOptionsRoundTrip(t, map[string]string{
		"option-1":          "value-1",
		"option-2":          "value-2",
		"option-no-value-3": "",
	})
}

func assertPluginOptionsRoundTrip(t testing.TB, options map[string]string) {
	optionsSlice := PluginOptionsToOptionsSlice(options)
	assert.True(t, sort.SliceIsSorted(optionsSlice, func(i, j int) bool {
		return optionsSlice[i] < optionsSlice[j]
	}))
	assert.Equal(t, options, OptionsSliceToPluginOptions(optionsSlice))
}

func TestGetConfigForDataInvalidDependency(t *testing.T) {
	t.Parallel()
	validConfig, err := os.ReadFile(filepath.Join("testdata", "success", "go", "buf.plugin.yaml"))
	require.NoError(t, err)
	// Valid dependencies
	verifyDependencies(t, validConfig, false, ExternalDependency{Plugin: "buf.build/library/go:v1.27.1"})
	verifyDependencies(t, validConfig, false, ExternalDependency{Plugin: "buf.build/library/go:v1.27.1-rc.1"})
	// Invalid dependencies
	verifyDependencies(t, validConfig, true, ExternalDependency{Plugin: "library/go:v1.28.0"})
	verifyDependencies(t, validConfig, true, ExternalDependency{Plugin: "buf.build/library/go"})
	verifyDependencies(t, validConfig, true, ExternalDependency{Plugin: "other.buf.build/library/go:v1.28.0"})
	verifyDependencies(t, validConfig, true, ExternalDependency{Plugin: "buf.build/library/go:1.28.0"})
	verifyDependencies(t, validConfig, true, ExternalDependency{Plugin: "buf.build/library/go:v1.28.0", Revision: -1})
	verifyDependencies(t, validConfig, true, ExternalDependency{Plugin: "buf.build/library/go:v1.28.0", Revision: math.MaxInt32 + 1})
	// duplicate dependencies (doesn't matter if version differs)
	verifyDependencies(t, validConfig, true, ExternalDependency{Plugin: "buf.build/library/go:v1.28.0"}, ExternalDependency{Plugin: "buf.build/library/go:v1.27.0", Revision: 1})
}

func verifyDependencies(t testing.TB, validConfigBytes []byte, fail bool, invalidDependencies ...ExternalDependency) {
	t.Helper()
	// make a defensive copy of a valid parsed config
	var cloned *ExternalConfig
	err := yaml.Unmarshal(validConfigBytes, &cloned)
	require.NoError(t, err)
	cloned.Deps = append([]ExternalDependency{}, invalidDependencies...)
	yamlBytes, err := yaml.Marshal(cloned)
	require.NoError(t, err)
	_, err = GetConfigForData(context.Background(), yamlBytes)
	if fail {
		assert.Error(t, err)
	} else {
		assert.NoError(t, err)
	}
}


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

namespace Konspiration
{
    class Program
    {
        static void Main(string[] args)
        {

         // golqmo mazalo beshe....
        }
    }
}


text:
<?php

namespace App\Http\Requests\Article;

use Auth;
use Illuminate\Foundation\Http\FormRequest;
use Input;

class ArticleCreateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::user()->hasRole('editor');
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|unique:articles,title',
            'slug' => 'required|unique:articles,slug',
            'category' => 'required',
            'author_id' => 'required',
            'content' => 'required',
        ];
    }

    public function getValidRequest()
    {
        return [
            'author_id' => $this->input('author_id'),
            'category_id' => $this->input('category'),
            'slug' => $this->input('slug'),
            'title' => $this->input('title'),
            'subtitle' => $this->input('subtitle'),
            'content' => $this->input('content'),
            'article_image' => $this->input('article_image'),
            'meta_keywords' => $this->input('meta_keywords'),
            'meta_description' => $this->input('meta_description'),
            'is_published' => $this->input('is_published') ?? false,
            'published_at' => $this->input('published_at'),
        ];
    }

}


text:
//
//  TKCalendarMonthView.h
//  Created by Devin Ross on 6/10/10.
//

#import <UIKit/UIKit.h>

@class TKCalendarMonthTiles;
@protocol TKCalendarMonthViewDelegate, TKCalendarMonthViewDataSource;

@interface TKCalendarMonthView : UIView {

	TKCalendarMonthTiles *currentTile,*oldTile;
	UIButton *leftArrow, *rightArrow;
	UIImageView *topBackground, *shadow;
	UILabel *monthYear;
	UIScrollView *tileBox;
	BOOL sunday;

	id <TKCalendarMonthViewDelegate> delegate;
	id <TKCalendarMonthViewDataSource> dataSource;

}

@property (nonatomic,assign) id <TKCalendarMonthViewDelegate> delegate;
@property (nonatomic,assign) id <TKCalendarMonthViewDataSource> dataSource;

- (id) initWithSundayAsFirst:(BOOL)sunday; // it sunday regardless right now...

- (NSDate*) dateSelected;
- (NSDate*) monthDate;
- (void) selectDate:(NSDate*)date;
- (void) reloadCal;

@end

@protocol TKCalendarMonthViewDelegate <NSObject>

@optional
- (void) calendarMonthView:(TKCalendarMonthView*)monthView didSelectDate:(NSDate*)d;
- (void) calendarMonthView:(TKCalendarMonthView*)monthView monthDidChange:(NSDate*)d;

@end

@protocol TKCalendarMonthViewDataSource <NSObject>

- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate;

@end


text:
import PropTypes from 'prop-types';
import React from 'react';

import { ViewPropTypes, View } from 'react-native';

import decorateMapComponent, {
  USES_DEFAULT_IMPLEMENTATION,
  SUPPORTED,
} from './decorateMapComponent';

// if ViewPropTypes is not defined fall back to View.propType (to support RN < 0.44)
const viewPropTypes = ViewPropTypes || View.propTypes;

const propTypes = {
  ...viewPropTypes,

  /**
   * The path template of the local tile source.
   * The patterns {x} {y} {z} will be replaced at runtime,
   * for example, /storage/emulated/0/tiles/{z}/{x}/{y}.png.
   */
  pathTemplate: PropTypes.string.isRequired,

  /**
   * The order in which this tile overlay is drawn with respect to other overlays. An overlay
   * with a larger z-index is drawn over overlays with smaller z-indices. The order of overlays
   * with the same z-index is arbitrary. The default zIndex is -1.
   *
   * @platform android
   */
  zIndex: PropTypes.number,

  /**
   * Size of tile images.
   */
  tileSize: PropTypes.number,
};

class MapLocalTile extends React.Component {
  render() {
    const AIRMapLocalTile = this.getAirComponent();
    return <AIRMapLocalTile {...this.props} />;
  }
}

MapLocalTile.propTypes = propTypes;

export default decorateMapComponent(MapLocalTile, {
  componentType: 'LocalTile',
  providers: {
    google: {
      ios: SUPPORTED,
      android: USES_DEFAULT_IMPLEMENTATION,
    },
  },
});


text:
package com.polidea.rxandroidble2.internal.connection;

import android.bluetooth.BluetoothGattCharacteristic;

import com.polidea.rxandroidble2.internal.BleIllegalOperationException;
import com.polidea.rxandroidble2.internal.RxBleLog;

import bleshadow.javax.inject.Inject;

/**
 * Implementation of {@link IllegalOperationHandler}. This class logs a warning if there was no match between possessed
 * and requested properties.
 */
public class LoggingIllegalOperationHandler extends IllegalOperationHandler {

    @Inject
    public LoggingIllegalOperationHandler(IllegalOperationMessageCreator messageCreator) {
        super(messageCreator);
    }

    /**
     * This method logs a warning.
     * @param characteristic the characteristic upon which the operation was requested
     * @param neededProperties bitmask of properties needed by the operation
     */
    @Override
    public BleIllegalOperationException handleMismatchData(BluetoothGattCharacteristic characteristic, int neededProperties) {
        RxBleLog.w(messageCreator.createMismatchMessage(characteristic, neededProperties));
        return null;
    }
}


text:
<container>
  <callout>
    <row>
      <columns>

Sportwear

      </columns>
    </row>

    <row>
      <columns small="12" large="6">

Men's black
fleece

£9.85 (was £14.95)

          <button class="radius small" href="https://www.cancerresearchuk.org/">Buy now</button>

      </columns>
      <columns small="12" large="6">

Women's black sports t-shirt

£7.50 (was £9.99)

          <button class="radius small" href="https://www.cancerresearchuk.org/">Buy now</button>

      </columns>
    </row>

    <row>
      <columns small="3"></columns>
      <columns small="6">
        <button class="radius expanded" href="https://www.cancerresearchuk.org/">See all products</button>
      </columns>
      <columns small="3"></columns>
    </row>
  </callout>
</container>


text:
package org.apache.camel.management;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.apache.camel.Exchange;
import org.apache.camel.ServiceStatus;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

import static org.awaitility.Awaitility.await;

/**
 * Extended test to see if mbeans is removed and stats are correct
 */
public class ManagedRouteStopAndStartCleanupTest extends ManagedRouteStopAndStartTest {

    @Test
    public void testStopAndStartRoute() throws Exception {
        // JMX tests dont work well on AIX CI servers (hangs them)
        if (isPlatform("aix")) {
            return;
        }

        MBeanServer mbeanServer = getMBeanServer();
        ObjectName on = getRouteObjectName(mbeanServer);

        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedBodiesReceived("Hello World");

        template.sendBodyAndHeader("file://target/data/managed", "Hello World", Exchange.FILE_NAME, "hello.txt");

        assertMockEndpointsSatisfied();

        // should be started
        String state = (String) mbeanServer.getAttribute(on, "State");
        assertEquals("Should be started", ServiceStatus.Started.name(), state);

        // need a bit time to let JMX update
        await().atMost(1, TimeUnit.SECONDS).untilAsserted(() -> {
            // should have 1 completed exchange
            Long completed = (Long) mbeanServer.getAttribute(on, "ExchangesCompleted");
            assertEquals(1, completed.longValue());
        });

        // should be 1 consumer and 2 processors
        Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=consumers,*"), null);
        assertEquals("Should be 1 consumer", 1, set.size());

        set = mbeanServer.queryNames(new ObjectName("*:type=processors,*"), null);
        assertEquals("Should be 2 processors", 2, set.size());

        // stop
        log.info(">>>>>>>>>>>>>>>>>> invoking stop <<<<<<<<<<<<<<<<<<<<<");
        mbeanServer.invoke(on, "stop", null, null);
        log.info(">>>>>>>>>>>>>>>>>> invoking stop DONE <<<<<<<<<<<<<<<<<<<<<");

        state = (String) mbeanServer.getAttribute(on, "State");
        assertEquals("Should be stopped", ServiceStatus.Stopped.name(), state);

        // should be 0 consumer and 0 processor
        set = mbeanServer.queryNames(new ObjectName("*:type=consumers,*"), null);
        assertEquals("Should be 0 consumer", 0, set.size());

        set = mbeanServer.queryNames(new ObjectName("*:type=processors,*"), null);
        assertEquals("Should be 0 processor", 0, set.size());

        mock.reset();
        mock.expectedBodiesReceived("Bye World");
        // wait 2 seconds while route is stopped to verify that file was not consumed
        mock.setResultWaitTime(2000);

        template.sendBodyAndHeader("file://target/data/managed", "Bye World", Exchange.FILE_NAME, "bye.txt");

        // route is stopped so we do not get the file
        mock.assertIsNotSatisfied();

        // prepare mock for starting route
        mock.reset();
        mock.expectedBodiesReceived("Bye World");

        // start
        log.info(">>>>>>>>>>>>>>>>> invoking start <<<<<<<<<<<<<<<<<<");
        mbeanServer.invoke(on, "start", null, null);
        log.info(">>>>>>>>>>>>>>>>> invoking start DONE <<<<<<<<<<<<<<<<<<");

        state = (String) mbeanServer.getAttribute(on, "State");
        assertEquals("Should be started", ServiceStatus.Started.name(), state);

        // should be 1 consumer and 1 processor
        set = mbeanServer.queryNames(new ObjectName("*:type=consumers,*"), null);
        assertEquals("Should be 1 consumer", 1, set.size());

        set = mbeanServer.queryNames(new ObjectName("*:type=processors,*"), null);
        assertEquals("Should be 2 processors", 2, set.size());

        // this time the file is consumed
        mock.assertIsSatisfied();

        // need a bit time to let JMX update
        await().atMost(1, TimeUnit.SECONDS).until(() -> {
            Long num = (Long) mbeanServer.getAttribute(on, "ExchangesCompleted");
            return num == 2;
        });

        // should have 2 completed exchange
        Long completed = (Long) mbeanServer.getAttribute(on, "ExchangesCompleted");
        assertEquals(2, completed.longValue());
    }

}