text:
"""
    SoftLayer.tests.managers.cdn_tests
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    :license: MIT, see LICENSE for more details.
"""
import math

from SoftLayer.managers import cdn
from SoftLayer import testing
from SoftLayer.testing import fixtures

class CDNTests(testing.TestCase):

    def set_up(self):
        self.cdn_client = cdn.CDNManager(self.client)

    def test_list_accounts(self):
        accounts = self.cdn_client.list_accounts()
        self.assertEqual(accounts, fixtures.SoftLayer_Account.getCdnAccounts)

    def test_get_account(self):
        account = self.cdn_client.get_account(12345)
        self.assertEqual(
            account,
            fixtures.SoftLayer_Network_ContentDelivery_Account.getObject)

    def test_get_origins(self):
        origins = self.cdn_client.get_origins(12345)
        self.assertEqual(
            origins,
            fixtures.SoftLayer_Network_ContentDelivery_Account.
            getOriginPullMappingInformation)

    def test_add_origin(self):
        self.cdn_client.add_origin(12345,
                                   'http',
                                   'http://localhost/',
                                   'self.local',
                                   False)

        args = ({
            'mediaType': 'http',
            'originUrl': 'http://localhost/',
            'cname': 'self.local',
            'isSecureContent': False
        },)
        self.assert_called_with('SoftLayer_Network_ContentDelivery_Account',
                                'createOriginPullMapping',
                                args=args,
                                identifier=12345)

    def test_remove_origin(self):
        self.cdn_client.remove_origin(12345, 12345)
        self.assert_called_with('SoftLayer_Network_ContentDelivery_Account',
                                'deleteOriginPullRule',
                                args=(12345,),
                                identifier=12345)

    def test_load_content(self):
        urls = ['http://a/img/0x001.png',
                'http://b/img/0x002.png',
                'http://c/img/0x004.png',
                'http://d/img/0x008.png',
                'http://e/img/0x010.png',
                'http://e/img/0x020.png']

        self.cdn_client.load_content(12345, urls)
        calls = self.calls('SoftLayer_Network_ContentDelivery_Account',
                           'loadContent')
        self.assertEqual(len(calls),
                         math.ceil(len(urls) / float(cdn.MAX_URLS_PER_LOAD)))

    def test_load_content_single(self):
        url = 'http://geocities.com/Area51/Meteor/12345/under_construction.gif'
        self.cdn_client.load_content(12345, url)

        self.assert_called_with('SoftLayer_Network_ContentDelivery_Account',
                                'loadContent',
                                args=([url],),
                                identifier=12345)

    def test_load_content_failure(self):
        urls = ['http://z/img/0x004.png',
                'http://y/img/0x002.png',
                'http://x/img/0x001.png']

        service = self.client['SoftLayer_Network_ContentDelivery_Account']
        service.loadContent.return_value = False

        self.cdn_client.load_content(12345, urls)
        calls = self.calls('SoftLayer_Network_ContentDelivery_Account',
                           'loadContent')
        self.assertEqual(len(calls),
                         math.ceil(len(urls) / float(cdn.MAX_URLS_PER_LOAD)))

    def test_purge_content(self):
        urls = ['http://z/img/0x020.png',
                'http://y/img/0x010.png',
                'http://x/img/0x008.png',
                'http://w/img/0x004.png',
                'http://v/img/0x002.png',
                'http://u/img/0x001.png']

        self.cdn_client.purge_content(12345, urls)
        calls = self.calls('SoftLayer_Network_ContentDelivery_Account',
                           'purgeContent')
        self.assertEqual(len(calls),
                         math.ceil(len(urls) / float(cdn.MAX_URLS_PER_PURGE)))

    def test_purge_content_failure(self):
        urls = ['http://z/img/0x004.png',
                'http://y/img/0x002.png',
                'http://x/img/0x001.png']

        mock = self.set_mock('SoftLayer_Network_ContentDelivery_Account',
                             'purgeContent')
        mock.return_value = False

        self.cdn_client.purge_content(12345, urls)
        calls = self.calls('SoftLayer_Network_ContentDelivery_Account',
                           'purgeContent')
        self.assertEqual(len(calls),
                         math.ceil(len(urls) / float(cdn.MAX_URLS_PER_PURGE)))

    def test_purge_content_single(self):
        url = 'http://geocities.com/Area51/Meteor/12345/under_construction.gif'

        self.cdn_client.purge_content(12345, url)
        self.assert_called_with('SoftLayer_Network_ContentDelivery_Account',
                                'purgeContent',
                                args=([url],),
                                identifier=12345)


text:
int main(int argc, char *argv[]){
    std::string outputDirectory;

    // set test parameters from command line
    bool unknownArgument = false;
    if (argc > 1) {
        for (int i = 1; i < argc - 1; i++) {
            if ((std::strcmp(argv[i], "--output-dir") == 0) || (std::strcmp(argv[i], "-o") == 0)) {
                outputDirectory = argv[++i];
            } else {
                unknownArgument = true;
            }
        }
    }
    if (outputDirectory.empty()) {
        std::cout << "No output directory supplied." << std::endl;
        unknownArgument = true;
    }
    if (unknownArgument) {
        std::cout << "Unknown arguments." << std::endl;
        std::cout << "Usage: " << argv[0] << " --output-dir|-o <output directory>" << std::endl;
        return 1;
    }
    std::cout << "Will place all output files in " << outputDirectory << std::endl;

    // setup loggers
    size_t q_size = 4096; //queue size must be power of 2
    spdlog::set_async_mode(q_size, spdlog::async_overflow_policy::block_retry, nullptr, std::chrono::seconds(2));
    spdlog::set_level(spdlog::level::debug);

    // create server listener threads
    std::vector<listener*> listeners;
    for (std::pair<std::string, long> test : testingParams::allTests) {
        auto logger = spdlog::basic_logger_mt(test.first, outputDirectory + "/" + test.first + ".log");
        listeners.push_back(new listener(test.first, outputDirectory, test.second, logger));
    }
    // create the logger and listener for the main server
    //auto mainServerLogger = spdlog::basic_logger_mt(testingParams::mainServer.first, outputDirectory + "/" +
    //        testingParams::mainServer.first + ".log");
    std::vector<spdlog::sink_ptr> sinks;
    sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_st>());
    std::string mainServerLogPath = outputDirectory + "/" + testingParams::mainServer.first + ".log";
    sinks.push_back(std::make_shared<spdlog::sinks::simple_file_sink_mt>(mainServerLogPath));
    auto mainServerLogger = std::make_shared<spdlog::logger>(testingParams::mainServer.first, begin(sinks), end(sinks));
    spdlog::register_logger(mainServerLogger);
    mainServerLogger->flush_on(spdlog::level::info);
    listeners.push_back(new listener(testingParams::mainServer.first, outputDirectory, testingParams::mainServer.second,
                                     mainServerLogger));

    // start listener threads
    std::thread listenerThreads[listeners.size()];
    for (int i = 0; i < listeners.size(); i++) {
        listenerThreads[i] = std::thread(&listener::runTask, listeners[i]);
    }
    mainServerLogger->info("Started listeners");

    // wait for all listeners to finish (actually never)
    for (int i = 0; i < listeners.size(); i++) {
        listenerThreads[i].join();
    }

    return 0;

}

redpajama_set_name: RedPajamaGithub


text:
![Build Status](https://github.com/pelargir/auto-session-timeout/actions/workflows/minitest.yml/badge.svg)

# Auto::Session::Timeout

Provides automatic session timeout in a Rails application. Very easy
to install and configure. Have you ever wanted to force your users
off your app if they go idle for a certain period of time? Many
online banking sites use this technique. If your app is used on any
kind of public computer system, this gem is a necessity.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'auto-session-timeout'
```

And then execute:

```
$ bundle
```

Or install it yourself as:

```
$ gem install auto-session-timeout
```

## Usage

After installing, tell your application controller to use auto timeout:

```ruby
class ApplicationController < ActionController::Base
  auto_session_timeout 1.hour
end
```

This will use a global timeout of 1 hour. The gem assumes your authentication
provider has a `#current_user` method that returns the currently logged in user.

If you want to specify a  custom timeout value per user, don't pass a value to
the controller as shown above. Instead,  override `#auto_timeout` in your
`#current_user` model. This is  typically the `User` class:

```ruby
class ApplicationController < ActionController::Base
  auto_session_timeout
end

class User < ActiveRecord::Base
  def auto_timeout
    15.minutes
  end
end
```

You will also need to insert a call to the `#auto_session_timeout_js`
helper method inside the body tags in your views. The easiest way to
do this is to insert it once inside your default or application-wide
layout. Make sure you are only rendering if the user is logged in,
otherwise the gem will attempt to force non-existent sessions to
timeout, wreaking havoc:

```erb
<body>
  <% if current_user %>
    <%= auto_session_timeout_js %>
  <% end %>
</body>
```

You need to setup two actions: one to return the session status and
another that runs when the session times out. You can use the default
actions included with the gem by inserting this line in your target
controller (most likely your user or session controller):

```ruby
class SessionsController < ApplicationController
  auto_session_timeout_actions
end
```

To customize the default actions, simply override them. You can call
the `#render_session_status` and `#render_session_timeout` methods to
use the default implementation from the gem, or you can define the
actions entirely with your own custom code:

```ruby
class SessionsController < ApplicationController
  def active
    render_session_status
  end

  def timeout
    render_session_timeout
  end
end
```

In any of these cases, make sure to properly map the actions in your
routes.rb file:

```ruby
get "active",  to: "sessions#active"
get "timeout", to: "sessions#timeout"
```

You're done! Enjoy watching your sessions automatically timeout.

## Using with Devise

When using Devise for authentication you will need to add a scoped
sessions controller and call the timeout actions helper there.
For example:

```ruby
class Users::SessionsController < Devise::SessionsController
  auto_session_timeout_actions
end
```

In your routes.rb file you will need to declare your scoped controller
and declare the timeout actions inside the same Devise scope:

```ruby
Rails.application.routes.draw do
  devise_for :users, controllers: { sessions: "users/sessions" }

  devise_scope :user do
    get "active", to: "users/sessions#active"
    get "timeout", to: "users/sessions#timeout"
  end
end
```

You can use Devise's `#user_signed_in?` method when you call the JS helper
method in your view:

```erb
<body>
  <% if user_signed_in? %>
    <%= auto_session_timeout_js %>
  <% end %>
</body>
```

## Optional Configuration

By default, the JavaScript code checks the server every 60 seconds for
active sessions. If you prefer that it check more frequently, pass a
frequency attribute to the helper method. The frequency is given in
seconds. The following example checks the server every 15 seconds:

```erb
<body>
  <% if current_user %>
    <%= auto_session_timeout_js frequency: 15 %>
  <% end %>
</body>
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Resources

* Repository: http://github.com/pelargir/auto-session-timeout/
* Blog: http://www.matthewbass.com
* Author: Matthew Bass


text:
namespace gyper
{
//----------------------------------- starts_with / ends_with ----------------------------
// TODO: this can be implemented much more generically and nicer with c++ ranges / c++20

inline bool starts_with(std::string_view input, std::string_view prefix)
{
  auto in_it = begin(input);
  auto in_end = end(input);

  auto pre_it = begin(prefix);
  auto pre_end = end(prefix);

  if (pre_end - pre_it > in_end - in_it)
    return false;

  while (in_it != in_end && pre_it != pre_end)
  {
    if (*in_it != *pre_it)
      return false;

    ++in_it;
    ++pre_it;
  }

  return true;
}

inline bool ends_with(std::string_view input, std::string_view prefix)
{
  auto in_it = rbegin(input);
  auto in_end = rend(input);

  auto pre_it = rbegin(prefix);
  auto pre_end = rend(prefix);

  if (pre_end - pre_it > in_end - in_it)
    return false;

  while (in_it != in_end && pre_it != pre_end)
  {
    if (*in_it != *pre_it)
      return false;

    ++in_it;
    ++pre_it;
  }

  return true;
}

//----------------------------------- split_on_delim ------------------------------------
// TODO replace with views in C++20

// cannot return views into temporary of string
inline std::vector<std::string_view> split_on_delim(std::string && input, char const delim) = delete;

inline std::vector<std::string_view> split_on_delim(std::string_view input, char const delim)
{
  std::vector<std::string_view> ret;

  for (size_t i = 0, s = 1; i <= input.size(); ++i, ++s)
  {
    if (i == input.size() || input[i] == delim)
    {
      //                begin_ptr                , size
      ret.emplace_back(input.data() + i - (s - 1), s - 1);
      s = 0;
    }
  }

  return ret;
}

//----------------------------------- stoll that works with string_view ------------------------
// TODO remove special case when removing support for GCC7

#if __has_include(<charconv>)
inline int64_t stoi64(std::string_view str)
{
  int64_t ret = 0;
  auto tmp = std::from_chars(str.data(), str.data() + str.size(), ret);

  if (tmp.ec != std::errc())
  {
    print_log(log_severity::error, "Converting \"", str, "\" of size ", str.size(), " to int failed.");
    std::exit(1);
  }

  return ret;
}
#else // GCC7
inline int64_t stoi64(std::string_view str)
{
  std::string tmp{str}; // needless copy to get null-terminated string
  return std::stoll(tmp);
}
#endif

// Returns an iterator to the nth occurence of an element (char). Expects n>=1.
template <typename Tit>
inline Tit find_nth_occurence(Tit begin, Tit end, char const element, int n)
{
  assert(n >= 1);
  int count{0};
  return std::find_if(begin, end, [&count, element, n](char x) { return x == element && ++count == n; });
}

} // namespace gyper


text:
import socket
from redis import Redis

import nexus

from nexus_redis import conf
from nexus_redis.helpers import get_net_loc

class RedisModule(nexus.NexusModule):
    home_url = 'index'
    name = 'redis'

    def get_caches(self):
        caches = {}
        for config in conf.CONNECTIONS:
            netloc = get_net_loc(config)
            if netloc in caches:
                continue
            try:
                caches[netloc] = Redis(
                    host=config.get('host'),
                    port=config.get('port'),
                    password=config.get('password'),
                    db=config.get('db'),
                    )
            except Exception, e:
                self.logger.exception(e)
        return caches

    def get_stats(self, timeout=5):
        default_timeout = socket.getdefaulttimeout()
        socket.setdefaulttimeout(timeout)

        results = {}
        for netloc, conn in self.get_caches().iteritems():
            try:
                stats = conn.info()
            except Exception, e:
                stats = {'online': 0}
            else:
                stats['online'] = 1
                stats['db_size'] = conn.dbsize()
            results[netloc] = stats

        socket.setdefaulttimeout(default_timeout)

        return results

    def get_title(self):
        return 'Redis'

    def get_urls(self):
        from django.conf.urls.defaults import patterns, url

        urlpatterns = patterns('',
            url(r'^$', self.as_view(self.index), name='index'),
            url(r'^by-server/$', self.as_view(self.by_server), name='by-server'),
        )

        return urlpatterns

    def render_on_dashboard(self, request):
        cache_stats = self.get_stats()

        global_stats = {
            'expired_keys': 0,
            'total_commands_processed': 0,
            'used_memory': 0,
            'connected_clients': 0,
            'connected_slaves': 0,
            'online': 0,
            'keyspace_misses': 0,
            'keyspace_hits': 0,
            'total': 0
        }

        for netloc, stats in cache_stats.iteritems():
            for k in global_stats.iterkeys():
                global_stats[k] += float(stats.get(k, 0))
            global_stats['keyspace_commands'] = global_stats['keyspace_hits'] + global_stats['keyspace_misses']
            global_stats['total'] += 1

        return self.render_to_string('nexus/redis/dashboard.html', {
            'global_stats': global_stats,
        })

    def index(self, request):
        return self.render_to_response("nexus/redis/index.html", {
            'cache_stats': self.get_stats(),
        }, request)

    def by_server(self, request):
        global_stats = {
            'expired_keys': 0,
            'total_commands_processed': 0,
            'used_memory': 0,
            'connected_clients': 0,
            'connected_slaves': 0,
            'keyspace_misses': 0,
            'keyspace_hits': 0,
            'online': 0,
            'total': 0,
        }
        server_stats = {}
        for netloc, stats in self.get_stats().iteritems():
            hostname = netloc.split(':', 1)[0]
            if hostname not in server_stats:
                server_stats[hostname] = global_stats.copy()
                server_stats[hostname]['servers'] = set()
                server_stats[hostname]['keyspace_commands'] = server_stats[hostname]['keyspace_hits'] + server_stats[hostname]['keyspace_misses']

            host_info = (netloc, stats['online'])

            if host_info in server_stats[hostname]['servers']:
                continue

            for k in global_stats.iterkeys():
                server_stats[hostname][k] += float(stats.get(k, 0))

            server_stats[hostname]['servers'].add(host_info)

            server_stats[hostname]['total'] = len(server_stats[hostname]['servers'])

        return self.render_to_response("nexus/redis/by_server.html", {
            'cache_stats': server_stats,
        }, request)

nexus.site.register(RedisModule, 'redis', category='cache')


text:
"use strict";

function isRestorable(obj) {
    return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon;
}

module.exports = isRestorable;


text:
@class WEPopoverController;

@interface fcOrderPriceBreakdownViewController : UIViewController

@property (nonatomic,weak) IBOutlet UITextView *mainText;
@property (nonatomic,weak) IBOutlet UIButton *doneBut;
@property (nonatomic,strong) WEPopoverController *WEcontroller;
@property (nonatomic,strong) NSDecimalNumber *orderTotal;
@property (nonatomic,strong) NSDecimalNumber *orderItemsTotal;
@property (nonatomic,strong) NSDecimalNumber *orderDiscount;
@property (nonatomic,strong) NSDecimalNumber *orderTip;
@property (nonatomic,strong) NSDecimalNumber *orderTax;
@property (nonatomic,strong) NSDecimalNumber *orderTaxableAmount;
@property (nonatomic,strong) NSDecimalNumber *orderConvenienceFee;
@property (nonatomic,assign) BOOL orderTaxable;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
-(IBAction) doDone:(id)sender;

@end


text:
@testset "execute" begin
    execute(`ls -al`, TEST_CONFIG, "myproject")
    execute(`julia -v`, TEST_CONFIG, join(TEST_TMP_DIR, "test-playground"))
end


text:
(function (root, cls) {
   if(typeof module !== 'undefined' && module.exports) {
      module.exports = cls();
   } else if (typeof define === 'function' && define.amd) {
      define(cls);
   } else {
      root.Pledge = cls();
   }
}(this, function() {

   "use strict";

   function bindScope(fn, scope) {
      if (Function.prototype.bind) {
         return fn.bind(scope);
      } else {
         return function() {
            return fn.apply(scope, arguments);
         };
      }
   }

   /**
    * @class Pledge
    * @constructor
    *
    * @param {Function} resolver
    */
   function Pledge(resolver) {
      if(!Pledge.isPledge(this)) {
         return new Pledge(resolver);
      }

      var boundResolve = bindScope(this._resolve, this),
         boundReject = bindScope(this._reject, this);

      this._state = Pledge.PENDING;
      this._purgeHandlers();

      if (typeof resolver === 'function') {
        try {
           resolver(boundResolve, boundReject);
        } catch (err) {
           this._reject(err);
        }
      } else {
         throw new Error('Pledge constructor takes a function argument.');
      }
   }

   /**
    * @type {Function[]}
    */
   Pledge.prototype._onFulfilled = null;

   /**
    * @type {Function[]}
    */
   Pledge.prototype._onRejected = null;

   /**
    * @type {String}
    */
   Pledge.prototype._state = null;

   /**
    * @type {Object}
    */
   Pledge.prototype._result = null;

   /**
    * Proxies external Pledges returned as values in callbacks to the resolve/reject handlers.
    *
    * @param {Pledge} externalPledge
    */
   Pledge.prototype._resolveExternalPledge = function(externalPledge) {
      externalPledge.then(bindScope(this._resolve, this), bindScope(this._reject, this));
   };

   /**
    * Function that will be passed to the resolver method supplied by the user to allow them to resolve the Pledge.
    *
    * @param {Object} value
    */
   Pledge.prototype._resolve = function(value) {
      var chainedValue;
      try {
         this._state = Pledge.RESOLVED;
         this._result = value;

         for (var i = 0, l = this._onFulfilled.length; i < l; i++) {
            chainedValue = this._onFulfilled[i](value);

            if (Pledge.isPledge(value)) {
               this._resolveExternalPledge(value);

               return this._onFulfilled = this._onFulfilled.slice(i);
            } else if(typeof chainedValue !== 'undefined') {
               this._result = value = chainedValue;
            }
         }
      } catch (err) {
         this._reject(err);
      }

      this._purgeHandlers();
   };

   /**
    * Function that will be passed to the resolver method supplied by the user to allow them to reject the Pledge.
    *
    * @param {Object} value
    */
   Pledge.prototype._reject = function(value) {
      var chainedValue;
      this._state = Pledge.REJECTED;
      this._result = value;

      for (var i = 0, l = this._onRejected.length; i < l; i++) {
         chainedValue = this._onRejected[i](value);

         if (Pledge.isPledge(value)) {
            this._resolveExternalPledge(value);

            return this._onRejected = this._onRejected.slice(i);
         } else if(typeof chainedValue !== 'undefined') {
            this._result = value = chainedValue;
         }
      }

      this._purgeHandlers();
   };

   /**
    * Clean handlers after Pledge has resolves/rejected.
    */
   Pledge.prototype._purgeHandlers = function() {
      this._onFulfilled = [];
      this._onRejected = [];
   };

   /**
    * Method to allow pledge resolution to be handled; both arugments are optional, but the first will allow a success and the second a failure handler.
    * The handlers will be invoked if the appropriate function is run in the resolve mehod supplied in the pledge constructor.
    *
    * @method then
    * @chainable
    * @param {Function} [onFulfilled]
    * @param {Function} [onRejected]
    * @return {Pledge}
    */
   Pledge.prototype.then = function(onFulfilled, onRejected) {
      if (typeof onFulfilled === 'function') {
         this._onFulfilled.push(onFulfilled);
      }

      if (typeof onRejected === 'function') {
         this._onRejected.push(onRejected);
      }

      if (this._state === Pledge.RESOLVED) {
         this._resolve(this._result);
      }

      if (this._state === Pledge.REJECTED) {
         this._reject(this._result);
      }

      return this;
   };

   /**
    * Shortcut method to save passing null as first argument of "then". It will add a new rejection handler.
    *
    * @method catch
    * @chainable
    * @param {Function} [onRejected]
    * @return {Pledge}
    */
   Pledge.prototype.catch = function(onRejected) {
      if (typeof onRejected === 'function') {
         this._onRejected.push(onRejected);
      }

      if (this._state === Pledge.REJECTED) {
         this._reject(this._result);
      }

      return this;
   };

   /**
    * Utility to get Pledge state.
    *
    * @method getState
    * @return {String}
    */
   Pledge.prototype.getState = function() {
      return this._state;
   };

   /**
    * Utility to get Pledge result.
    *
    * @method getResult
    * @return {Object}
    */
   Pledge.prototype.getResult = function() {
      return this._result;
   };

   /**
    * Static method that returns a resolved Pledge.
    *
    * @method reject
    * @static
    * @param {Object} value
    * @return {Pledge}
    */
   Pledge.resolve = function(value) {
      return new Pledge(function(resolve, reject) {
         resolve(value);
      });
   };

   /**
    * Static method that returns a rejected Pledge.
    *
    * @method reject
    * @static
    * @param {Object} value
    * @return {Pledge}
    */
   Pledge.reject = function(value) {
      return new Pledge(function(resolve, reject) {
         reject(value);
      });
   };

   /**
    * Static method that takes an Array of Pledges/Objects and returns a new Pledge that resolves only when
    * all the pledges in the given Array have resolved. The resolve handler will recieve an Array of all results
    * in the same order as the original Pledge Array. If any fail returned Pledge will fail and pass the value of the failed Pledge.
    *
    * @method all
    * @static
    * @param {Pledge[]|Object[]} pledgeArr
    * @return {Pledge}
    */
   Pledge.all = function(pledgeArr) {
      pledgeArr = [].concat(pledgeArr);

      var pledge = new Pledge(function(resolve, reject) {
         var fulFilledArguments = [];
         var state = Pledge.PENDING;
         var pledgeArrClone = pledgeArr.slice();

         for (var i = 0, l = pledgeArrClone.length; i < l; i++) {
            if (!Pledge.isPledge(pledgeArrClone[i])) {
               pledgeArrClone[i] = Pledge.resolve(pledgeArrClone[i]);
            }

            pledgeArrClone[i].then(function(i) {
               return function(value) {
                  if (state !== Pledge.REJECTED) {
                     fulFilledArguments[i] = value;
                     if (fulFilledArguments.length === l) {
                        resolve(fulFilledArguments);
                        state = Pledge.RESOLVED;
                     }
                  }
               };
            }(i), function(value) {
               reject(value);
               state = Pledge.REJECTED;
            });
         }
      });

      return pledge;
   };

   /**
    * Static method that takes an Array of Pledges/Objects and returns a new Pledge that resolves or rejects as soon as the first
    * Pledge in the supplied Array resolves or rejects.
    *
    * @method race
    * @static
    * @param {Pledge[]|Object[]} pledgeArr
    * @return {Pledge}
    */
   Pledge.race = function(pledgeArr) {
      pledgeArr = [].concat(pledgeArr);

      var pledgeArrClone = pledgeArr.slice();
      var pledge = new Pledge(function(resolve, reject) {
         var state = Pledge.PENDING;

         for (var i = 0, l = pledgeArrClone.length; i < l; i++) {
            if (!Pledge.isPledge(pledgeArrClone[i])) {
               pledgeArrClone[i] = Pledge.resolve(pledgeArrClone[i]);
             }

            pledgeArrClone[i].then(function(value) {
               if (state === Pledge.PENDING) {
                  resolve(value);
                  state = Pledge.RESOLVED;
               }
            }, function(value) {
               if (state === Pledge.PENDING) {
                  reject(value);
                  state = Pledge.REJECTED;
               }
            });
         }
      });

      return pledge;
   };

   /**
    * Static method for checking whether given argument is an instance of Pledge.
    *
    * @method isPledge
    * @static
    * @param {Pledge|Object} check
    * @return {Boolean}
    */
   Pledge.isPledge = function(check) {
      return check && check instanceof Pledge;
   };

   /**
    * @static
    * @type {String}
    */
   Pledge.PENDING = 'pending';

   /**
    * @static
    * @type {String}
    */
   Pledge.REJECTED = 'rejected';

   /**
    * @static
    * @type {String}
    */
   Pledge.RESOLVED = 'resolved';

   return Pledge;
}));


text:
package org.kie.workbench.common.forms.fields.shared.fieldTypes.basic.slider.definition;

import org.kie.workbench.common.forms.fields.shared.AbstractFieldDefinition;
import org.kie.workbench.common.forms.fields.shared.fieldTypes.basic.slider.type.SliderFieldType;

public abstract class SliderBaseDefinition<T extends Number> extends AbstractFieldDefinition {

    public static final SliderFieldType FIELD_TYPE = new SliderFieldType();

    public SliderBaseDefinition(String className) {
        super(className);
    }

    @Override
    public SliderFieldType getFieldType() {
        return FIELD_TYPE;
    }

    public abstract T getMin();

    public abstract void setMin(T min);

    public abstract T getMax();

    public abstract void setMax(T max);

    public abstract T getPrecision();

    public abstract void setPrecision(T precision);

    public abstract T getStep();

    public abstract void setStep(T step);
}


text:
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { Observable } from 'rxjs/rx';
import { AuthenticationService } from './authentication.service';

@Injectable()
export class AuthenticationGuard implements CanActivate {
	constructor(private router: Router, private authenticationService: AuthenticationService) {
	}

	public canActivate(): boolean | Observable<boolean> {
		if (this.authenticationService.isLoggedIn) {
			return true;
		}

		this.router.navigate(['/login']);
		return false;
	}
}


text:
package com.koatee.conjugator.french.models;

import java.util.HashMap;
import java.util.Map;

import com.koatee.conjugator.Person;
import com.koatee.conjugator.Tense;
import com.koatee.conjugator.french.RegularVerb;

public class Parler extends RegularVerb{

	public Parler(String infinitive) {
		super();

		this.suffixes = new HashMap<Tense, Map<Person, String>>();

		HashMap<Person, String> presentSufixes = new HashMap<Person, String>();
		presentSufixes.put(Person.FIRST_SINGULAR, "e");
		presentSufixes.put(Person.SECOND_SINGULAR, "es");
		presentSufixes.put(Person.THIRD_SINGULAR, "e");
		presentSufixes.put(Person.FIRST_PLURAL, "ons");
		presentSufixes.put(Person.SECOND_PLURAL, "ez");
		presentSufixes.put(Person.THIRD_PLURAL, "ent");
		this.suffixes.put(Tense.PRESENT_INDICATIVE, presentSufixes);

		HashMap<Person, String> imperfectSufixes = new HashMap<Person, String>();
		imperfectSufixes.put(Person.FIRST_SINGULAR, "ais");
		imperfectSufixes.put(Person.SECOND_SINGULAR, "ais");
		imperfectSufixes.put(Person.THIRD_SINGULAR, "ait");
		imperfectSufixes.put(Person.FIRST_PLURAL, "ions");
		imperfectSufixes.put(Person.SECOND_PLURAL, "iez");
		imperfectSufixes.put(Person.THIRD_PLURAL, "aient");
		this.suffixes.put(Tense.PAST_IMPERFECT, imperfectSufixes);

		HashMap<Person, String> futureSufixes = new HashMap<Person, String>();
		futureSufixes.put(Person.FIRST_SINGULAR, "erai");
		futureSufixes.put(Person.SECOND_SINGULAR, "eras");
		futureSufixes.put(Person.THIRD_SINGULAR, "era");
		futureSufixes.put(Person.FIRST_PLURAL, "erons");
		futureSufixes.put(Person.SECOND_PLURAL, "erez");
		futureSufixes.put(Person.THIRD_PLURAL, "eront");
		this.suffixes.put(Tense.FUTURE, futureSufixes);

		HashMap<Person, String> pastParticipleSufix = new HashMap<Person, String>();
		pastParticipleSufix.put(Person.IMPERSONAL, "é");
		this.suffixes.put(Tense.PAST_PARTICIPLE, pastParticipleSufix);

		setInfinitive(infinitive);
	}

	public Parler(){
		this("Parler");
	}

}


text:
=pod

=head1 NAME

RSA_set_default_method, RSA_get_default_method, RSA_set_method,
RSA_get_method, RSA_PKCS1_OpenSSL, RSA_null_method, RSA_flags,
RSA_new_method - select RSA method

=head1 SYNOPSIS

 #include <openssl/rsa.h>

 void RSA_set_default_method(const RSA_METHOD *meth);

 RSA_METHOD *RSA_get_default_method(void);

 int RSA_set_method(RSA *rsa, const RSA_METHOD *meth);

 RSA_METHOD *RSA_get_method(const RSA *rsa);

 RSA_METHOD *RSA_PKCS1_OpenSSL(void);

 RSA_METHOD *RSA_null_method(void);

 int RSA_flags(const RSA *rsa);

 RSA *RSA_new_method(ENGINE *engine);

=head1 DESCRIPTION

An B<RSA_METHOD> specifies the functions that OpenSSL uses for RSA
operations. By modifying the method, alternative implementations such as
hardware accelerators may be used. IMPORTANT: See the NOTES section for
important information about how these RSA API functions are affected by the
use of B<ENGINE> API calls.

Initially, the default RSA_METHOD is the OpenSSL internal implementation,
as returned by RSA_PKCS1_OpenSSL().

RSA_set_default_method() makes B<meth> the default method for all RSA
structures created later. B<NB>: This is true only whilst no ENGINE has
been set as a default for RSA, so this function is no longer recommended.

RSA_get_default_method() returns a pointer to the current default
RSA_METHOD. However, the meaningfulness of this result is dependent on
whether the ENGINE API is being used, so this function is no longer
recommended.

RSA_set_method() selects B<meth> to perform all operations using the key
B<rsa>. This will replace the RSA_METHOD used by the RSA key and if the
previous method was supplied by an ENGINE, the handle to that ENGINE will
be released during the change. It is possible to have RSA keys that only
work with certain RSA_METHOD implementations (eg. from an ENGINE module
that supports embedded hardware-protected keys), and in such cases
attempting to change the RSA_METHOD for the key can have unexpected
results.

RSA_get_method() returns a pointer to the RSA_METHOD being used by B<rsa>.
This method may or may not be supplied by an ENGINE implementation, but if
it is, the return value can only be guaranteed to be valid as long as the
RSA key itself is valid and does not have its implementation changed by
RSA_set_method().

RSA_flags() returns the B<flags> that are set for B<rsa>'s current
RSA_METHOD. See the BUGS section.

RSA_new_method() allocates and initializes an RSA structure so that
B<engine> will be used for the RSA operations. If B<engine> is NULL, the
default ENGINE for RSA operations is used, and if no default ENGINE is set,
the RSA_METHOD controlled by RSA_set_default_method() is used.

RSA_flags() returns the B<flags> that are set for B<rsa>'s current method.

RSA_new_method() allocates and initializes an B<RSA> structure so that
B<method> will be used for the RSA operations. If B<method> is B<NULL>,
the default method is used.

=head1 THE RSA_METHOD STRUCTURE

 typedef struct rsa_meth_st
 {
     /* name of the implementation */
        const char *name;

     /* encrypt */
        int (*rsa_pub_enc)(int flen, unsigned char *from,
          unsigned char *to, RSA *rsa, int padding);

     /* verify arbitrary data */
        int (*rsa_pub_dec)(int flen, unsigned char *from,
          unsigned char *to, RSA *rsa, int padding);

     /* sign arbitrary data */
        int (*rsa_priv_enc)(int flen, unsigned char *from,
          unsigned char *to, RSA *rsa, int padding);

     /* decrypt */
        int (*rsa_priv_dec)(int flen, unsigned char *from,
          unsigned char *to, RSA *rsa, int padding);

     /* compute r0 = r0 ^ I mod rsa->n (May be NULL for some
                                        implementations) */
        int (*rsa_mod_exp)(BIGNUM *r0, BIGNUM *I, RSA *rsa);

     /* compute r = a ^ p mod m (May be NULL for some implementations) */
        int (*bn_mod_exp)(BIGNUM *r, BIGNUM *a, const BIGNUM *p,
          const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);

     /* called at RSA_new */
        int (*init)(RSA *rsa);

     /* called at RSA_free */
        int (*finish)(RSA *rsa);

     /* RSA_FLAG_EXT_PKEY        - rsa_mod_exp is called for private key
      *                            operations, even if p,q,dmp1,dmq1,iqmp
      *                            are NULL
      * RSA_METHOD_FLAG_NO_CHECK - don't check pub/private match
      */
        int flags;

        char *app_data; /* ?? */

        int (*rsa_sign)(int type,
                const unsigned char *m, unsigned int m_length,
                unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
        int (*rsa_verify)(int dtype,
                const unsigned char *m, unsigned int m_length,
                const unsigned char *sigbuf, unsigned int siglen,
                                                                const RSA *rsa);
     /* keygen. If NULL builtin RSA key generation will be used */
        int (*rsa_keygen)(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb);

 } RSA_METHOD;

=head1 RETURN VALUES

RSA_PKCS1_OpenSSL(), RSA_PKCS1_null_method(), RSA_get_default_method()
and RSA_get_method() return pointers to the respective RSA_METHODs.

RSA_set_default_method() returns no value.

RSA_set_method() returns a pointer to the old RSA_METHOD implementation
that was replaced. However, this return value should probably be ignored
because if it was supplied by an ENGINE, the pointer could be invalidated
at any time if the ENGINE is unloaded (in fact it could be unloaded as a
result of the RSA_set_method() function releasing its handle to the
ENGINE). For this reason, the return type may be replaced with a B<void>
declaration in a future release.

RSA_new_method() returns NULL and sets an error code that can be obtained
by L<ERR_get_error(3)> if the allocation fails. Otherwise
it returns a pointer to the newly allocated structure.

=head1 BUGS

The behaviour of RSA_flags() is a mis-feature that is left as-is for now
to avoid creating compatibility problems. RSA functionality, such as the
encryption functions, are controlled by the B<flags> value in the RSA key
itself, not by the B<flags> value in the RSA_METHOD attached to the RSA key
(which is what this function returns). If the flags element of an RSA key
is changed, the changes will be honoured by RSA functionality but will not
be reflected in the return value of the RSA_flags() function - in effect
RSA_flags() behaves more like an RSA_default_flags() function (which does
not currently exist).

=head1 SEE ALSO

L<RSA_new(3)>

=head1 COPYRIGHT

Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.

Licensed under the OpenSSL license (the "License").  You may not use
this file except in compliance with the License.  You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.

=cut


text:
#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using KUtils;
using UnityEditor;

namespace KFrameWork
{
    public class EditorRef : IBundleRef
    {
        public UnityEngine.Object MainObject { get; private set; }

        private string _name;

        public string name
        {
            get
            {
                return this._name;
            }
        }

        public string LoadName
        {
            get
            {
                return this._name;
            }
        }

        public int DependCount
        {
            get
            {
                return 1;
            }
        }

        public int InstanceRefCount
        {
            get
            {
                return 1;
            }
        }

        public bool SupportAsync
        {
            get
            {
                return false;
            }
        }

        public int SelfRefCount
        {
            get
            {
                return 0;
            }
        }

        public string filename { get; private set; }

        private string _editorpath;

        public EditorRef(UnityEngine.Object o,string bundlename,string name,string editorpath)
        {
            this.MainObject = o;
            this._name = name;
            this.filename = name;
            this._editorpath = editorpath;
        }

        public void NeedThis(IBundleRef dep)
        {

        }

        public void LogDepends()
        {

        }

        public bool Instantiate(out UnityEngine.Object target, Component c = null)
        {
            if (MainObject == null)
            {
                target = null;
                return false;
            }

            if (MainObject is GameObject)
            {
                target = GameObject.Instantiate(MainObject);
            }
            else
            {
                target = MainObject;
            }
            return true;
        }

        public bool LoadAsset(out UnityEngine.Object target)
        {
            target = this.MainObject;
            return true;
        }

        public bool LoadAsset(string abname, out UnityEngine.Object target)
        {
            target = this.MainObject;
            return true;
        }

        public AssetBundleRequest LoadAssetAsync()
        {
            return null;
        }

        public void Lock(LockType tp = LockType.END)
        {

        }

        public void UnLoad(bool all)
        {

        }

        public void UnLock(LockType tp = LockType.END)
        {

        }

        public UnityEngine.Object InstantiateWithBundle(UnityEngine.Object prefab, Component c = null)
        {
            if (prefab is GameObject)
            {
                return GameObject.Instantiate(prefab);
            }
            else
                return prefab;
        }

        public UnityEngine.Object SimpleInstantiate()
        {
            UnityEngine.Object o;
            this.Instantiate(out o);
            return o;
        }

        public void Retain()
        {

        }

        public void Retain(UnityEngine.Object o)
        {

        }

        public void Release()
        {

        }

        public string[] GetAllAssetNames()
        {
            return null;
        }

        public void Release(UnityEngine.Object o)
        {

        }

        public bool LoadAllAssets(out UnityEngine.Object[] target)
        {
            target = AssetDatabase.LoadAllAssetsAtPath(this._editorpath);
            return true;
        }
    }
}
#endif


text:
package com.novartis.pcs.ontology.service.mapper;

import javax.ejb.Local;

@Local
public interface ControlledVocabularyAutoMapperLocal {

	public void execute(boolean sendNotifcation);

}


text:
require 'parser/ruby18'
require 'parser/ruby19'
require 'parser/ruby20'
require 'parser/ruby21'


text:
/*
 * $Id: AttributeComboImpl.java,v 1.3 2007/03/12 10:40:53 agoubard Exp $
 */
package com.mycompany.allinone.api;

import com.mycompany.allinone.api.AttributeCombo.Request.Person;
import java.util.Calendar;
import java.util.Iterator;
import org.xins.common.types.standard.Date;

/**
 * Implementation of the AttributeCombo function.
 *
 *
Description: A function to test the attribute-combo.
 *
 * @version $Revision: 1.3 $ $Date: 2007/03/12 10:40:53 $
 * @author John Doe (john.doe@mycompany.com)
 */
public final class AttributeComboImpl extends AttributeCombo {

   /**
    * Constructs a new AttributeComboImpl instance.
    *
    * @param api
    *    the API to which this function belongs, guaranteed to be not
    *    null.
    */
   public AttributeComboImpl(APIImpl api) {
      super(api);
   }

   /**
    * Calls this function. If the function fails, it may throw any kind of
    * exception. All exceptions will be handled by the caller.
    *
    * @param request
    *    the request, never null.
    *
    * @return
    *    the result of the function call, should never be null.
    *
    * @throws Throwable
    *    if anything went wrong.
    */
   public Result call(Request request) throws Throwable {
      Calendar calendar = Calendar.getInstance();
      SuccessfulResult result = new SuccessfulResult();
      Iterator itPersons = request.listPerson().iterator();
      while (itPersons.hasNext()) {
         Person nextPerson = (Person)itPersons.next();
         Registration registration = new Registration();
         if (nextPerson.isSetAge()) {
            int age = nextPerson.getAge().intValue();
            registration.setRegistrationYear(calendar.get(Calendar.YEAR) - age + 1);
            registration.setRegistrationMonth(calendar.get(Calendar.MONTH));
         } else {
            int year;
            int month;
            int day;
            if (nextPerson.isSetBirthDate()) {
               year = nextPerson.getBirthDate().getYear();
               month = nextPerson.getBirthDate().getMonthOfYear();
               day = nextPerson.getBirthDate().getDayOfMonth();
            } else {
               year = nextPerson.getBirthYear().intValue();
               month = nextPerson.getBirthMonth().intValue();
               day = nextPerson.getBirthDay().intValue();
            }

            // Create an invalid response for year above 2006
            // This is only for demonstration purpose as no API should normally
            // return an invalid response.
            if (year <= 2006) {
               registration.setRegistrationDate(new Date.Value(year + 1, month, 1));
            }
         }
         result.addRegistration(registration);
      }
      return result;
   }
}


text:
const unsigned int FLIPPED_HORIZONTALLY_FLAG    = 0x80000000;
const unsigned int FLIPPED_VERTICALLY_FLAG      = 0x40000000;
const unsigned int FLIPPED_DIAGONALLY_FLAG      = 0x20000000;

using namespace uth;
using namespace TMX;

TileLayer::TileLayer(tinyxml2::XMLElement* layerElement, Map* map)
{
	for(auto it = map->tilesets.begin(); it != map->tilesets.end(); ++it)
	{
		Texture* t = (*it)->GetTexture();

		if(m_spriteBatches.find(t) == m_spriteBatches.end())
		{
            auto s = new SpriteBatch(false);
			s->SetTexture(t);
			m_spriteBatches[t] = s;
		}
	}

	parseElement(layerElement, map);
}

TileLayer::~TileLayer()
{
	//for(auto it = m_tiles.begin(); it != m_tiles.end(); ++it)
	//	delete (*it);

	for(auto it = m_spriteBatches.begin(); it != m_spriteBatches.end(); ++it)
		delete (*it).second;
}

// Public

void TileLayer::Draw(RenderTarget& target)
{
    if (!m_active)
        return;

	for(auto it = m_spriteBatches.begin(); it != m_spriteBatches.end(); ++it)
		(*it).second->Draw(target);
}

unsigned int TileLayer::GetHeight()
{
	return m_height;
}

unsigned int TileLayer::GetWidth()
{
	return m_width;
}

const std::string& TileLayer::GetName()
{
	return m_name;
}

std::string TileLayer::GetProperty(const std::string& name)
{
	auto result = m_properties.find(name);
	if(result != m_properties.end())
		return result->second;

	return std::string();
}

Tile* TileLayer::GetTile(const int x, const int y)
{
	for(auto it = m_tiles.begin(); it != m_tiles.end(); ++it)
	{
		auto tile = (*it);
		if(tile->tileRectangle.position.x == x && tile->tileRectangle.position.y == y)
			return tile;
	}

	return nullptr;
}

// Private

void TileLayer::parseElement(tinyxml2::XMLElement* layerElement, Map* map)
{
	// Get properties
	auto properties = layerElement->FirstChildElement("properties");
	if(properties != 0)
		parseProperties(properties);

	m_name = layerElement->Attribute("name");
	m_width = layerElement->UnsignedAttribute("width");
	m_height = layerElement->UnsignedAttribute("height");
    if (layerElement->Attribute("visible") != 0)
    {
        m_active = layerElement->IntAttribute("visible") == 0 ? false : true;
    }
    else
        m_active = true;

	// Parse data
	unsigned int x = 0;
	unsigned int y = 0;
	auto tile = layerElement->FirstChildElement("data")->FirstChildElement("tile");
	while(tile != 0)
	{
		unsigned int gid = tile->UnsignedAttribute("gid");

        // Go to the next "line"
        if (x >= map->GetWidth())
        {
            x = 0;
            y++;
        }

        // Tile is "empty space"
        if (gid == 0)
        {
            x++;
            tile = tile->NextSiblingElement("tile");
            continue;
        }

		// Read out the flags
		bool flipped_horizontally = (gid & FLIPPED_HORIZONTALLY_FLAG) != 0;
		bool flipped_vertically = (gid & FLIPPED_VERTICALLY_FLAG) != 0;
        // TODO: implement this
		//bool flipped_diagonally = (gid & FLIPPED_DIAGONALLY_FLAG) != 0;

		// Clear the flags
		gid &= ~(FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG
			| FLIPPED_DIAGONALLY_FLAG);

		// Find correct tileset
		for(int i = map->tilesets.size() - 1; i >= 0; --i)
		{
			Tileset* tileset = map->tilesets[i].get();

            if (tileset->GetFirstGID() <= gid)
            {
                const pmath::Rect t(static_cast<float>(x * tileset->GetTileWidth()), static_cast<float>(y * tileset->GetTileHeight()),
                    static_cast<float>(tileset->GetTileWidth()), static_cast<float>(tileset->GetTileHeight()));

                auto tile = new Tile(t);

                // NOTE: do diagonal before these
                if (flipped_horizontally)
                    tile->transform.SetScale(-1, tile->transform.GetScale().y);
                if (flipped_vertically)
                    tile->transform.SetScale(tile->transform.GetScale().x, -1);

				map->AddChild(tile);
                const pmath::Rect texCoords = tileset->GetTile(gid - tileset->GetFirstGID());

                m_tiles.push_back(tile);
                m_spriteBatches.at(tileset->GetTexture())->AddSprite(&tile->transform, "", pmath::Vec4(1, 1, 1, 1), texCoords);
                x++;
                break;
            }
		}
		tile = tile->NextSiblingElement("tile");
	}
}

void TileLayer::parseProperties(tinyxml2::XMLElement* propertiesElement)
{
	auto p = propertiesElement->FirstChildElement("property");
	while(p != 0)
	{
		std::pair<std::string, std::string> tmp;
		tmp.first = p->Attribute("name");
		tmp.second = p->Attribute("value");

		m_properties.insert(tmp);

		p = p->NextSiblingElement("property");
	}
}


text:
Let's start with two objects, **A** and **B**. We'll put a data-property and method on each.

    const A = {
      label: 'A',
      sayA(){return `A: I'm from ${this.label}`}
    }

    const B = {
      label: 'B',
      sayB(){return `B: I'm from ${this.label}`}
    }

    ...

Then let's initialize the mxObject by calling the mxObject factory function and immediately mix-in **A**

	...

	const mxObj = mxObject().mixin(A)

	// mxObj still doesn't have any of its own properties
	console.log(Object.getOwnPropertyNames(mxObj)) // returns []

	// yet it can access properties on A as if it A were in its prototype chain
	console.log(mxObj.label)    // 'A'
	console.log(mxObj.sayA())   // 'A: I'm from A'

	// and we can check to see if A is a mixin of mxObj(this is like
	// Object.prototype.isPrototypeOf())
	console.log(mxObj.isMixinOf(A))  // true

	...

If we want to later include behavior from **B**, we can simply mix-in **B**'s behavior as well

	...

	mxObj.mixin(B)

	// mxObj still doesn't have any of its own properties
	console.log(Object.getOwnPropertyNames(mxObj)) // returns []

	// yet it can access properties from both B and A as if both A and B were
	// prototypes. Since mxObj inherits 'label' from both A and B, those mixins
	// collide on the 'label' property. Since A was mixed-in first, A.label
	// takes priority over B.label.
	console.log(mxObj.label)    // returns 'A'
	console.log(mxObj.sayA())   // returns 'A: I'm from A'
	console.log(mxObj.sayB())   // returns 'B: I'm from A'

	// nevertheless, mxObject still "knows" that B.label exists
	console.log(mxObj.getAll('label'))  // returns ['A', 'B']

	...

Like prototypes, mixins are a form of "live" inheritance

	...

	// A change on a mixin is "seen" from all mxObjects that have mixed it in
	A.label = 'AA'
	console.log(mxObj.label)  // returns 'AA'

	...

And don't forget, not all Bears are Wizards and not all Wizards are Bears!

	...

	// A does NOT inherit from B
	// B does NOT inherit from A

	// ERROR: A.sayB is not a function [it's undefined]
	try{ A.sayB() } catch(err){ console.log(err.message) }

	// ERROR: B.sayA is not a function [it's undefined]
	try{ B.sayA() } catch(err){ console.log(err.message) }

	...

### A Basic Example | *Extensions*

###### *NOTE: even though this example purely uses extensions, a single mxObject can both mix and extend. For example, `mxObject().mixin(A).extend(C).mixin(B).extend(D)` mixes in both A and B, and it extends from both C and D*

  Let's start with two objects, **C** and **D**. We'll put a data-property and method on each.

      const C = {
        label: 'C',
        sayC(){return `C: I'm from ${this.label}`}
      }

      const D = {
        label: 'D',
        sayD(){return `D: I'm from ${this.label}`}
      }

      ...

  Then let's initialize the mxObject by calling the mxObject factory function and immediately extend from **C**

  	...

  	const mxObj = mxObject().extend(C)

  	// mxObj now has its own 'label' property and its own 'sayC()' property
  	console.log(Object.getOwnPropertyNames(mxObj)) // returns ['label', 'sayC']

  	// when it accesses its own properties (or at least the ones extended from C),
  	// it behaves virtually identically to C
  	console.log(mxObj.label)    // 'C'
  	console.log(mxObj.sayC())   // 'C: I'm from C'

  	// and we can check to see if mxObj is an extension of C
  	//   (this is like the instanceof keyword)
  	console.log(mxObj.isExtensionOf(C))  // true

  	...

  If we want to later include behavior from **D**, we can simply extend from **D**'s behavior as well

  	...

  	mxObj.extend(D)

  	// mxObj now has an additional property 'sayD()'
  	console.log(Object.getOwnPropertyNames(mxObj)) // returns ['label', 'sayC', 'sayD']

  	// and 'label' has been overwritten
  	console.log(mxObj.label)    // returns 'D'
  	console.log(mxObj.sayC())   // returns 'C: I'm from D'
  	console.log(mxObj.sayD())   // returns 'D: I'm from D'

  	...

  Like non-static properties of class instances, extended properties are NOT "live".

  	// mxObject properties that have been extended do not "see" changes to the
  	// original object
  	D.label = 'DD'
  	console.log(mxObj.label)  // returns 'D'


text:
echo "Starting test..."

workingDir=tmp
mkdir -p $workingDir
rm -f $workingDir/*

skeletonSentences=testData/skeletonSentences.detritus.txt
wordlist=testData/wordlist.unicode.txt
detritusWordlist=testData/wordlist.ascii.txt

goldXML=$workingDir/gold.xml
goldDetritus=$workingDir/gold.goldDetritus.txt

processedDetritus=$workingDir/processedDetritus.txt
missingDetritus=$workingDir/missingDetritus.txt
extraDetritus=$workingDir/extraDetritus.txt

type=generateAbstracts

generationLog=$workingDir/generationLog.txt
detritusLog=$workingDir/detritusLog.txt

echo "Generating test data..."
python generateDetritusTestcases.py --$type --skeletonSentencesFile $skeletonSentences --wordlistFile $wordlist --detritusFile $detritusWordlist --outXML $goldXML  --outDetritusCounts $goldDetritus > $generationLog
if [[ $? -ne 0 ]]; then
        echo "generateDetritusTestcases.py FAILED."
        echo "Quitting test early!"
        exit 255
fi

echo "Running code..."
python ../detritusMajigger.py --termsWithSynonymsFile $wordlist --abstractsFile $goldXML --outFile $processedDetritus > $detritusLog 2>&1
if [[ $? -ne 0 ]]; then
        echo "detritusMajigger.py FAILED."
        echo "Quitting test early!"
        exit 255
fi

comm -23 <(sort $goldDetritus) <(sort $processedDetritus) > $missingDetritus
comm -13 <(sort $goldDetritus) <(sort $processedDetritus) > $extraDetritus

numMissing=`cat $missingDetritus | wc -l`
numExtra=`cat $extraDetritus | wc -l`

failed=0

echo
echo "--------------"
echo " TEST RESULTS"
echo "--------------"

if [[ $numMissing -gt 0 ]]; then
	echo "$numMissing missing detritus!"
	failed=1
fi

if [[ $numExtra -gt 0 ]]; then
	echo "$numExtra extra detritus!"
	failed=1
fi

if [[ $failed -eq 0 ]]; then
	echo "Test PASSED."
	exit 0
else
	echo "Test FAILED."
	exit 255
fi


text:
package redis.clients.jedis;

public class HostAndPort {
  public static final String LOCALHOST_STR = "localhost";

  private String host;
  private int port;
  private String nodeKey;

  public HostAndPort(String host, int port) {
    this.host = host;
    this.port = port;
    this.nodeKey = host + ":" + port;
  }

  public HostAndPort(String nodeKey) {
    int indexOf = nodeKey.indexOf(':');
    this.host = convertHost(nodeKey.substring(0, indexOf));
    this.port = Integer.valueOf(nodeKey.substring(indexOf + 1));
    this.nodeKey = nodeKey;
  }

  public String getHost() {
    return host;
  }

  public int getPort() {
    return port;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof HostAndPort) {
      HostAndPort hp = (HostAndPort) obj;

      String thisHost = convertHost(host);
      String hpHost = convertHost(hp.host);
      return port == hp.port && thisHost.equals(hpHost);

    }

    return false;
  }

  @Override
  public int hashCode() {
    return 31 * convertHost(host).hashCode() + port;
  }

  @Override
  public String toString() {
    return host + ":" + port;
  }

  private String convertHost(String host) {
    if (host.equals("127.0.0.1")) return LOCALHOST_STR;
    else if (host.equals("::1")) return LOCALHOST_STR;

    return host;
  }

  public String getNodeKey() {
    return nodeKey;
  }
}


text:
import os.path as op
import warnings

import numpy as np
from numpy.testing import assert_array_equal, assert_allclose

from scipy.signal import hann

from nose.tools import assert_raises, assert_true, assert_equal

import mne
from mne import read_source_estimate
from mne.datasets import testing
from mne.stats.regression import linear_regression, linear_regression_raw
from mne.io import RawArray

warnings.simplefilter('always')

data_path = testing.data_path(download=False)
stc_fname = op.join(data_path, 'MEG', 'sample',
                    'sample_audvis_trunc-meg-lh.stc')
raw_fname = data_path + '/MEG/sample/sample_audvis_trunc_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_trunc_raw-eve.fif'

@testing.requires_testing_data
def test_regression():
    """Test Ordinary Least Squares Regression."""
    tmin, tmax = -0.2, 0.5
    event_id = dict(aud_l=1, aud_r=2)

    # Setup for reading the raw data
    raw = mne.io.read_raw_fif(raw_fname, add_eeg_ref=False)
    events = mne.read_events(event_fname)[:10]
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                        baseline=(None, 0), add_eeg_ref=False)
    picks = np.arange(len(epochs.ch_names))
    evoked = epochs.average(picks=picks)
    design_matrix = epochs.events[:, 1:].astype(np.float64)
    # makes the intercept
    design_matrix[:, 0] = 1
    # creates contrast: aud_l=0, aud_r=1
    design_matrix[:, 1] -= 1
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        lm = linear_regression(epochs, design_matrix, ['intercept', 'aud'])
        assert_true(w[0].category == RuntimeWarning)
        assert_true('non-data' in '%s' % w[0].message)

    for predictor, parameters in lm.items():
        for value in parameters:
            assert_equal(value.data.shape, evoked.data.shape)

    assert_raises(ValueError, linear_regression, [epochs, epochs],
                  design_matrix)

    stc = read_source_estimate(stc_fname).crop(0, 0.02)
    stc_list = [stc, stc, stc]
    stc_gen = (s for s in stc_list)
    with warnings.catch_warnings(record=True):  # divide by zero
        warnings.simplefilter('always')
        lm1 = linear_regression(stc_list, design_matrix[:len(stc_list)])
    lm2 = linear_regression(stc_gen, design_matrix[:len(stc_list)])
    for val in lm2.values():
        # all p values are 0 < p <= 1 to start, but get stored in float32
        # data, so can actually be truncated to 0. Thus the mlog10_p_val
        # actually maintains better precision for tiny p-values.
        assert_true(np.isfinite(val.p_val.data).all())
        assert_true((val.p_val.data <= 1).all())
        assert_true((val.p_val.data >= 0).all())
        # all -log10(p) are non-negative
        assert_true(np.isfinite(val.mlog10_p_val.data).all())
        assert_true((val.mlog10_p_val.data >= 0).all())
        assert_true((val.mlog10_p_val.data >= 0).all())

    for k in lm1:
        for v1, v2 in zip(lm1[k], lm2[k]):
            assert_array_equal(v1.data, v2.data)

@testing.requires_testing_data
def test_continuous_regression_no_overlap():
    """Test regression without overlap correction, on real data."""
    tmin, tmax = -.1, .5

    raw = mne.io.read_raw_fif(raw_fname, preload=True, add_eeg_ref=False)
    raw.apply_proj()
    events = mne.read_events(event_fname)
    event_id = dict(audio_l=1, audio_r=2)

    raw = raw.pick_channels(raw.ch_names[:2])

    epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                        baseline=None, reject=None, add_eeg_ref=False)

    revokeds = linear_regression_raw(raw, events, event_id,
                                     tmin=tmin, tmax=tmax,
                                     reject=None)

    # Check that evokeds and revokeds are nearly equivalent
    for cond in event_id.keys():
        assert_allclose(revokeds[cond].data,
                        epochs[cond].average().data, rtol=1e-15)

    # Test events that will lead to "duplicate" errors
    old_latency = events[1, 0]
    events[1, 0] = events[0, 0]
    assert_raises(ValueError, linear_regression_raw,
                  raw, events, event_id, tmin, tmax)

    events[1, 0] = old_latency
    events[:, 0] = range(len(events))
    assert_raises(ValueError, linear_regression_raw, raw,
                  events, event_id, tmin, tmax, decim=2)

def test_continuous_regression_with_overlap():
    """Test regression with overlap correction."""
    signal = np.zeros(100000)
    times = [1000, 2500, 3000, 5000, 5250, 7000, 7250, 8000]
    events = np.zeros((len(times), 3), int)
    events[:, 2] = 1
    events[:, 0] = times
    signal[events[:, 0]] = 1.
    effect = hann(101)
    signal = np.convolve(signal, effect)[:len(signal)]
    raw = RawArray(signal[np.newaxis, :], mne.create_info(1, 100, 'eeg'))

    assert_allclose(effect,
                    linear_regression_raw(raw, events, {1: 1}, tmin=0)[1]
                    .data.flatten())


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">

    {% load static %}
    <link rel="stylesheet" href="{% static 'dice/w3.css' %}">
    <link rel="shortcut icon" href="{% static 'dice/images/favicon.ico' %}">

    <title>dicey9000web</title>

	  dicey9000

dicey9000 is a dice roll web app powered by
	Django
	that was originally designed as a
	Discord bot.
	Check out source code for this page at

	  Github.

Dice Roller

	  <form method="post" novalidate>
	    {% csrf_token %}
	    {% load widget_tweaks %}
	    {{ form.non_field_errors }}

	      {% for field in form %}

		{% if field.label == "Roll Modifier" %}
		{{ field|add_class:"w3-input w3-border"|attr:"placeholder:0 for sum of the results" }}
		{% else %}
		{{ field|add_class:"w3-input w3-border" }}
		{% endif %}
		{{ field.label }}
		{% for error in field.errors %}

{{ error }}
		{% endfor %}

	      {% endfor %}

	    <input type="submit" value="Roll!" class="w3-btn w3-red w3-ripple w3-margin-left w3-margin-bottom">
	  </form>

Roll Results

{{ roll_output|safe }}

      dicey9000web &copy 2017 by
      Bruno Medeiros


text:
//
//  $Id$
//
//  SPDatabaseData.h
//  sequel-pro
//
//  Created by Stuart Connolly (stuconnolly.com) on May 20, 2009.
//  Copyright (c) 2009 Stuart Connolly. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person
//  obtaining a copy of this software and associated documentation
//  files (the "Software"), to deal in the Software without
//  restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following
//  conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//  OTHER DEALINGS IN THE SOFTWARE.
//
//  More info at <http://code.google.com/p/sequel-pro/>

@class SPServerSupport;
@class SPMySQLConnection;

/**
 * @class SPDatabaseData SPDatabaseData.h
 *
 * @author Stuart Connolly http://stuconnolly.com/
 *
 * This class provides various convenience methods for obtaining data associated with the current database,
 * if available. This includes available encodings, collations, etc.
 */
@interface SPDatabaseData : NSObject
{
	NSString *characterSetEncoding;
	NSString *defaultCharacterSetEncoding;
	NSString *defaultCollation;
	NSString *serverDefaultCharacterSetEncoding;
	NSString *serverDefaultCollation;
	NSString *defaultStorageEngine;

	NSMutableArray *collations;
	NSMutableArray *characterSetCollations;
	NSMutableArray *storageEngines;
	NSMutableArray *characterSetEncodings;
	NSMutableDictionary *cachedCollationsByEncoding;

	SPMySQLConnection *connection;
	SPServerSupport *serverSupport;
}

/**
 * @property connection The current database connection
 */
@property (readwrite, assign) SPMySQLConnection *connection;

/**
 * @property serverSupport The connection's associated SPServerSupport instance
 */
@property (readwrite, assign) SPServerSupport *serverSupport;

- (void)resetAllData;

- (NSArray *)getDatabaseCollations;
- (NSArray *)getDatabaseCollationsForEncoding:(NSString *)encoding;
- (NSArray *)getDatabaseStorageEngines;
- (NSArray *)getDatabaseCharacterSetEncodings;

- (NSString *)getDatabaseDefaultCharacterSet;
- (NSString *)getDatabaseDefaultCollation;
- (NSString *)getDatabaseDefaultStorageEngine;

- (NSString *)getServerDefaultCharacterSet;
- (NSString *)getServerDefaultCollation;

@end