text:
package org.efaps.db;

import java.util.concurrent.TimeUnit;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 * @version $Id$
 */
public interface ICacheDefinition
{
    /**
     *
     * @return lifespan of the entry. Negative values are interpreted as
     *         unlimited lifespan. 0 means do not apply
     */
    long getLifespan();

    /**
     * @return time unit for lifespan
     */
    TimeUnit getLifespanUnit();

    /**
     * @return the maximum amount of time this key is allowed to be idle for
     *         before it is considered as expired. 0 means do not apply
     */
    long getMaxIdleTime();

    /**
     * @return time unit for max idle time
     */
    TimeUnit getMaxIdleTimeUnit();
}


text:
package com.orhanobut.wasp.utils;

import java.util.Map;

public interface RequestInterceptor {

  /**
   * For each request, these headers will be added
   *
   * @param headers to be added request headers
   */
  void onHeadersAdded(Map<String, String> headers);

  /**
   * For each request, these query params will be added
   *
   * @param params query parameters to be added request url
   */
  void onQueryParamsAdded(Map<String, Object> params);

  /**
   * For each request, these retry policy will be set
   *
   * @return defaultRetryPolicy
   */
  WaspRetryPolicy getRetryPolicy();

  /**
   * @return AuthToken object. This will be used to determine if the authtoken
   * should be used in every calls or just filtered ones
   */
  AuthToken getAuthToken();

}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * The model provides some widget functionality to the blog
 * @todo: Move the logic from here into a Factory loaded models
 *
 * @package     Nails
 * @subpackage  module-blog
 * @category    Model
 * @author      Nails Dev Team
 * @link
 */

use Nails\Factory;

class NAILS_Blog_widget_model extends NAILS_Model
{
    /**
     * Returns an array of the latest blog posts
     * @param  integer $blogId The ID of the blog to get posts from
     * @param  integer $limit  The maximum number of posts to return
     * @return array
     */
    public function latestPosts($blogId, $limit = 5)
    {
        $oDb = Factory::service('Database');
        $oDb->select('id,blog_id,slug,title,published');
        $oDb->where('is_published', true);
        $oDb->where('published <=', 'NOW()', false);
        $oDb->where('is_deleted', false);
        $oDb->where('blog_id', $blogId);
        $oDb->limit($limit);
        $oDb->order_by('published', 'DESC');
        $posts = $oDb->get(NAILS_DB_PREFIX . 'blog_post')->result();

        if (!$this->load->isModelLoaded('blog_post_model')) {

            $this->load->model('blog/blog_post_model');
        }

        foreach ($posts as $post) {

            $post->url = $this->blog_post_model->formatUrl($post->slug, $post->blog_id);
        }

        return $posts;
    }

    // --------------------------------------------------------------------------

    /**
     * Returns an array of the most popular blog posts
     * @param  integer $blogId The ID of the blog to get posts from
     * @param  integer $limit  The maximum number of posts to return
     * @return array
     */
    public function popularPosts($blogId, $limit = 5)
    {
        $oDb = Factory::service('Database');
        $oDb->select('bp.id,bp.blog_id,bp.slug,bp.title,bp.published,COUNT(bph.id) hits');
        $oDb->join(NAILS_DB_PREFIX . 'blog_post bp', 'bp.id = bph.post_id');
        $oDb->where('bp.is_published', true);
        $oDb->where('bp.published <=', 'NOW()', false);
        $oDb->where('bp.is_deleted', false);
        $oDb->where('blog_id', $blogId);
        $oDb->group_by('bp.id');
        $oDb->order_by('hits', 'DESC');
        $oDb->order_by('bp.published', 'DESC');
        $oDb->limit($limit);

        $posts = $oDb->get(NAILS_DB_PREFIX . 'blog_post_hit bph')->result();

        if (!$this->load->isModelLoaded('blog_post_model')) {

            $this->load->model('blog/blog_post_model');
        }

        foreach ($posts as $post) {

            $post->url = $this->blog_post_model->formatUrl($post->slug, $post->blog_id);
        }

        return $posts;
    }

    // --------------------------------------------------------------------------

    /**
     * Returns an array of a blog's categories
     * @param  integer $blogId        The ID of the blog to get categories from
     * @param  boolean $includeCount  Whether to include the post count of each category
     * @param  boolean $onlyPopulated Whether to remove categories which don't have any posts in them
     * @return array
     */
    public function categories($blogId, $includeCount = true, $onlyPopulated = true)
    {
        $oDb = Factory::service('Database');
        $oDb->select('c.id,c.blog_id,c.slug,c.label');

        if ($includeCount) {

            $sql  = '(SELECT COUNT(DISTINCT bpc.post_id) FROM ' . NAILS_DB_PREFIX . 'blog_post_category bpc JOIN ';
            $sql .= NAILS_DB_PREFIX . 'blog_post bp ON bpc.post_id = bp.id WHERE bpc.category_id = c.id AND ';
            $sql .= 'bp.is_published = 1 AND bp.is_deleted = 0 AND bp.published <= NOW()) post_count';

            $oDb->select($sql);
        }

        if ($onlyPopulated) {

            $oDb->having('post_count > ', 0);
        }

        $oDb->where('c.blog_id', $blogId);
        $oDb->order_by('c.label');

        $categories = $oDb->get(NAILS_DB_PREFIX . 'blog_category c')->result();

        $this->load->model('blog/blog_category_model');

        foreach ($categories as $category) {

            $category->url = $this->blog_category_model->formatUrl($category->slug, $category->blog_id);
        }

        return $categories;
    }

    // --------------------------------------------------------------------------

    /**
     * Returns an array of a blog's tags
     * @param  integer $blogId        The ID of the blog to get tags from
     * @param  boolean $includeCount  Whether to include the post count of each tag
     * @param  boolean $onlyPopulated Whether to remove tags which don't have any posts in them
     * @return array
     */
    public function tags($blogId, $includeCount = true, $onlyPopulated = true)
    {
        $oDb = Factory::service('Database');
        $oDb->select('t.id,t.blog_id,t.slug,t.label');

        if ($includeCount) {

            $sql  = '(SELECT COUNT(DISTINCT bpt.post_id) FROM ' . NAILS_DB_PREFIX . 'blog_post_tag bpt JOIN ';
            $sql .= NAILS_DB_PREFIX . 'blog_post bp ON bpt.post_id = bp.id WHERE bpt.tag_id = t.id AND ';
            $sql .= 'bp.is_published = 1 AND bp.is_deleted = 0 AND bp.published <= NOW()) post_count';

            $oDb->select($sql);
        }

        if ($onlyPopulated) {

            $oDb->having('post_count > ', 0);
        }

        $oDb->where('t.blog_id', $blogId);
        $oDb->order_by('t.label');

        $tags = $oDb->get(NAILS_DB_PREFIX . 'blog_tag t')->result();

        $this->load->model('blog/blog_tag_model');

        foreach ($tags as $tag) {

            $tag->url = $this->blog_tag_model->formatUrl($tag->slug, $tag->blog_id);
        }

        return $tags;
    }
}

// --------------------------------------------------------------------------

/**
 * OVERLOADING NAILS' MODELS
 *
 * The following block of code makes it simple to extend one of the core Nails
 * models. Some might argue it's a little hacky but it's a simple 'fix'
 * which negates the need to massively extend the CodeIgniter Loader class
 * even further (in all honesty I just can't face understanding the whole
 * Loader class well enough to change it 'properly').
 *
 * Here's how it works:
 *
 * CodeIgniter instantiate a class with the same name as the file, therefore
 * when we try to extend the parent class we get 'cannot redeclare class X' errors
 * and if we call our overloading class something else it will never get instantiated.
 *
 * We solve this by prefixing the main class with NAILS_ and then conditionally
 * declaring this helper class below; the helper gets instantiated et voila.
 *
 * If/when we want to extend the main class we simply define NAILS_ALLOW_EXTENSION
 * before including this PHP file and extend as normal (i.e in the same way as below);
 * the helper won't be declared so we can declare our own one, app specific.
 *
 **/

if (!defined('NAILS_ALLOW_EXTENSION_BLOG_WIDGET_MODEL')) {

    class Blog_widget_model extends NAILS_Blog_widget_model
    {
    }
}


text:
# frozen_string_literal: true

describe 'GH-1248', site: true, stdio: true do
  before do
    File.write('content/stuff.html', 'hi')

    File.write('Rules', <<~EOS)
      preprocess do
        @config[:output_dir] = 'ootpoot'
      end

      passthrough '/**/*'
    EOS
  end

  before do
    Nanoc::CLI.run(%w[compile])
  end

  example do
    expect { Nanoc::CLI.run(%w[compile --verbose]) }
      .not_to output(/identical .* ootpoot\/stuff.html/).to_stdout
  end
end


text:
import sys
import json

from googleapiclient import sample_tools
from googleapiclient.http import build_http

def main(argv):
    # Use the discovery doc to build a service that we can use to make
    # MyBusiness API calls, and authenticate the user so we can access their
    # account
    MyBusinessAccount, flags = sample_tools.init(argv, "mybusinessaccountmanagement", "v1", __doc__, __file__, scope="https://www.googleapis.com/auth/business.manage")

    # Get the list of accounts the authenticated user has access to
    output = MyBusinessAccount.accounts().list().execute()
    print("List of Accounts:\n")
    print(json.dumps(output, indent=2) + "\n")

if __name__ == "__main__":
  main(sys.argv)


text:
<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class SettingRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email'	=> 'required|email|min:7',
            'facebook' => 'sometimes|min:21|max:200',
            'twitter' => 'sometimes|min:18|max:200',
            'logo' => 'sometimes|max:2048|image'
        ];
    }

}


text:
<?php
/**
 * Upgrader API: Plugin_Installer_Skin class
 *
 * @package WordPress
 * @subpackage Upgrader
 * @since 4.6.0
 */

/**
 * Plugin Installer Skin for WordPress Plugin Installer.
 *
 * @since 2.8.0
 * @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php.
 *
 * @see WP_Upgrader_Skin
 */
class Plugin_Installer_Skin extends WP_Upgrader_Skin {
	public $api;
	public $type;

	/**
	 *
	 * @param array $args
	 */
	public function __construct($args = array()) {
		$defaults = array( 'type' => 'web', 'url' => '', 'plugin' => '', 'nonce' => '', 'title' => '' );
		$args = wp_parse_args($args, $defaults);

		$this->type = $args['type'];
		$this->api = isset($args['api']) ? $args['api'] : array();

		parent::__construct($args);
	}

	/**
	 */
	public function before() {
		if ( !empty($this->api) )
			$this->upgrader->strings['process_success'] = sprintf( __('Successfully installed the plugin %s %s.'), $this->api->name, $this->api->version);
	}

	/**
	 */
	public function after() {
		$plugin_file = $this->upgrader->plugin_info();

		$install_actions = array();

		$from = isset($_GET['from']) ? wp_unslash( $_GET['from'] ) : 'plugins';

		if ( 'import' == $from )
			$install_actions['activate_plugin'] = '' . __( 'Activate Plugin & Run Importer' ) . '';
		else
			$install_actions['activate_plugin'] = '' . __( 'Activate Plugin' ) . '';

		if ( is_multisite() && current_user_can( 'manage_network_plugins' ) ) {
			$install_actions['network_activate'] = '' . __( 'Network Activate' ) . '';
			unset( $install_actions['activate_plugin'] );
		}

		if ( 'import' == $from ) {
			$install_actions['importers_page'] = '' . __( 'Return to Importers' ) . '';
		} elseif ( $this->type == 'web' ) {
			$install_actions['plugins_page'] = '' . __( 'Return to Plugin Installer' ) . '';
		} elseif ( 'upload' == $this->type && 'plugins' == $from ) {
			$install_actions['plugins_page'] = '' . __( 'Return to Plugin Installer' ) . '';
		} else {
			$install_actions['plugins_page'] = '' . __( 'Return to Plugins page' ) . '';
		}

		if ( ! $this->result || is_wp_error($this->result) ) {
			unset( $install_actions['activate_plugin'], $install_actions['network_activate'] );
		} elseif ( ! current_user_can( 'activate_plugin', $plugin_file ) ) {
			unset( $install_actions['activate_plugin'] );
		}

		/**
		 * Filters the list of action links available following a single plugin installation.
		 *
		 * @since 2.7.0
		 *
		 * @param array  $install_actions Array of plugin action links.
		 * @param object $api             Object containing WordPress.org API plugin data. Empty
		 *                                for non-API installs, such as when a plugin is installed
		 *                                via upload.
		 * @param string $plugin_file     Path to the plugin file.
		 */
		$install_actions = apply_filters( 'install_plugin_complete_actions', $install_actions, $this->api, $plugin_file );

		if ( ! empty( $install_actions ) ) {
			$this->feedback( implode( ' ', (array) $install_actions ) );
		}
	}
}


text:
namespace base {
namespace test {
class ScopedTaskEnvironment;
}
}  // namespace base

class PersistentPrefStore;

// Calls CommitPendingWrite() on |store| with a callback. Verifies that the
// callback runs on the appropriate sequence. |scoped_task_environment| is the
// test's ScopedTaskEnvironment. This function is meant to be reused in the
// tests of various PersistentPrefStore implementations.
void TestCommitPendingWriteWithCallback(
    PersistentPrefStore* store,
    base::test::ScopedTaskEnvironment* scoped_task_environment);

#endif  // COMPONENTS_PREFS_PERSISTENT_PREF_STORE_UNITTEST_H_


text:
namespace Free.FileFormats.VRML.Interfaces
{
	/// <summary>
	/// This is the base node type for all Material nodes.
	/// </summary>
	public interface X3DMaterialNode : X3DAppearanceChildNode
	{
	}
}


text:
package com.amazonaws.services.pinpoint.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.pinpoint.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * CampaignHookMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CampaignHookMarshaller {

    private static final MarshallingInfo<String> LAMBDAFUNCTIONNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LambdaFunctionName").build();
    private static final MarshallingInfo<String> MODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Mode").build();
    private static final MarshallingInfo<String> WEBURL_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("WebUrl").build();

    private static final CampaignHookMarshaller instance = new CampaignHookMarshaller();

    public static CampaignHookMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(CampaignHook campaignHook, ProtocolMarshaller protocolMarshaller) {

        if (campaignHook == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(campaignHook.getLambdaFunctionName(), LAMBDAFUNCTIONNAME_BINDING);
            protocolMarshaller.marshall(campaignHook.getMode(), MODE_BINDING);
            protocolMarshaller.marshall(campaignHook.getWebUrl(), WEBURL_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
module StopTimeExceptionsHelper
end


text:
Makes it easy to show life-ending, world-collapsing, let's-give-up-and-go-home error messages to your users.

### How do I even?

Wrap your app in <cd-error-message> elements.

```html
<body>
  <cd-error-message>
    <ng-view></ng-view>
  </cd-error-message>
</body>
```

Then, whenever you encounter an error, set $rootScope.cdErrorMessage to the desired error message.

```coffee
$http.get("/important/data.json").catch (error)->
   $rootScope.cdErrorMessage = "Oh, the humanity!"
   console.log error
```

Or, if you don't want to $rootScope, you can use the cdErrorMessage() service to make that easier and more explicit.

```coffee
$http.get("/important/data.json").catch (error)->
   cdErrorMessage "Oh, the humanity!"
   console.log error
```

We'll hide your app and show the error. You can style the message with the `cdErrorMessage` class, too.

## License
Copyright (c) 2014 CD Industrial Group Inc., released under MIT license.


text:
#import "NSObject.h"

@interface UIAccelerometer : NSObject
{
    double _updateInterval;
    id <UIAccelerometerDelegate> _delegate;
    struct {
        unsigned int delegateDidAccelerate:1;
        unsigned int reserved:31;
    } _accelerometerFlags;
}

+ (id)sharedAccelerometer;
@property(nonatomic) id <UIAccelerometerDelegate> delegate; // @synthesize delegate=_delegate;
@property(nonatomic) double updateInterval; // @synthesize updateInterval=_updateInterval;
- (void)_acceleratedInX:(double)arg1 y:(double)arg2 z:(double)arg3 timestamp:(double)arg4;
- (id)init;

@end


text:
var React = require('react');
var PropTypes = React.PropTypes;

import { BarChart,Treemap } from 'rd3';

var ChartTest = React.createClass({
  propTypes: {
    title: PropTypes.string,
  },
  getDefaultProps: function() {
    return {
      title:'Title'
    };
  },
  render: function() {

    return (

          test
          {/* only render if data is passed  */}
          { this.props.TreemapChartData_D3 &&
            <Treemap
              data={this.props.TreemapChartData_D3 ? this.props.TreemapChartData_D3 : [{"label": null,"value": null}]}
              width={1000}
              height={200}
              fill={'#3182bd'}
              title="Treemap"
              textColor="#484848"
              fontColor="12px"
              hoverAnimation={true}
            />
        }
        {/* only render if data is passed  */}
        { this.props.BarChartData_D3 &&

            <BarChart
            data={this.props.BarChartData_D3 ?  this.props.BarChartData_D3 : [{"name": null,"values": [{"x":null,"y":null}]}]}
            width={1000}
            height={300}
            title="Bar Chart"
            xAxisLabel="Value"
            yAxisLabel="Label"
            />
        }

    );
  }
});

module.exports = ChartTest;


text:
package com.deepoove.swagger.diff.output;

import com.alibaba.fastjson.JSON;
import com.deepoove.swagger.diff.SwaggerDiff;

public class JsonRender implements Render {

    @Override
    public String render(SwaggerDiff diff) {
        return JSON.toJSONString(diff);
    }
}


text: Test401::Application.config.session_store :cookie_store, key: '_Test_4_0_1_session'


text:
If a user wishes to change their email or username they can do so as long as they know their current password. To change a user's Email:

```objc
CMUser *user = [[CMUser alloc] initWithEmail:@"test@example.com" andPassword:@"my-password"];

[self.user changeEmailTo:@"newTest@example.com" password:@"my-password" callback:^(CMUserAccountResult resultCode, NSArray *messages) {
  switch (resultCode) {
    case CMUserAccountEmailChangeSucceeded:
      // Success! You should resave the local user now.
      break;
    case CMUserAccountCredentialChangeFailedDuplicateEmail:
      // This email is already in use
      break;
    case CMUserAccountUnknownResult:
      // An error occurred
      break;
    default:
      break;
  }
}];
```

Changing the username is similar.

```objc
CMUser *user = [[CMUser alloc] initWithUsername:@"My Username" andPassword:@"my-password"];

[self.user changeUsernameTo:@"A Better Username" password:@"my-password" callback:^(CMUserAccountResult resultCode, NSArray *messages) {
  switch (resultCode) {
    case CMUserAccountUsernameChangeSucceeded:
      // Success! You should resave the local user now.
      break;
    case CMUserAccountCredentialChangeFailedDuplicateUsername:
      // This userbane is already in use
      break;
    case CMUserAccountUnknownResult:
      // An error occurred
      break;
    default:
      break;
  }
}];
```

If you want to change more than one at once there is another method.

```objc
[self.user changeUserCredentialsWithPassword:@"my-password"
                                 newPassword:@"my-new-password"
                                 newUsername:@"The Best Username"
                                   newEmail:@"testing123@example.com"
                                    callback:^(CMUserAccountResult resultCode, NSArray *messages) {
                                      switch (resultCode) {
                                          case CMUserAccountCredentialChangeSucceeded:
                                              // Success! You should resave your user locally now.
                                              break;
                                          case CMUserAccountCredentialChangeFailedDuplicateInfo:
                                              // The email or username is already in use
                                              break;
                                          case CMUserAccountCredentialChangeFailedInvalidCredentials:
                                              // The user's Password was incorrect
                                              break;n
                                          case CMUserAccountUnknownResult:
                                              // An error occurred
                                              break;
                                          default:
                                              break;
                                      }
                                  }];
```

When changing more than one property of the user you may pass nil as any parameter except password.


text:
package vmsstartupscriptsexample

import (
	"testing"

	"github.com/GoogleCloudPlatform/cloud-foundation-toolkit/infra/blueprint-test/pkg/tft"
	"github.com/terraform-google-modules/anthos-vm/test/integration/remote"
)

func TestVMStartupScriptsExample(t *testing.T) {
	example := tft.NewTFBlueprintTest(t)
	abmTest := remote.NewABMTest(t, example)
	example.DefineInit(abmTest.Init)
	example.DefineApply(abmTest.Apply)
	example.DefineVerify(abmTest.Verify)
	example.DefineTeardown(abmTest.Teardown)
	example.Test()
}


text:
using namespace UnitTesting;

CreateUnitTest( TestTCPRequest, "Platform/Net/TCPRequest")
{
   NetSocket mSocket;
   S32 mDataRecved;

   void handleNotify(NetSocket sock, U32 state)
   {
      // Only consider our own socket.
      if(mSocket != sock)
         return;

      // Ok - what's the state? We do some dumb responses to given states
      // in order to fulfill the request.
      if(state == Net::Connected)
      {
         U8 reqBuffer[] = {
            "GET / HTTP/1.0\nUser-Agent: Torque/1.0\n\n"
         };

         Net::Error e = Net::sendtoSocket(mSocket, reqBuffer, sizeof(reqBuffer));

         test(e == Net::NoError, "Got an error sending our HTTP request!");
      }
      else if(state == Net::Disconnected)
      {
         Process::requestShutdown();
         mSocket = NULL;
      }
   }

   void handleReceive(NetSocket sock, RawData incomingData)
   {
      // Only consider our own socket.
      if(mSocket != sock)
         return;

      char buff[4096];
      dMemcpy(buff, incomingData.data, incomingData.size);
      buff[incomingData.size] = 0;

      UnitPrint("Got a message...\n");
      UnitPrint(buff);
      UnitPrint("------\n");

      mDataRecved += incomingData.size;
   }

   void run()
   {
      mSocket = InvalidSocket;
      mDataRecved = 0;

      // Initialize networking - done by initLibraries currently
      //test(Net::init(), "Failed to initialize networking!");

      // Hook into the signals.
      Net::smConnectionNotify. notify(this, &TestTCPRequest::handleNotify);
      Net::smConnectionReceive.notify(this, &TestTCPRequest::handleReceive);

      // Open a TCP connection to garagegames.com
      mSocket = Net::openConnectTo("ip:72.246.107.193:80");

      while(Process::processEvents())
         ;

      // Unhook from the signals.
      Net::smConnectionNotify. remove(this, &TestTCPRequest::handleNotify);
      Net::smConnectionReceive.remove(this, &TestTCPRequest::handleReceive);

      test(mDataRecved > 0, "Didn't get any data back!");
   }
};

CreateUnitTest( TestTCPRequestJournal, "Platform/Net/JournalTCPRequest")
{
   NetSocket mSocket;
   S32 mDataRecved;

   void handleNotify(NetSocket sock, U32 state)
   {
      // Only consider our own socket.
      if(mSocket != sock)
         return;

      // Ok - what's the state? We do some dumb responses to given states
      // in order to fulfill the request.
      if(state == Net::Connected)
      {
         U8 reqBuffer[] = {
            "GET / HTTP/1.0\nUser-Agent: Torque/1.0\n\n"
         };

         Net::Error e = Net::sendtoSocket(mSocket, reqBuffer, sizeof(reqBuffer));

         test(e == Net::NoError, "Got an error sending our HTTP request!");
      }
      else if(state == Net::Disconnected)
      {
         Process::requestShutdown();
         mSocket = NULL;
      }
   }

   void handleReceive(NetSocket sock, RawData incomingData)
   {
      // Only consider our own socket.
      if(mSocket != sock)
         return;

      char buff[4096];
      dMemcpy(buff, incomingData.data, incomingData.size);
      buff[incomingData.size] = 0;

      UnitPrint("Got a message...\n");
      UnitPrint(buff);
      UnitPrint("------\n");

      mDataRecved += incomingData.size;
   }

   void makeRequest()
   {
      mSocket = InvalidSocket;
      mDataRecved = 0;

      // Initialize networking - done by initLibraries currently
      //test(Net::init(), "Failed to initialize networking!");

      // Hook into the signals.
      Net::smConnectionNotify. notify(this, &TestTCPRequestJournal::handleNotify);
      Net::smConnectionReceive.notify(this, &TestTCPRequestJournal::handleReceive);

      // Open a TCP connection to garagegames.com
      mSocket = Net::openConnectTo("ip:72.246.107.193:80");

      // Let the callbacks enable things to process.
      while(Process::processEvents())
         ;

      // Unhook from the signals.
      Net::smConnectionNotify. remove(this, &TestTCPRequestJournal::handleNotify);
      Net::smConnectionReceive.remove(this, &TestTCPRequestJournal::handleReceive);

      test(mDataRecved > 0, "Didn't get any data back!");
   }

   void run()
   {
      Journal::Record("journalTCP.jrn");

      makeRequest();

      S32 bytesRead = mDataRecved;

      Journal::Stop();

      Journal::Play("journalTCP.jrn");

      makeRequest();

      Journal::Stop();

      test(bytesRead == mDataRecved, "Didn't get same data back from journal playback.");

   }
};


text:
//-----------------------------------------------------------------------
// <copyright file="DefaultLanguage.cs" company="Thinking Solutions Pty Ltd">
//     Copyright (c) Thinking Solutions 2015. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using PatTuring2016.Speech.Forms;
using System.Speech.Recognition;
using System.Windows.Forms;

namespace PatTuring2016.Speech.LanguageCheckers
{
    public class DefaultLanguage : AbstractLanguage, ISpeechIsCommand
    {
        internal override void AddCommands(Choices commands)
        {
            // add language swap commands
            commands.Add("mandarin", "german", "italian");
            commands.Add("cantonese", "french", "australian");
            commands.Add("american", "english", "portuguese");
            commands.Add("spanish", "japanese", "korean");

            // other commands
            commands.Add("target only", "confirm source", "close the program");
            commands.Add("formal", "polite", "intimate", "reset");
            commands.Add("phonetics", "characters", "letters");
            commands.Add("low", "neutral", "high", "very high");

            // temporary commands
            commands.Add("Jackson helped the invaders no the police yesterday at the stadium, but Meagan did not.");
            commands.Add("Susan hit no helped the girl my mother ate the spaghetti with.");
            commands.Add("John saw the bear at the parking lot yesterday because he was alert.");
            commands.Add("Who helped?");
            commands.Add("Who didn't help?");
            commands.Add("Who was helpful?");
            commands.Add("Who was unhelpful?");
            commands.Add("When did Jackson help the invaders?");
            commands.Add("When did Jackson help the police?");
            commands.Add("Where did Jackson help?");
            commands.Add("Where did Meagan not help?");
            commands.Add("What did my mother eat?");
            commands.Add("Why did John see the bear?");
            commands.Add("Who was seen by John?");

            commands.Add("John ate the fish yesterday no the beef at the beach, and Beth, the pork.");
            commands.Add("My friend's mother saw the apple in the parking lot.");
            commands.Add("Then she went to the airport at 3pm.");
            commands.Add("Where was the apple seen?");
            commands.Add("Who saw the apple?");
            commands.Add("Where was the apple?");

            commands.Add("The witness arrived at the court.");
            commands.Add("Then, the lawyer saw himself in the mirror.");

            commands.Add("The lawyer arrived at the court.");
            commands.Add("Then the dog bit his mother.");
            commands.Add("Then, the witness saw himself in the mirror.");

            commands.Add("He answered the questions before he left.");
            commands.Add("Who answered?");

            commands.Add("Call Beth no John.");
            commands.Add("Who was called?");
        }

        internal override void SetIntimate(ConversingController conversingController)
        {
            ContextForm.cbxPolite.Text = "Low";
            ContextForm.cbxFormality.Text = "Neutral";
        }

        internal override void SetPolite(ConversingController conversingController)
        {
            ContextForm.cbxPolite.Text = "Neutral";
            ContextForm.cbxFormality.Text = "Neutral";
        }

        internal override void SetFormal(ConversingController conversingController)
        {
            ContextForm.cbxPolite.Text = "Neutral";
            ContextForm.cbxFormality.Text = "High";
        }

        // return true if we should continue
        public bool SpeechIsCommand(string text, Converser converser, ConversingController conversingController)
        {
            // deal with commands if present
            switch (text)
            {
                //case "target only":
                //    converser.cbxTargetOnly.Checked = true;
                //    return true;
                //case "confirm source":
                //    converser.cbxTargetOnly.Checked = false;
                //    return true;

                case "formal":
                    SetFormal(conversingController);
                    return true;

                case "polite":
                    SetPolite(conversingController);
                    return true;

                case "intimate":
                    SetIntimate(conversingController);
                    return true;

                case "close the program":
                    Application.Exit();
                    return true;
            }

            return false;
        }
    }
}


text:
[![Crates.io](https://img.shields.io/crates/v/json_macros.svg)](https://crates.io/crates/json_macros)
[![Build Status](https://travis-ci.org/tomjakubowski/json_macros.svg?branch=master)]
(https://travis-ci.org/tomjakubowski/json_macros)

``` rust
let properties = json! {
    "menu": {
        "id": "file",
        "value": "File",
        "popup": {
            "menuitem": [
                {"value": "New", "onclick": "CreateNewDoc()"},
                {"value": "Open", "onclick": "OpenDoc()"},
                {"value": "Close", "onclick": "CloseDoc()"}
            ]
        }
    }
};

let menu_value = properties.find_path(["menu", "value"])
    .map(|x| x.as_string());

assert_eq!(menu_value, Some("File"));
```

Use JSON-like literals in Rust to construct [`serde_json`][] `Value`s
or [`rustc-serialize`][] `Json` values.

Because `json_macros` is a compiler plugin, it's only compatible with
the Rust [nightly channel][rust-nightly].

Depending on your project's needs, you may ask `json_macros` to
generate code that constructs [`serde_json`][] values or code that
constructs [`rustc-serialize`][] values.

## Using json_macros with rustc-serialize

By default, `json_macros` generates code for `rustc-serialize`.  In a
future release, the default may switch to `serde_json`, but
`json_macros` should be at least optionally compatible with
`rustc-serialize` for as long as that crate is supported.

To use `json_macros` with `rustc-serialize`, add both packages as
dependencies to your `Cargo.toml`.

```toml
[dependencies]
json_macros = "^0.3"
rustc-serialize = "^0.3"
```

Your crate will also need to link with `rustc_serialize` and `use` it
in any submodule that uses the `json!()` macro.

```rust
extern crate rustc_serialize;

// ...

mod foo {
    use rustc_serialize;
    // ...
}
```

### Example

```rust
#![feature(plugin)]
#![plugin(json_macros)]

extern crate rustc_serialize;

pub fn main() {
    let x = 123i32;
    println!("{}", json!({ // object literal
        "foo": "foooooo", // string literal keys and values
        "bar": [true, null, 123, 123.4], // array, boolean, null, numeric literals
        "quux": { // nest as deeply as you like
          "a": [1, 2, 3, 4],
          "b": { "a": null },
          "c": false
        },
        "waldo": (192 - x) // wrap in parens to splice ToJson expressions directly
    }).pretty().to_string());
}
```

## Using json_macros with serde_json

To use `json_macros` with `serde_json`, add both packages as
dependencies to your `Cargo.toml`.  Enable the `with-serde_json`
feature for `json_macros` and disable the default features so as to
not depend on `rustc-serialize`.

```toml
[dependencies]
rustc-serialize = "^0.3"

[dependencies.json_macros]
version = "^0.3"
default-features = false
features = ["with-serde"]
```

Your crate will also need to link with `serde_json` and `use` it in
any submodule that uses the `json!()` macro.

```rust
extern crate serde_json;

// ...

mod foo {
    use serde_json;
    // ...
}
```

### Example

```rust
#![feature(plugin)]
#![plugin(json_macros)]

extern crate serde_json;

pub fn main() {
    let x = 123i32;
    println!("{}", serde_json::to_string_pretty(&json!({ // object literal
        "foo": "foooooo", // string literal keys and values
        "bar": [true, null, 123, 123.4], // array, boolean, null, numeric literals
        "quux": { // nest as deeply as you like
          "a": [1, 2, 3, 4],
          "b": { "a": null },
          "c": false
        },
        "waldo": (192 - x) // wrap in parens to splice ToJson expressions directly
    })).unwrap());
}
```

[`serde_json`]: <https://github.com/serde-rs/json>
[`rustc-serialize`]: <https://doc.rust-lang.org/rustc-serialize/rustc_serialize/index.html>
[rust-nightly]: <http://doc.rust-lang.org/book/nightly-rust.html>


text:
#include <stdlib.h>
#include <jni.h>
#include <android/log.h>
#include <string>
#include "platform/android/jni/JniHelper.h"
#include "platform/android/CCFileUtils-android.h"
#include "android/asset_manager_jni.h"
#include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"

#include "base/ccUTF8.h"

#define  LOG_TAG    "Java_org_cocos2dx_lib_Cocos2dxHelper.cpp"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)

static const std::string className = "org/cocos2dx/lib/Cocos2dxHelper";

static EditTextCallback s_editTextCallback = nullptr;
static void* s_ctx = nullptr;

static int __deviceSampleRate = 44100;
static int __deviceAudioBufferSizeInFrames = 192;

using namespace cocos2d;
using namespace std;

string g_apkPath;

extern "C" {

    JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetApkPath(JNIEnv*  env, jobject thiz, jstring apkPath) {
        g_apkPath = JniHelper::jstring2string(apkPath);
    }

    JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetContext(JNIEnv*  env, jobject thiz, jobject context, jobject assetManager) {
        JniHelper::setClassLoaderFrom(context);
        FileUtilsAndroid::setassetmanager(AAssetManager_fromJava(env, assetManager));
    }

    JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetAudioDeviceInfo(JNIEnv*  env, jobject thiz, jboolean isSupportLowLatency, jint deviceSampleRate, jint deviceAudioBufferSizeInFrames) {
        __deviceSampleRate = deviceSampleRate;
        __deviceAudioBufferSizeInFrames = deviceAudioBufferSizeInFrames;
        LOGD("nativeSetAudioDeviceInfo: sampleRate: %d, bufferSizeInFrames: %d", __deviceSampleRate, __deviceAudioBufferSizeInFrames);
    }

    JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) {
        jsize  size = env->GetArrayLength(text);

        if (size > 0) {
            jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0);
            char* buffer = (char*)malloc(size+1);
            if (buffer != nullptr) {
                memcpy(buffer, data, size);
                buffer[size] = '\0';
                // pass data to edittext's delegate
                if (s_editTextCallback) s_editTextCallback(buffer, s_ctx);
                free(buffer);
            }
            env->ReleaseByteArrayElements(text, data, 0);
        } else {
            if (s_editTextCallback) s_editTextCallback("", s_ctx);
        }
    }

}

const char * getApkPath() {
    return g_apkPath.c_str();
}

std::string getPackageNameJNI() {
    return JniHelper::callStaticStringMethod(className, "getCocos2dxPackageName");
}

int getObbAssetFileDescriptorJNI(const char* path, long* startOffset, long* size) {
    JniMethodInfo methodInfo;
    int fd = 0;

    if (JniHelper::getStaticMethodInfo(methodInfo, className.c_str(), "getObbAssetFileDescriptor", "(Ljava/lang/String;)[J")) {
        jstring stringArg = methodInfo.env->NewStringUTF(path);
        jlongArray newArray = (jlongArray)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, stringArg);
        jsize theArrayLen = methodInfo.env->GetArrayLength(newArray);

        if (theArrayLen == 3) {
            jboolean copy = JNI_FALSE;
            jlong *array = methodInfo.env->GetLongArrayElements(newArray, &copy);
            fd = static_cast<int>(array[0]);
            *startOffset = array[1];
            *size = array[2];
            methodInfo.env->ReleaseLongArrayElements(newArray, array, 0);
        }

        methodInfo.env->DeleteLocalRef(methodInfo.classID);
        methodInfo.env->DeleteLocalRef(stringArg);
    }

    return fd;
}

int getDeviceSampleRate()
{
    return __deviceSampleRate;
}

int getDeviceAudioBufferSizeInFrames()
{
    return __deviceAudioBufferSizeInFrames;
}

void conversionEncodingJNI(const char* src, int byteSize, const char* fromCharset, char* dst, const char* newCharset)
{
    JniMethodInfo methodInfo;

    if (JniHelper::getStaticMethodInfo(methodInfo, className.c_str(), "conversionEncoding", "([BLjava/lang/String;Ljava/lang/String;)[B")) {
        jbyteArray strArray = methodInfo.env->NewByteArray(byteSize);
        methodInfo.env->SetByteArrayRegion(strArray, 0, byteSize, reinterpret_cast<const jbyte*>(src));

        jstring stringArg1 = methodInfo.env->NewStringUTF(fromCharset);
        jstring stringArg2 = methodInfo.env->NewStringUTF(newCharset);

        jbyteArray newArray = (jbyteArray)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, strArray, stringArg1, stringArg2);
        jsize theArrayLen = methodInfo.env->GetArrayLength(newArray);
        methodInfo.env->GetByteArrayRegion(newArray, 0, theArrayLen, (jbyte*)dst);

        methodInfo.env->DeleteLocalRef(strArray);
        methodInfo.env->DeleteLocalRef(stringArg1);
        methodInfo.env->DeleteLocalRef(stringArg2);
        methodInfo.env->DeleteLocalRef(methodInfo.classID);
    }
}


text:
package uk.nhs.hdn.common.http.client.uploadContents;

import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import uk.nhs.hdn.common.http.ContentTypeWithCharacterSet;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;

public class ByteArrayUploadContent extends AbstractUploadContent
{
	@NotNull
	private final byte[] content;
	private final int length;

	@SuppressWarnings({"AssignmentToCollectionOrArrayFieldFromParameter", "MethodCanBeVariableArityMethod"})
	public ByteArrayUploadContent(@ContentTypeWithCharacterSet @NonNls @NotNull final String contentType, @NotNull final byte[] content)
	{
		super(contentType);
		this.content = content;
		length = content.length;
	}

	@Override
	public void configure(@NotNull final HttpURLConnection httpConnection)
	{
		super.configure(httpConnection);
		httpConnection.setFixedLengthStreamingMode(length);
	}

	@Override
	public final void upload(@NotNull final HttpURLConnection httpConnection) throws IOException
	{
		final OutputStream outputStream = httpConnection.getOutputStream();
		boolean firstExceptionThrown = false;
		try
		{
			outputStream.write(content);
			firstExceptionThrown = true;
		}
		finally
		{
			try
			{
				outputStream.close();
			}
			catch (IOException e)
			{
				if (firstExceptionThrown)
				{
					throw e;
				}
			}
		}
	}
}


text:
CWAC Layouts: Custom Containers, Concisely Coded
================================================

**UPDATE 2021-05-08**: This project is discontinued. This repository will be removed from public access on or after 1 December 2021.

This project has a handful
of Android containers (`ViewGroup` implementations) designed to handle
specific scenarios:

- `AspectLockedFrameLayout` that resizes itself, and its children, to
fit within a specific aspect ratio

- `MirroringFrameLayout` and an associated `Mirror` that duplicates and
scales the contents of the `MirroringFrameLayout` onto the `Mirror`

This Android library project is
[available as a JAR](https://github.com/commonsguy/cwac-layouts/releases)
or as an artifact for use with Gradle. To use that, add the following
blocks to your `build.gradle` file:

```groovy
repositories {
    maven {
        url "https://s3.amazonaws.com/repo.commonsware.com"
    }
}

dependencies {
    implementation 'com.commonsware.cwac:layouts:0.4.5'
}
```

Or, if you cannot use SSL, use `http://repo.commonsware.com` for the repository
URL.

**NOTE**: The JAR name, as of v0.4.1, has a `cwac-` prefix, to help distinguish it from other JARs.

Usage: AspectLockedFrameLayout
------------------------------
`AspectLockedFrameLayout` inherits from `FrameLayout`, and so you start by
setting it up much like you would any other `FrameLayout`. In fact, if you do
nothing else, it behaves the same as a regular `FrameLayout`.

However, if you call `setAspectRatio()` (supplying a `double` of the aspect
ratio you want) or `setAspectRatioSource()` (supplying a `View` whose aspect
ratio should be matched), then `AspectLockedFrameLayout` will reduce its height
or width to maintain the requested aspect ratio. This affects the children of
the `AspectLockedFrameLayout` as well, of course.

Since the `AspectLockedFrameLayout` effectively overrides and reduces its size,
you can use `android:layout_gravity` to position the shrunken
`AspectLockedFrameLayout` within its parent:

```xml
<FrameLayout
	android:layout_width="match_parent"
	android:layout_height="match_parent">

	<com.commonsware.cwac.layouts.AspectLockedFrameLayout
		android:id="@+id/source"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:layout_gravity="center">

		<!-- children go here -->
	</com.commonsware.cwac.layouts.AspectLockedFrameLayout>
</FrameLayout>
```

Note that the resizing only takes place when the `AspectLockedFrameLayout`
is measured. If you change the aspect ratio, call `requestLayout()` on
the `AspectLockedFrameLayout` (or any parent container) to get it to resize.

**NOTE**: `ConstraintLayout` also offers aspect ratio control, so you might
consider using it if it better fits your needs.

Usage: Mirroing
---------------
The mirror classes are specifically designed for use with Android's
`Presentation` class, specifically for actual presentations. In a presentation,
the presenter needs to be able to see and control some widgets, but the
audience simply needs to see the widgets via a projector or other external
display. `MirroringFrameLayout`, used as a container around the control
widgets, will clone its output onto the `Mirror` `View`, which in turn
can be hosted by a `Presentation`.

To mirror a widget or widget hierarchy, wrap it in a `com.commonsware.cwac.layouts.MirroringFrameLayout`:

```xml
<com.commonsware.cwac.layouts.MirroringFrameLayout
	android:id="@+id/source"
	android:layout_width="1000px"
	android:layout_height="0dp"
	android:layout_weight="1"
	android:background="#88FF0000">

	<WebView
	android:id="@+id/webkit"
	android:layout_width="match_parent"
	android:layout_height="match_parent"/>

</com.commonsware.cwac.layouts.MirroringFrameLayout>
```

Also add a `com.commonsware.cwac.layouts.Mirror` widget where you want the duplicate
contents to be rendered.

Then, in your Java code, attach the `Mirror` to the `MirroringFrameLayout`:

```java
MirroringFrameLayout source=
    (MirroringFrameLayout)findViewById(R.id.source);
Mirror target=(Mirror)findViewById(R.id.target);

source.setMirror(target);
```

And that's it.

This should work for all widgets except `SurfaceView` and `TextureView`, plus
things derived from them (e.g., `VideoView`, Maps V2 `MapView`).

Note that `MirroringFrameLayout` inherits from `AspectLockedFrameLayout` and sets its
aspect ratio to match that of the `Mirror`. This ensures that the `Mirror` will be
filled without some type of anamorphic stretching.

You are welcome to implement the `MirrorSink` interface on something and use that
as the destination for the mirroring, rather than use a `Mirror`.

JavaDocs
--------
An API reference, in the form of JavaDocs, is available [online](http://javadocs.commonsware.com/cwac/layouts/index.html).

Dependencies
------------
This project has no dependencies and should work on most versions of Android, though
it is only being tested on API Level 8+.

Version
-------
This is version v0.4.5 of this module, meaning it is coming along nicely.

Demo
----
In the `demo/` sub-project you will find
a `SimpleMirrorActivity` activity and a `WebMirrorActivity` that each
demonstrates the use of `MirroringFrameLayout` and `Mirror`.

Additional Documentation
------------------------
[The Busy Coder's Guide to Android Development](https://commonsware.com/Android)
contains a chapter on custom views that covers the classes from this
library, how to use them, and how they work.

License
-------
The code in this project is licensed under the Apache
Software License 2.0, per the terms of the included LICENSE
file.

Questions
---------
If you have questions regarding the use of this code, please post a question
on [StackOverflow](http://stackoverflow.com/questions/ask) tagged with
`commonsware-cwac` and `android` after [searching to see if there already is an answer](https://stackoverflow.com/search?q=[commonsware-cwac]+layouts). Be sure to indicate
what CWAC module you are having issues with, and be sure to include source code
and stack traces if you are encountering crashes.

If you have encountered what is clearly a bug, or if you have a feature request,
please post an [issue](https://github.com/commonsguy/cwac-layouts/issues).
The [contribution guidelines](CONTRIBUTING.md)
provide some suggestions for how to create a bug report that will get
the problem fixed the fastest.

You are also welcome to join
[the CommonsWare Community](https://community.commonsware.com/)
and post questions
and ideas to [the CWAC category](https://community.commonsware.com/c/cwac).

Do not ask for help via social media.

Also, if you plan on hacking
on the code with an eye for contributing something back,
please read the [contribution guidelines](CONTRIBUTING.md).

Release Notes
-------------
- v0.4.5: updated build instructions, added null check for bitmap in `MirroringFrameLayout`
- v0.4.4: updated build instructions, removed some unnecessary casts
- v0.4.3: reorganized code into Android Studio standard structured, added JavaDocs
- v0.4.2: updated for Android Studio 1.0 and new AAR publishing system
- v0.4.1: updated Gradle, fixed manifest for merging, added `cwac-` prefix to JAR
- v0.4.0: switched to `ViewTreeObserver` for more reliable updating; added `MirrorSink`
- v0.3.0: migrated to support Gradle and publish an AAR artifact
- v0.2.2: improved efficiency and resiliency to source/mirror issues
- v0.2.1: fixed `AspectLockedFrameLayout` to handle zero height/width better
- v0.2.0: added `AspectLockedFrameLayout` and used for `MirroringFrameLayout`
- v0.1.0: initial release

Who Made This?
--------------
![CommonsWare](http://commonsware.com/images/logo.png)


text:
package org.apache.cassandra.distributed.upgrade;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

import com.google.common.base.Preconditions;
import org.junit.After;
import org.junit.BeforeClass;

import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.dht.Murmur3Partitioner;
import org.apache.cassandra.distributed.UpgradeableCluster;
import org.apache.cassandra.distributed.api.ICluster;
import org.apache.cassandra.distributed.api.IInstanceConfig;
import org.apache.cassandra.distributed.impl.Instance;
import org.apache.cassandra.distributed.shared.DistributedTestBase;
import org.apache.cassandra.distributed.shared.Versions;
import org.apache.cassandra.utils.ByteBufferUtil;

import static org.apache.cassandra.distributed.shared.Versions.Major;
import static org.apache.cassandra.distributed.shared.Versions.Version;
import static org.apache.cassandra.distributed.shared.Versions.find;
import static org.apache.commons.lang3.ArrayUtils.isNotEmpty;

public class UpgradeTestBase extends DistributedTestBase
{
    @After
    public void afterEach()
    {
        System.runFinalization();
        System.gc();
    }

    @BeforeClass
    public static void beforeClass() throws Throwable
    {
        ICluster.setup();
    }

    public UpgradeableCluster.Builder builder()
    {
        return UpgradeableCluster.build();
    }

    public static interface RunOnCluster
    {
        public void run(UpgradeableCluster cluster) throws Throwable;
    }

    public static interface RunOnClusterAndNode
    {
        public void run(UpgradeableCluster cluster, int node) throws Throwable;
    }

    public static class TestVersions
    {
        final Version initial;
        final Version[] upgrade;

        public TestVersions(Version initial, Version ... upgrade)
        {
            Preconditions.checkArgument(isNotEmpty(upgrade), "TestVersions must be constructed with one or more target upgrade versions.");
            this.initial = initial;
            this.upgrade = upgrade;
        }
    }

    public static class TestCase implements Instance.ThrowingRunnable
    {
        private final Versions versions;
        private final List<TestVersions> upgrade = new ArrayList<>();
        private int nodeCount = 3;
        private RunOnCluster setup;
        private RunOnClusterAndNode runAfterNodeUpgrade;
        private RunOnCluster runAfterClusterUpgrade;
        private final Set<Integer> nodesToUpgrade = new LinkedHashSet<>();
        private Consumer<IInstanceConfig> configConsumer;

        public TestCase()
        {
            this(find());
        }

        public TestCase(Versions versions)
        {
            this.versions = versions;
        }

        public TestCase nodes(int nodeCount)
        {
            this.nodeCount = nodeCount;
            return this;
        }

        public TestCase upgrade(Major initial, Major ... upgrade)
        {
            this.upgrade.add(new TestVersions(versions.getLatest(initial),
                                              Arrays.stream(upgrade)
                                                    .map(versions::getLatest)
                                                    .toArray(Version[]::new)));
            return this;
        }

        public TestCase upgrade(Version initial, Version ... upgrade)
        {
            this.upgrade.add(new TestVersions(initial, upgrade));
            return this;
        }

        public TestCase setup(RunOnCluster setup)
        {
            this.setup = setup;
            return this;
        }

        public TestCase runAfterNodeUpgrade(RunOnClusterAndNode runAfterNodeUpgrade)
        {
            this.runAfterNodeUpgrade = runAfterNodeUpgrade;
            return this;
        }

        public TestCase runAfterClusterUpgrade(RunOnCluster runAfterClusterUpgrade)
        {
            this.runAfterClusterUpgrade = runAfterClusterUpgrade;
            return this;
        }

        public TestCase withConfig(Consumer<IInstanceConfig> config)
        {
            this.configConsumer = config;
            return this;
        }

        public void run() throws Throwable
        {
            if (setup == null)
                throw new AssertionError();
            if (upgrade.isEmpty())
                throw new AssertionError();
            if (runAfterClusterUpgrade == null && runAfterNodeUpgrade == null)
                throw new AssertionError();
            if (runAfterClusterUpgrade == null)
                runAfterClusterUpgrade = (c) -> {};
            if (runAfterNodeUpgrade == null)
                runAfterNodeUpgrade = (c, n) -> {};
            if (nodesToUpgrade.isEmpty())
                for (int n = 1; n <= nodeCount; n++)
                    nodesToUpgrade.add(n);

            for (TestVersions upgrade : this.upgrade)
            {
                try (UpgradeableCluster cluster = init(UpgradeableCluster.create(nodeCount, upgrade.initial, configConsumer)))
                {
                    setup.run(cluster);

                    for (Version version : upgrade.upgrade)
                    {
                        for (int n : nodesToUpgrade)
                        {
                            cluster.get(n).shutdown().get();
                            cluster.get(n).setVersion(version);
                            cluster.get(n).startup();
                            runAfterNodeUpgrade.run(cluster, n);
                        }

                        runAfterClusterUpgrade.run(cluster);
                    }
                }
            }
        }
        public TestCase nodesToUpgrade(int ... nodes)
        {
            Set<Integer> set = new HashSet<>(nodes.length);
            for (int n : nodes)
            {
                set.add(n);
            }
            nodesToUpgrade.addAll(set);
            return this;
        }

        public TestCase nodesToUpgradeOrdered(int ... nodes)
        {
            for (int n : nodes)
            {
                nodesToUpgrade.add(n);
            }
            return this;
        }
     }

    protected TestCase allUpgrades(int nodes, int... toUpgrade)
    {
        return new TestCase().nodes(nodes)
                             .upgrade(Versions.Major.v22, Versions.Major.v30)
                             .upgrade(Versions.Major.v22, Versions.Major.v3X)
                             .upgrade(Versions.Major.v30, Versions.Major.v3X)
                             .upgrade(Versions.Major.v30, Versions.Major.v4)
                             .upgrade(Versions.Major.v3X, Versions.Major.v4)
                             .nodesToUpgrade(toUpgrade);
    }

    protected static int primaryReplica(List<Long> initialTokens, Long token)
    {
        int primary = 1;

        for (Long initialToken : initialTokens)
        {
            if (token <= initialToken)
            {
                break;
            }

            primary++;
        }

        return primary;
    }

    protected static Long tokenFrom(int key)
    {
        DecoratedKey dk = Murmur3Partitioner.instance.decorateKey(ByteBufferUtil.bytes(key));
        return (Long) dk.getToken().getTokenValue();
    }

    protected static int nextNode(int current, int numNodes)
    {
        return current == numNodes ? 1 : current + 1;
    }
}


text:
<?php
/**
 * sevenX - WPDevKit
 * Custom configuration by sevenX
 *
 * The wp-config.php creation script uses this file during the
 * installation. You don't have to use the web site, you can
 * copy this file to "wp-config.php" and fill in the values.
 *
 * Summary:
 * * Initial settings
 * * Path/File settings
 * * Database Setting
 * * FTP Setting
 * * Security Settings
 * * Maintenance/Performance settings
 * * Dev/Debug settings
 * * Theme settings
 */

// #####################################
// Initial settings
// #####################################
/** @var string Directory containing all of the site's files */
$root_dir = dirname(__DIR__);

/** @var string Document Root */
$webroot_dir = $root_dir . '/';

// * Expose global env() function from oscarotero/env
Env::init();

// * Use Dotenv to set required environment variables and load .env file in root
$dotenv = new Dotenv\Dotenv($root_dir);
if (file_exists($root_dir . '/.env')) {
    $dotenv->load();
    $dotenv->required(['DB_NAME', 'DB_USER', 'DB_PASSWORD', 'WP_HOME', 'WP_SITEURL']);
}

/**
 * Set up our global environment constant and load its config first
 * Default: dev
 */
$envs = [
	'dev'       => 'http://example.dev',
	'staging'   => 'http://staging.example.com',
	'live'      => 'http://example.com'
];
define('ENVIRONMENTS', serialize($envs));
define('WP_ENV', env('WP_ENV') ?: 'dev');

$env_config = __DIR__ . '/env/' . WP_ENV . '.php';

if (file_exists($env_config)) {
    require_once $env_config;
}

// #####################################
// Path/File settings
// #####################################
// * URLs
define('WP_HOME', env('WP_HOME'));
define('WP_SITEURL', env('WP_SITEURL'));

// * Custom Content Directory
define('CONTENT_DIR', '/content');
define('WP_CONTENT_DIR', $webroot_dir . CONTENT_DIR);
define('WP_CONTENT_URL', WP_HOME . CONTENT_DIR);

// #####################################
// Database Setting
// #####################################
define('DB_NAME', env('DB_NAME'));
define('DB_USER', env('DB_USER'));
define('DB_PASSWORD', env('DB_PASSWORD'));
define('DB_HOST', env('DB_HOST') ?: 'localhost');
define('DB_CHARSET', 'utf8');
define('DB_COLLATE', '');

// * Changed for security reasons
$table_prefix = env('DB_PREFIX') ?: 'uniqueprefix_';
define( 'CUSTOM_USER_TABLE',      $table_prefix . 'authorized_user' );
define( 'CUSTOM_USER_META_TABLE', $table_prefix . 'authorized_usermeta' );

// #####################################
// FTP Settings
// #####################################
define( 'FTP_HOST', env('FTP_HOST') );
define( 'FTP_USER', env('FTP_USER') );
define( 'FTP_PASS', env('FTP_PASS') );
define( 'FTP_SSL', 	env('FTP_SSL') );
define( 'FS_METHOD', env('FS_METHOD') );

// #####################################
// Security Settings
// #####################################
// * Generator https://api.wordpress.org/secret-key/1.1/salt
define('AUTH_KEY', env('AUTH_KEY'));
define('SECURE_AUTH_KEY', env('SECURE_AUTH_KEY'));
define('LOGGED_IN_KEY', env('LOGGED_IN_KEY'));
define('NONCE_KEY', env('NONCE_KEY'));
define('AUTH_SALT', env('AUTH_SALT'));
define('SECURE_AUTH_SALT', env('SECURE_AUTH_SALT'));
define('LOGGED_IN_SALT', env('LOGGED_IN_SALT'));
define('NONCE_SALT', env('NONCE_SALT'));

/*
// secure logins and dashboard, passwords and cookies are never sent in the clear
define('FORCE_SSL_ADMIN', TRUE);
define('FORCE_SSL_LOGIN', TRUE);
/**/
/*
// Enabling/Disabling theme/plugin editor
define( 'DISALLOW_FILE_EDIT', TRUE );
/**/
/*
// Disallow anything that creates, deletes, or edits core, plugin, or theme files.
define( 'DISALLOW_FILE_MODS', TRUE );
/**/
/*
// Disallow unfiltered_html for all users, even admins and super admins
define( 'DISALLOW_UNFILTERED_HTML', TRUE );
/**/
/*
// Allow uploads of filtered file types to users with administrator role
define( 'ALLOW_UNFILTERED_UPLOADS', FALSE );
/**/

// #####################################
// Maintenance/Performance settings
// #####################################
// * Disable WordPress Auto Updates:
define( 'AUTOMATIC_UPDATER_DISABLED', FALSE );

// * Enable/Disable Core Updates:
define( 'WP_AUTO_UPDATE_CORE', 'minor' ); // true, false

// * Memory Limit
define( 'WP_MEMORY_LIMIT', '128M');

// * Autosave Interval in seconds
define( 'AUTOSAVE_INTERVAL', 60);

// * Limit Post/Page Revisions
define( 'WP_POST_REVISIONS', 6);

// * Enabling Trash for Media Files
define( 'MEDIA_TRASH', TRUE );

// * Disable Media Revisions
define( 'IMAGE_EDIT_OVERWRITE', TRUE );

// * days before WordPress permanently deletes
define( 'EMPTY_TRASH_DAYS', 14);

// * Setup Multi site
define( 'WP_ALLOW_MULTISITE', FALSE);

// * Compression for JS and styles
define( 'CONCATENATE_SCRIPTS', FALSE );
define( 'COMPRESS_SCRIPTS',    FALSE );

// * DB Repair - http://yourwebsite.com/wp-admin/maint/repair.php*/
define('WP_ALLOW_REPAIR', FALSE);

// #####################################
// Dev/Debug settings
// #####################################
// * Instant Debug via URL param: ?debugger=true
if ( isset($_GET['debugger']) && $_GET['debugger'] === 'true') {
    define( 'WP_DEBUG', TRUE );
} else {
    define( 'WP_DEBUG', FALSE );
}
if ( WP_DEBUG ) {
    define('WP_DEBUG_LOG', TRUE); // leave the debug file in WP_CONTENT_DIR . '/debug.log'
    define('WP_DEBUG_DISPLAY', TRUE);
    define('SAVEQUERIES', TRUE); // saves database queries to an array and can be displayed
    define('SCRIPT_DEBUG', TRUE); // non-minified versions of the Javascripts will be used.
    @ini_set('log_errors', 'On');
    @ini_set('display_errors', 'On');
    @ini_set('error_log', $_SERVER['DOCUMENT_ROOT'] . '/logs/php_errors.log');
}

// #####################################
// More setting
// #####################################
define('WP_DEFAULT_THEME', 'twentysixteen');
define('WPLANG', 'de_DE');
define('WPLANG_DIR', 'languages');
define('DISABLE_WP_CRON', env('DISABLE_WP_CRON') ?: false);

// #####################################
// Bootstrap Wordpress
// #####################################
if (!defined('ABSPATH')) {
    define('ABSPATH', $webroot_dir . '/wp/');
}


text:
package org.apache.causeway.core.metamodel.interactions;

import org.apache.causeway.applib.Identifier;
import org.apache.causeway.applib.annotation.Where;
import org.apache.causeway.applib.services.wrapper.events.ActionVisibilityEvent;
import org.apache.causeway.core.metamodel.consent.InteractionContextType;
import org.apache.causeway.core.metamodel.consent.InteractionInitiatedBy;
import org.apache.causeway.core.metamodel.object.MmUnwrapUtil;
import org.apache.causeway.core.metamodel.spec.feature.ObjectAction;

/**
 * See {@link InteractionContext} for overview; analogous to
 * {@link ActionVisibilityEvent}.
 */
public class ActionVisibilityContext
extends VisibilityContext
implements ActionInteractionContext  {

    private final ObjectAction objectAction;

    public ActionVisibilityContext(
            final InteractionHead head,
            final ObjectAction objectAction,
            final Identifier identifier,
            final InteractionInitiatedBy interactionInitiatedBy,
            final Where where) {
        super(InteractionContextType.ACTION_VISIBLE, head, identifier, interactionInitiatedBy, where);
        this.objectAction = objectAction;
    }

    @Override
    public ObjectAction getObjectAction() {
        return objectAction;
    }

    @Override
    public ActionVisibilityEvent createInteractionEvent() {
        return new ActionVisibilityEvent(MmUnwrapUtil.single(getTarget()), getIdentifier());
    }

}


text:
package com.devspark.robototextview.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.DigitalClock;

import com.devspark.robototextview.util.RobotoTextViewUtils;

/**
 * Implementation of a {@link DigitalClock} with native support for all the Roboto fonts.
 *
 * @author Evgeny Shishkin
 */
public class RobotoDigitalClock extends DigitalClock {

    /**
     * Simple constructor to use when creating a widget from code.
     *
     * @param context The Context the widget is running in, through which it can
     *                access the current theme, resources, etc.
     */
    public RobotoDigitalClock(Context context) {
        this(context, null);
    }

    /**
     * Constructor that is called when inflating a widget from XML. This is called
     * when a widget is being constructed from an XML file, supplying attributes
     * that were specified in the XML file. This version uses a default style of
     * 0, so the only attribute values applied are those in the Context's Theme
     * and the given AttributeSet.
     *

     *

     * The method onFinishInflate() will be called after all children have been
     * added.
     *
     * @param context The Context the widget is running in, through which it can
     *                access the current theme, resources, etc.
     * @param attrs   The attributes of the XML tag that is inflating the widget.
     */
    public RobotoDigitalClock(Context context, AttributeSet attrs) {
        super(context, attrs);

        if (!isInEditMode()) {
            RobotoTextViewUtils.initTypeface(this, context, attrs);
        }
    }

}


text:
//------------------------------------------------------------------------------
// <copyright file="SynchronizationContextMode.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.Util {
    using System;

    internal enum SynchronizationContextMode {

        Normal,
        Legacy

    }
}


text:
import { Scheduler } from "../core/Scheduler";
import { Record } from "./Record";
import { MockObserver } from "./MockObserver";
import { IObserver } from "../observer/IObserver";
import { Observer } from "../core/Observer";
import { TestStream } from "./TestStream";
import { MockPromise } from "./MockPromise";
export declare class TestScheduler extends Scheduler {
    static next(tick: any, value: any): Record;
    static error(tick: any, error: any): Record;
    static completed(tick: any): Record;
    static create(isReset?: boolean): TestScheduler;
    constructor(isReset: boolean);
    private _clock;
    clock: number;
    private _isReset;
    private _isDisposed;
    private _timerMap;
    private _streamMap;
    private _subscribedTime;
    private _disposedTime;
    private _observer;
    setStreamMap(observer: IObserver, messages: [Record]): void;
    remove(observer: Observer): void;
    publishRecursive(observer: MockObserver, initial: any, recursiveFunc: Function): void;
    publishInterval(observer: IObserver, initial: any, interval: number, action: Function): number;
    publishIntervalRequest(observer: IObserver, action: Function): number;
    publishTimeout(observer: IObserver, time: number, action: Function): number;
    private _setClock();
    startWithTime(create: Function, subscribedTime: number, disposedTime: number): MockObserver;
    startWithSubscribe(create: any, subscribedTime?: number): MockObserver;
    startWithDispose(create: any, disposedTime?: number): MockObserver;
    publicAbsolute(time: any, handler: any): void;
    start(): void;
    createStream(args: any): TestStream;
    createObserver(): MockObserver;
    createResolvedPromise(time: number, value: any): MockPromise;
    createRejectPromise(time: number, error: any): MockPromise;
    private _getMinAndMaxTime();
    private _exec(time, map);
    private _runStream(time);
    private _runAt(time, callback);
    private _tick(time);
}


text:
{% extends "mobile/portal_template.html" %}
{% load experimentstats %}

		{% block content %}

			 {% if experiments %}
	            {{ experiments.count }} Experiments
		    {% endif %}

		{% if experiments %}
			{% for experiment in experiments %}

				{{experiment.title}}

					From {{experiment.institution_name}}, deposited {{ experiment.update_time|date:"jS F Y" }}

					{{ experiment.dataset_set.all.count }} dataset(s), containing {{ experiment.id|experiment_file_count }} files

			{% endfor %}
		{% endif %}

			{% endblock %}


text: .. automodule:: skrf.media.device


text:
package main

import (
	"fmt"
	"log"
	"os"
	"os/user"
	"strconv"
	"strings"

	"github.com/pkg/errors"

	"github.com/google/fscrypt/actions"
	"github.com/google/fscrypt/metadata"
	"github.com/google/fscrypt/util"
)

const (
	// Suffixes for questions with a yes or no default
	defaultYesSuffix = " [Y/n] "
	defaultNoSuffix  = " [y/N] "
)

// Descriptions for each of the protector sources
var sourceDescriptions = map[metadata.SourceType]string{
	metadata.SourceType_pam_passphrase:    "Your login passphrase",
	metadata.SourceType_custom_passphrase: "A custom passphrase",
	metadata.SourceType_raw_key:           "A raw 256-bit key",
}

// askQuestion asks the user a yes or no question. Returning a boolean on a
// successful answer and an error if there was not a response from the user.
// Returns the defaultChoice on empty input (or in quiet mode).
func askQuestion(question string, defaultChoice bool) (bool, error) {
	// If in quiet mode, we just use the default
	if quietFlag.Value {
		return defaultChoice, nil
	}
	// Loop until failure or valid input
	for {
		if defaultChoice {
			fmt.Print(question + defaultYesSuffix)
		} else {
			fmt.Print(question + defaultNoSuffix)
		}

		input, err := util.ReadLine()
		if err != nil {
			return false, err
		}

		switch strings.ToLower(input) {
		case "y", "yes":
			return true, nil
		case "n", "no":
			return false, nil
		case "":
			return defaultChoice, nil
		}
	}
}

// askConfirmation asks the user for confirmation of a specific action. An error
// is returned if the user declines or IO fails.
func askConfirmation(question string, defaultChoice bool, warning string) error {
	// All confirmations are "yes" if we are forcing.
	if forceFlag.Value {
		return nil
	}

	// Defaults of "no" require forcing.
	if !defaultChoice {
		if quietFlag.Value {
			return ErrNoDestructiveOps
		}
	}

	if warning != "" && !quietFlag.Value {
		fmt.Println(wrapText("WARNING: "+warning, 0))
	}

	confirmed, err := askQuestion(question, defaultChoice)
	if err != nil {
		return err
	}
	if !confirmed {
		return ErrCanceled
	}
	return nil
}

// usernameFromID returns the username for the provided UID. If the UID does not
// correspond to a user or the username is blank, an error is returned.
func usernameFromID(uid int64) (string, error) {
	u, err := user.LookupId(strconv.Itoa(int(uid)))
	if err != nil || u.Username == "" {
		return "", errors.Wrapf(ErrUnknownUser, "uid %d", uid)
	}
	return u.Username, nil
}

// formatUsername either returns the username for the provided UID, or a string
// containing the error for unknown UIDs.
func formatUsername(uid int64) string {
	username, err := usernameFromID(uid)
	if err != nil {
		return fmt.Sprintf("[%v]", err)
	}
	return username
}

// formatInfo gives a string description of metadata.ProtectorData.
func formatInfo(data actions.ProtectorInfo) string {
	switch data.Source() {
	case metadata.SourceType_pam_passphrase:
		return "login protector for " + formatUsername(data.UID())
	case metadata.SourceType_custom_passphrase:
		return fmt.Sprintf("custom protector %q", data.Name())
	case metadata.SourceType_raw_key:
		return fmt.Sprintf("raw key protector %q", data.Name())
	default:
		panic(ErrInvalidSource)
	}
}

// promptForName gets a name from user input (or flags) and returns it.
func promptForName(ctx *actions.Context) (string, error) {
	// A name flag means we do not need to prompt
	if nameFlag.Value != "" {
		return nameFlag.Value, nil
	}

	// Don't ask for a name if we do not need it
	if quietFlag.Value || ctx.Config.Source == metadata.SourceType_pam_passphrase {
		return "", nil
	}

	for {
		fmt.Print("Enter a name for the new protector: ")
		name, err := util.ReadLine()
		if err != nil {
			return "", err
		}
		if name != "" {
			return name, nil
		}
	}
}

// promptForSource gets a source type from user input (or flags) and modifies
// the context to use that source.
func promptForSource(ctx *actions.Context) error {
	// A source flag overrides everything else.
	if sourceFlag.Value != "" {
		val, ok := metadata.SourceType_value[sourceFlag.Value]
		if !ok || val == 0 {
			return ErrInvalidSource
		}
		ctx.Config.Source = metadata.SourceType(val)
		return nil
	}

	// Just use the default in quiet mode
	if quietFlag.Value {
		return nil
	}

	// We print all the sources with their number, description, and name.
	fmt.Println("The following protector sources are available:")
	for idx := 1; idx < len(metadata.SourceType_value); idx++ {
		source := metadata.SourceType(idx)
		description := sourceDescriptions[source]
		fmt.Printf("%d - %s (%s)\n", idx, description, source)
	}

	for {
		fmt.Printf("Enter the source number for the new protector [%d - %s]: ",
			ctx.Config.Source, ctx.Config.Source)
		input, err := util.ReadLine()
		if err != nil {
			return err
		}

		// Use the default if the user just hits enter
		if input == "" {
			return nil
		}

		// Check for a valid index, reprompt if invalid.
		index, err := strconv.Atoi(input)
		if err == nil && index >= 1 && index < len(metadata.SourceType_value) {
			ctx.Config.Source = metadata.SourceType(index)
			return nil
		}
	}
}

// promptForKeyFile returns an open file that should be used to create or unlock
// a raw_key protector. Be sure to close the file when done.
func promptForKeyFile(prompt string) (*os.File, error) {
	// If specified on the command line, we only try no open it once.
	if keyFileFlag.Value != "" {
		return os.Open(keyFileFlag.Value)
	}
	if quietFlag.Value {
		return nil, ErrSpecifyKeyFile
	}

	// Prompt for a valid path until we get a file we can open.
	for {
		fmt.Print(prompt)
		filename, err := util.ReadLine()
		if err != nil {
			return nil, err
		}
		file, err := os.Open(filename)
		if err == nil {
			return file, nil
		}
		fmt.Println(err)
	}

}

// promptForProtector, given a non-empty list of protector options, uses user
// input to select the desired protector. If there is only one option to choose
// from, that protector is automatically selected.
func promptForProtector(options []*actions.ProtectorOption) (int, error) {
	numOptions := len(options)
	log.Printf("selecting from %s", pluralize(numOptions, "protector"))

	// Get the number of load errors.
	numLoadErrors := 0
	for _, option := range options {
		if option.LoadError != nil {
			log.Printf("when loading option: %v", option.LoadError)
			numLoadErrors++
		}
	}

	if numLoadErrors == numOptions {
		return 0, ErrAllLoadsFailed
	}
	if numOptions == 1 {
		return 0, nil
	}
	if quietFlag.Value {
		return 0, ErrSpecifyProtector
	}

	// List all of the protector options which did not have a load error.
	fmt.Println("The available protectors are: ")
	for idx, option := range options {
		if option.LoadError != nil {
			continue
		}

		description := fmt.Sprintf("%d - %s", idx, formatInfo(option.ProtectorInfo))
		if option.LinkedMount != nil {
			description += fmt.Sprintf(" (linked protector on %q)", option.LinkedMount.Path)
		}
		fmt.Println(description)
	}

	if numLoadErrors > 0 {
		loadWarning := fmt.Sprintf("NOTE: %d of the %d protectors failed to load. ", numLoadErrors, numOptions)
		fmt.Print(wrapText(loadWarning+loadHelpText, 0) + "\n")
	}

	for {
		fmt.Print("Enter the number of protector to use: ")
		input, err := util.ReadLine()
		if err != nil {
			return 0, err
		}

		// Check for a valid index, reprompt if invalid.
		index, err := strconv.Atoi(input)
		if err == nil && index >= 0 && index < len(options) {
			return index, nil
		}
	}
}

// optionFn is an actions.OptionFunc which handles selecting an option for a
// specific policy. This is either done interactively, or by deferring to the
// protectorFlag.
func optionFn(policyDescriptor string, options []*actions.ProtectorOption) (int, error) {
	// If we have an unlock-with flag, we directly select the specified
	// protector to unlock the policy.
	if unlockWithFlag.Value != "" {
		log.Printf("optionFn(%s) w/ unlock flag", policyDescriptor)
		protector, err := getProtectorFromFlag(unlockWithFlag.Value, nil)
		if err != nil {
			return 0, err
		}

		for idx, option := range options {
			if option.Descriptor() == protector.Descriptor() {
				return idx, nil
			}
		}
		return 0, &actions.ErrNotProtected{PolicyDescriptor: policyDescriptor,
			ProtectorDescriptor: protector.Descriptor()}
	}

	log.Printf("optionFn(%s)", policyDescriptor)
	return promptForProtector(options)
}


text:
"use strict";

/**
 * Lamella
 * @class LAMELLA
 * @constructor
 */
function LAMELLA() {

  /**
   * Playing state
   * @type {Boolean}
   * @default false
   */
  this.paused = false;

  /**
   * Ready state
   * @type {Boolean}
   * @default false
   */
  this.ready = false;

  /**
   * Plugins
   * @type {Object}
   * @default Object
   */
  this.plugins = {};

  /**
   * Models
   * @type {Object}
   * @default Object
   */
  this.models = {};

  /**
   * Scenes
   * @type {Object}
   * @default Object
   */
  this.scenes = {};

  /**
   * Keypress map
   * @type {Object}
   */
  this.KEYMAP = {
    BACKSPACE: 8,
    TAB:       9,
    ENTER:     13,
    SHIFT:     16,
    CTRL:      17,
    ALT:       18,
    SPACE:     32,
    ARROW_L:   37,
    ARROW_U:   38,
    ARROW_R:   39,
    ARROW_D:   40,
  };

  /**
   * Collision map
   * @type {Object}
   */
  this.collisions = {
    CUBIC:    1,
    CIRCULAR: 2
  };

  /**
   * Pressed keys
   * @type {Object}
   */
  this.keys = {};

};

LAMELLA.prototype.constructor = LAMELLA;

/**
 * Run
 * @param {Boolean} ready
 * @method run
 */
LAMELLA.prototype.run = function(ready) {

  switch (ready) {

    /** Initialise system */
    case true:
      this.syncSettings();
      this.watchKeys();
      watch(this.Config, function(){
        this.setStorage(this.Config.storageKey, this.Config);
      }.bind(this));
      /** @async */
      this.Core.init(0, (function() {
        this.Hud.init(0, (function() {
          this.Interpreter.init(0, (function() {
            this.ready = true;
            this.Core.Grid.draw();
            console.info(this.getText("s_SystemLoaded"));
          }).bind(this));
        }).bind(this));
      }).bind(this));
    break;

    /** Fade in ui */
    case false:
      FastClick.attach(document.body);

      $("#progress-container").style.opacity = 0;
      $("#progress-logo").style.opacity      = 0;

      $("#nav").style.opacity  = 1;
      $("#main").style.opacity = 1;

      setTimeout(function() {
        $("#progress-container").style.display = "none";
        $("#progress-logo").style.display      = "none";

        this.run(true);
      }.bind(this), 50);
    break;

  };

  return void 0;

};

/**
 * Shortcut
 * Language specific text call
 * @param {String} key
 * @method getText
 * @return {String}
 */
LAMELLA.prototype.getText = function(key) {

  return this.Core.Language.get(key);

};

/**
 * Dynamic session rebuild
 * Rebuild language instance
 * Refresh grid instance
 * @param {Function} resolve
 * @method rebuild
 */
LAMELLA.prototype.rebuild = function(resolve) {

  this.Core.Language.change(this.Config.language.currentLang, function() {

    this.Hud.rebuildScenes();

    this.Core.Grid.drawTexts(true);

    if (resolve instanceof Function) resolve();

  }.bind(this));

  return void 0;

};

/**
 * Synchronize settings
 * @method syncSettings
 */
LAMELLA.prototype.syncSettings = function() {

  if (!this.getStorage(this.Config.storageKey)) {
    this.setStorage(this.Config.storageKey, this.Config);
  }

  var config = JSON.parse(this.getStorage(this.Config.storageKey));

  /** Synchronize grid settings */
  for (var key in config.grid) {
    this.Config.grid[key] = config.grid[key];
  };

  return void 0;

};

/**
 * Valid key code
 * @param {Number} key
 * @method validKey
 * @return {String}
 */
LAMELLA.prototype.validKey = function(key) {

  for (var ii in this.KEYMAP) {
    if (key === this.KEYMAP[ii]) {
      return (ii);
    }
  };

  return void 0;

};

/**
 * Watch pressed keys
 * @method watchKeys
 */
LAMELLA.prototype.watchKeys = function() {

  var keyDown = null;
  var keyUp   = null;

  window.addEventListener('keydown', function(e) {
    if (keyDown = this.validKey(e.keyCode)) {
      this.keys[keyDown] = true;
    }
  }.bind(this));

  window.addEventListener('keyup', function(e) {

    if (keyUp = this.validKey(e.keyCode)) {
      this.keys[keyUp] = false;
    }
  }.bind(this));

  return void 0;

};


text:
package org.carbon.sample.v2.infra.secured;

import lombok.Getter;
import lombok.Setter;
import org.carbon.modular.annotation.Property;

/**
 * @author garden 2018/03/29.
 */
@Setter
@Getter
@Property(key = "rocketty.cipher")
public class RockettyCipherProperty {
    private String passphrase;

    public RockettyCipherProperty() {
    }
}


text:
package org.elasticsearch.xpack.analytics.aggregations.metrics;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.ScoreMode;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.util.DoubleArray;
import org.elasticsearch.index.fielddata.HistogramValue;
import org.elasticsearch.index.fielddata.HistogramValues;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.LeafBucketCollector;
import org.elasticsearch.search.aggregations.LeafBucketCollectorBase;
import org.elasticsearch.search.aggregations.metrics.InternalMin;
import org.elasticsearch.search.aggregations.metrics.NumericMetricsAggregator;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
import org.elasticsearch.xpack.analytics.aggregations.support.HistogramValuesSource;

import java.io.IOException;
import java.util.Map;

public class HistoBackedMinAggregator extends NumericMetricsAggregator.SingleValue {

    private final HistogramValuesSource.Histogram valuesSource;
    final DocValueFormat format;
    DoubleArray mins;

    public HistoBackedMinAggregator(
        String name,
        ValuesSourceConfig config,
        AggregationContext context,
        Aggregator parent,
        Map<String, Object> metadata
    ) throws IOException {
        super(name, context, parent, metadata);
        this.valuesSource = config.hasValues() ? (HistogramValuesSource.Histogram) config.getValuesSource() : null;
        if (valuesSource != null) {
            mins = bigArrays().newDoubleArray(1, false);
            mins.fill(0, mins.size(), Double.POSITIVE_INFINITY);
        }
        this.format = config.format();
    }

    @Override
    public ScoreMode scoreMode() {
        return valuesSource != null && valuesSource.needsScores() ? ScoreMode.COMPLETE : ScoreMode.COMPLETE_NO_SCORES;
    }

    @Override
    public LeafBucketCollector getLeafCollector(LeafReaderContext ctx, final LeafBucketCollector sub) throws IOException {
        if (valuesSource == null) {
            return LeafBucketCollector.NO_OP_COLLECTOR;
        }

        final HistogramValues values = valuesSource.getHistogramValues(ctx);
        return new LeafBucketCollectorBase(sub, values) {

            @Override
            public void collect(int doc, long bucket) throws IOException {
                if (bucket >= mins.size()) {
                    long from = mins.size();
                    mins = bigArrays().grow(mins, bucket + 1);
                    mins.fill(from, mins.size(), Double.POSITIVE_INFINITY);
                }

                if (values.advanceExact(doc)) {
                    final HistogramValue sketch = values.histogram();
                    while (sketch.next()) {
                        double value = sketch.value();
                        double min = mins.get(bucket);
                        min = Math.min(min, value);
                        mins.set(bucket, min);
                    }
                }

            }
        };
    }

    @Override
    public double metric(long owningBucketOrd) {
        if (valuesSource == null || owningBucketOrd >= mins.size()) {
            return Double.POSITIVE_INFINITY;
        }
        return mins.get(owningBucketOrd);
    }

    @Override
    public InternalAggregation buildAggregation(long bucket) {
        if (valuesSource == null || bucket >= mins.size()) {
            return buildEmptyAggregation();
        }
        return new InternalMin(name, mins.get(bucket), format, metadata());
    }

    @Override
    public InternalAggregation buildEmptyAggregation() {
        return new InternalMin(name, Double.POSITIVE_INFINITY, format, metadata());
    }

    @Override
    public void doClose() {
        Releasables.close(mins);
    }
}


text:
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
    {
        "file": "plugins/org.apache.cordova.core.network-information/www/network.js",
        "id": "org.apache.cordova.core.network-information.network",
        "clobbers": [
            "navigator.connection",
            "navigator.network.connection"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.core.network-information/www/Connection.js",
        "id": "org.apache.cordova.core.network-information.Connection",
        "clobbers": [
            "Connection"
        ]
    }
]
});


text:
sudo apt-get install ruby-dev -y
sudo gem install jekyll bundler
printf "source 'https://rubygems.org' \ngem 'github-pages', group: :jekyll_plugins" > Gemfile
bundle install
bundle exec jekyll serve


text:
module Fog
  module Compute
    class Brightbox
      class Real

        def update_user(identifier, options)
          return nil if identifier.nil? || identifier == ""
          return nil if options.empty? || options.nil?
          request("put", "/1.0/users/#{identifier}", [200], options)
        end

      end
    end
  end
end


text:
import sst
import sst.actions

# test get_page_source

sst.actions.set_base_url('http://localhost:%s/' % sst.DEVSERVER_PORT)
sst.actions.go_to('/')

txt = sst.actions.get_page_source()

assert (txt != '')
assert '<html' in txt
assert '</head>' in txt
assert '<body>' in txt

# test get_element_source

elems = sst.actions.get_elements(tag='p')
for elem in elems:
    txt = sst.actions.get_element_source(elem)
    assert (len(txt) >= 0)


text:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

import { Story, Sprint } from '@ya-scrum/models';

@Component({
  selector: 'ya-story-selector-grid',
  templateUrl: './story-selector-grid.component.html',
  styleUrls: ['./story-selector-grid.component.scss']
})
export class StorySelectorGridComponent {

  @Input() stories: Story[];
  @Input() sprint: Sprint[];

  constructor(
  ) {
  }

  trackStory(index, story: Story) {
    return story ? story.$key : undefined;
  }

}


text:
from util import *

@responses.activate
def test_get(client, dummy_data):
    stub(responses.GET, "https://api.nexmo.com/v1/applications")
    host = "api.nexmo.com"
    request_uri = "/v1/applications"
    params = {"aaa": "xxx", "bbb": "yyy"}
    response = client.get(host, request_uri, params=params)
    assert isinstance(response, dict)
    assert request_user_agent() == dummy_data.user_agent
    assert "aaa=xxx" in request_query()
    assert "bbb=yyy" in request_query()

@responses.activate
def test_get_with_auth(client, dummy_data):
    stub(responses.GET, "https://api.nexmo.com/v1/applications")
    host = "api.nexmo.com"
    request_uri = "/v1/applications"
    params = {"aaa": "xxx", "bbb": "yyy"}
    response = client.get(host, request_uri, params=params, header_auth=True)
    assert isinstance(response, dict)
    assert request_user_agent() == dummy_data.user_agent
    assert "aaa=xxx" in request_query()
    assert "bbb=yyy" in request_query()
    assert_basic_auth()

@responses.activate
def test_post(client, dummy_data):
    stub(responses.POST, "https://api.nexmo.com/v1/applications")
    host = "api.nexmo.com"
    request_uri = "/v1/applications"
    params = {"aaa": "xxx", "bbb": "yyy"}
    response = client.post(host, request_uri, params)
    assert isinstance(response, dict)
    assert request_user_agent() == dummy_data.user_agent
    assert "aaa=xxx" in request_body()
    assert "bbb=yyy" in request_body()

@responses.activate
def test_post_with_auth(client, dummy_data):
    stub(responses.POST, "https://api.nexmo.com/v1/applications")
    host = "api.nexmo.com"
    request_uri = "/v1/applications"
    params = {"aaa": "xxx", "bbb": "yyy"}
    response = client.post(host, request_uri, params, header_auth=True)
    assert isinstance(response, dict)
    assert request_user_agent() == dummy_data.user_agent
    assert "aaa=xxx" in request_body()
    assert "bbb=yyy" in request_body()
    assert_basic_auth()

@responses.activate
def test_put(client, dummy_data):
    stub(responses.PUT, "https://api.nexmo.com/v1/applications")
    host = "api.nexmo.com"
    request_uri = "/v1/applications"
    params = {"aaa": "xxx", "bbb": "yyy"}
    response = client.put(host, request_uri, params=params)
    assert isinstance(response, dict)
    assert request_user_agent() == dummy_data.user_agent
    assert b"aaa" in request_body()
    assert b"xxx" in request_body()
    assert b"bbb" in request_body()
    assert b"yyy" in request_body()

@responses.activate
def test_put_with_auth(client, dummy_data):
    stub(responses.PUT, "https://api.nexmo.com/v1/applications")
    host = "api.nexmo.com"
    request_uri = "/v1/applications"
    params = {"aaa": "xxx", "bbb": "yyy"}
    response = client.put(host, request_uri, params=params, header_auth=True)
    assert_basic_auth()
    assert isinstance(response, dict)
    assert request_user_agent() == dummy_data.user_agent
    assert b"aaa" in request_body()
    assert b"xxx" in request_body()
    assert b"bbb" in request_body()
    assert b"yyy" in request_body()

@responses.activate
def test_delete(client, dummy_data):
    stub(responses.DELETE, "https://api.nexmo.com/v1/applications")
    host = "api.nexmo.com"
    request_uri = "/v1/applications"
    response = client.delete(host, request_uri)
    assert isinstance(response, dict)
    assert request_user_agent() == dummy_data.user_agent

@responses.activate
def test_delete_with_auth(client, dummy_data):
    stub(responses.DELETE, "https://api.nexmo.com/v1/applications")
    host = "api.nexmo.com"
    request_uri = "/v1/applications"
    response = client.delete(host, request_uri, header_auth=True)
    assert isinstance(response, dict)
    assert request_user_agent() == dummy_data.user_agent
    assert_basic_auth()