text:
![Async Logo](https://raw.githubusercontent.com/caolan/async/master/logo/async-logo_readme.jpg)

[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async)
[![NPM version](https://img.shields.io/npm/v/async.svg)](https://www.npmjs.com/package/async)
[![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master)
[![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

*For Async v1.5.x documentation, go [HERE](https://github.com/caolan/async/blob/v1.5.2/README.md)*

Async is a utility module which provides straight-forward, powerful functions
for working with asynchronous JavaScript. Although originally designed for
use with [Node.js](https://nodejs.org/) and installable via `npm install --save async`,
it can also be used directly in the browser.

Async is also installable via:

- [yarn](https://yarnpkg.com/en/): `yarn add async`
- [bower](http://bower.io/): `bower install async`

Async provides around 70 functions that include the usual 'functional'
suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns
for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these
functions assume you follow the Node.js convention of providing a single
callback as the last argument of your asynchronous function -- a callback which expects an Error as its first argument -- and calling the callback once.

## Quick Examples

```js
async.map(['file1','file2','file3'], fs.stat, function(err, results) {
    // results is now an array of stats for each file
});

async.filter(['file1','file2','file3'], function(filePath, callback) {
  fs.access(filePath, function(err) {
    callback(null, !err)
  });
}, function(err, results) {
    // results now equals an array of the existing files
});

async.parallel([
    function(callback) { ... },
    function(callback) { ... }
], function(err, results) {
    // optional callback
});

async.series([
    function(callback) { ... },
    function(callback) { ... }
]);
```

There are many more functions available so take a look at the docs below for a
full list. This module aims to be comprehensive, so if you feel anything is
missing please create a GitHub issue for it.

## Common Pitfalls [(StackOverflow)](http://stackoverflow.com/questions/tagged/async.js)

### Synchronous iteration functions

If you get an error like `RangeError: Maximum call stack size exceeded.` or other stack overflow issues when using async, you are likely using a synchronous iteratee.  By *synchronous* we mean a function that calls its callback on the same tick in the javascript event loop, without doing any I/O or using any timers.  Calling many callbacks iteratively will quickly overflow the stack. If you run into this issue, just defer your callback with `async.setImmediate` to start a new call stack on the next tick of the event loop.

This can also arise by accident if you callback early in certain cases:

```js
async.eachSeries(hugeArray, function iteratee(item, callback) {
    if (inCache(item)) {
        callback(null, cache[item]); // if many items are cached, you'll overflow
    } else {
        doSomeIO(item, callback);
    }
}, function done() {
    //...
});
```

Just change it to:

```js
async.eachSeries(hugeArray, function iteratee(item, callback) {
    if (inCache(item)) {
        async.setImmediate(function() {
            callback(null, cache[item]);
        });
    } else {
        doSomeIO(item, callback);
        //...
    }
});
```

Async does not guard against synchronous iteratees for performance reasons.  If you are still running into stack overflows, you can defer as suggested above, or wrap functions with [`async.ensureAsync`](#ensureAsync)  Functions that are asynchronous by their nature do not have this problem and don't need the extra callback deferral.

If JavaScript's event loop is still a bit nebulous, check out [this article](http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/) or [this talk](http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html) for more detailed information about how it works.

### Multiple callbacks

Make sure to always `return` when calling a callback early, otherwise you will cause multiple callbacks and unpredictable behavior in many cases.

```js
async.waterfall([
    function(callback) {
        getSomething(options, function (err, result) {
            if (err) {
                callback(new Error("failed getting something:" + err.message));
                // we should return here
            }
            // since we did not return, this callback still will be called and
            // `processData` will be called twice
            callback(null, result);
        });
    },
    processData
], done)
```

It is always good practice to `return callback(err, result)`  whenever a callback call is not the last statement of a function.

### Binding a context to an iteratee

This section is really about `bind`, not about `async`. If you are wondering how to
make `async` execute your iteratees in a given context, or are confused as to why
a method of another library isn't working as an iteratee, study this example:

```js
// Here is a simple object with an (unnecessarily roundabout) squaring method
var AsyncSquaringLibrary = {
    squareExponent: 2,
    square: function(number, callback){
        var result = Math.pow(number, this.squareExponent);
        setTimeout(function(){
            callback(null, result);
        }, 200);
    }
};

async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result) {
    // result is [NaN, NaN, NaN]
    // This fails because the `this.squareExponent` expression in the square
    // function is not evaluated in the context of AsyncSquaringLibrary, and is
    // therefore undefined.
});

async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result) {
    // result is [1, 4, 9]
    // With the help of bind we can attach a context to the iteratee before
    // passing it to async. Now the square function will be executed in its
    // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent`
    // will be as expected.
});
```

## Download

The source is available for download from
[GitHub](https://raw.githubusercontent.com/caolan/async/master/dist/async.min.js).
Alternatively, you can install using npm:

```bash
$ npm install --save async
```

As well as using Bower:

```bash
$ bower install async
```

You can then `require()` async as normal:

```js
var async = require("async");
```

Or require individual methods:

```js
var waterfall = require("async/waterfall");
var map = require("async/map");
```

__Development:__ [async.js](https://raw.githubusercontent.com/caolan/async/master/dist/async.js) - 29.6kb Uncompressed

### In the Browser

Async should work in any ES5 environment (IE9 and above).

Usage:

```html
<script type="text/javascript" src="async.js"></script>
<script type="text/javascript">

    async.map(data, asyncProcess, function(err, results) {
        alert(results);
    });

</script>
```

The portable versions of async, including `async.js` and `async.min.js`, are
included in the `/dist` folder. Async can also be found on the [jsDelivr CDN](http://www.jsdelivr.com/projects/async).

### ES Modules

We also provide async as a collection of ES2015 modules, in an alternative `async-es` package on npm.

```bash
$ npm install --save async-es
```

```js
import waterfall from 'async-es/waterfall';
import async from 'async-es';
```

## Other Libraries

* [`limiter`](https://www.npmjs.com/package/limiter) a package for rate-limiting based on requests per sec/hour.
* [`neo-async`](https://www.npmjs.com/package/neo-async) an altername implementation of Async, focusing on speed.
* [`co-async`](https://www.npmjs.com/package/co-async) a library inspired by Async for use with [`co`](https://www.npmjs.com/package/co) and generator functions.
*  [`promise-async`](https://www.npmjs.com/package/promise-async) a version of Async where all the methods are Promisified.


text:
OCInjection
==========

DI framework for Objective C. This framework is still under development, and it is not meant to be used in production yet.

OCInjection supports both property injection and constructor injection.
In order to inject a property you need to mark the property as @dynamic.

Property injection is required on root level (ex:Injecting property in a ViewContorller).
On lower levels you can decide to either go with property injection or constructor injection, but constructor injection is always preferred.

Configuring DI Container
----------
In order to configure binding create a new class inheriting from 'DIAbstractModule', and implement configure 'method'
```objective-c
#import "DIAbstractModule.h"

@interface DIConfig : DIAbstractModule

@end
```
```objective-c
@implementation DIConfig

- (void)configure
{
        // Binding protocol to a class, and mamarking it a singleton object
        // Since constrcutor is not defined the standard init method will be used for initialization
        [self bindProtocol:@protocol(ServiceClientProtocl) toClass:[ServiceClient class] asSingleton:YES];

        // Binding a protocol to a class, and defining a constructor
        // Objective c doesn't preserve method argument types (Class info) at runtime
        // So you must provide the type of parameters when binding
	[[[self bindProtocol:@protocol(GithubClientProtocol) toClass:[GithubClient class]] withConstructor]
		initWithServiceClient:Inject(@protocol(ServiceClientProtocl))];
}

@end
```
```objective-c
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    DIConfig *config = [[DIConfig alloc] init];
    [[DIInjector sharedInstance] setDefaultModule:config];

    return YES;
}
```
Using DI
----------
```objective-c
@interface ViewController : UIViewController

@property (nonatomic, strong) IBOutlet UIWebView *webView;

@end
```
```objective-c
@interface ViewController()
@property (nonatomic, strong) id <GithubClientProtocol> githubClient;
@end

@implementation ViewController
@synthesize webView;
@dynamic githubClient;

- (void)viewDidLoad
{
   [super viewDidLoad];

   [self.githubClient fetchDataByUsername:@"aryaxt"];
}

@end
```

Mocking Dependencies for Unit Testing
----------
```objective-c
@implementation DIMockConfig

- (void)configure
{
	OCMockObject *githubClient = [OCMockObject mockForProtocol:@protocol(GithubClientProtocol)];
	OCMockObject *serviceClient = [OCMockObject mockForProtocol:@protocol(ServiceClientProtocol)];

	[self bindProtocol:@protocol(ServiceClientProtocol) toInstance:serviceClient];
	[self bindProtocol:@protocol(GithubClientProtocol) toInstance:githubClient];
}

@end
```
Sample Unit Test
----------
```objective-c
@interface ViewControllerTests : SenTestCase

@property (nonatomic, strong) ViewController *viewController;

@end
```
```objective-c
@interface ViewControllerTests()
@property (nonatomic, strong) id <GithubClientProtocol> githubClient;
@end

@implementation ViewControllerTests
@dynamic githubClient;
@synthesize viewController;

#pragma mark - Setup & TearDown -

- (void)setUp
{
    [super setUp];

	DIMockConfig *module = [[DIMockConfig alloc] init];
	[[DIInjector sharedInstance] setDefaultModule:module];

    self.viewController = [[ViewController alloc] init];
}

- (void)tearDown
{
    self.viewController =  nil;

    [super tearDown];
}

#pragma mark - Tests -

- (void)testShouldFetchDataWithCorrectUsername
{
       // Since we bind GithubClientProtocol to an instance
       // The instance injected in viewController is the same as the one injected in test file
       // So we can mock the object and test it without having to make it a public property

	static NSString *expectedUsername = @"DependencyInjearyaxtction";
	[[(OCMockObject *)self.githubClient expect] fetchDataByUsername:expectedUsername];
	[self.viewController view]; // Trigger viewDidLoad
	[(OCMockObject *)self.githubClient verify];
}

@end
```
In-Line Dependency Resolving
----------
```objective-c
// Resolving Protocol
id <GoogleClientProtocol> googleClient = [[DIInjector sharedInstance] resolveForProtocol:@protocol(GoogleClientProtocol)];

// Resolving Class
YahooClient *yahooClient = [[DIInjector sharedInstance] resolveForClass:[YahooClient class]];
```

redpajama_set_name: RedPajamaGithub


text:
import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import { logOut } from './actions/logOutAction';

class App extends Component {
  constructor() {
    super();
    this.onClickHandler = this.onClickHandler.bind(this);
  }

  onClickHandler(event) {
    event.preventDefault();
    this.props.logOut(this.state);
  }

  render() {
    return (

            Docify

Logout

        {this.props.children}

    );
  }
}

App.propTypes = {
  children: React.PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node
  ]),
  logOut: PropTypes.func.isRequired
};

App.defaultProps = {
  children: [] || null
};

export default connect(null, { logOut })(App);


text:
import sys
import os
sys.path = [ '/export/rocks/install/rocks-dist/x86_64/build/include/installclass' ] + sys.path;
import re
import subprocess
import shlex
#import argparse

membership = '&membership;'
nodename = '&hostname;'

def find_disk_size(disk_size_str):
    match = re.match(r"([0-9\.]+)([a-z]+)", disk_size_str, re.I)
    if match:
        items = match.groups();
        if(len(items) == 2):
            size_units = { 'KB':1024, 'MB':1024*1024, 'GB':1024*1024*1024, 'TB':1024*1024*1024*1024, 'PB':1024*1024*1024*1024*1024 };
            if(items[1] in size_units):
                disk_size = float(items[0])*size_units[items[1]];
                return disk_size;
    return None;

def find_disk_id(line):
    tokens = line.split();
    if(len(tokens) >= 3 and tokens[0] == 'Disk'):
        disk = tokens[1];
        disk = disk.replace(':','');
        return disk;
    return None;

def find_os_disk(disks):
    disk_list = [ ];
    for disk in disks:
        disk_id = disk[0];
        disk_size = find_disk_size(disk[1]);
        if(disk_size and disk_id):
            disk_list.append((disk_id, disk_size));
        else:
            return None;        #could not determine size for one of the disks - play safe and return None
    if(len(disk_list) > 0):
        disk_list.sort(key=lambda x:x[1]);
        fptr = open('/tmp/disk_list.csv','wb');
        first_disk = True;
        for disk_id,disk_size in disk_list:
            fptr.write(disk_id+',%.2f'%(disk_size));
            if(first_disk):
                fptr.write(',OS_disk');
            fptr.write('\n');
            first_disk = False;
        fptr.close();
        return (disk_list[0][0], disk_list[0][1]);         #smallest disk
    return None;

def doDisk(file, disk, disk_size, force_format=False, root_partition_size=None):
    if(force_format):
        parted_cmd = '/sbin/parted -s '+disk+' mklabel msdos';
        print(parted_cmd);
        process = subprocess.Popen(shlex.split(parted_cmd), stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT);
        stdout_str = process.communicate()[0];
        print(stdout_str);
    disk = os.path.basename(disk);
    file.write('zerombr\n')
    file.write('clearpart --drives=%s\n' % disk)
    disk_size = int(float(disk_size)/(1024*1024*1024));   #GB
    max_swap = 64;     #64 GB
    recommended_root_size = 150; #150 GB
    if(root_partition_size):
        root_partition_size = min(disk_size, root_partition_size);
        swap_size = min(max_swap, disk_size-root_partition_size);
    else:
        if(disk_size <= recommended_root_size): #<=recommended, no swap
            root_partition_size = disk_size;
            swap_size = 0;
        else:
            swap_size = min(max_swap, disk_size-recommended_root_size);
            root_partition_size = disk_size-swap_size;
    file.write(('part biosboot --fstype=biosboot --size=1 --ondisk=%s\n')%(disk))
    if(swap_size > 0):
        file.write(('part swap --fstype="swap" --size=%d --ondisk=%s\n') % (swap_size*1024, disk))  #MB - as per kickstart
    if(root_partition_size < (disk_size - swap_size)):
        file.write('part / --fstype="ext4" --size=%d --ondisk=%s\n' % (root_partition_size*1024, disk))
    else:
        file.write('part / --fstype="ext4" --size=1 --grow --ondisk=%s\n'    % disk)
    file.write('bootloader --location=mbr --boot-drive=%s\n'%disk);

#
# main
#

#p = rocks_partition.RocksPartition();
#disks = p.getDisks();

def get_parted_disk_list():
    process = subprocess.Popen(shlex.split('/sbin/parted -l -m'), stdout=subprocess.PIPE);
    stdout_str = process.communicate()[0];
    list = stdout_str.split('\n');
    #First initialize uninitialized disks - create msdos if needed
    for line in list:
        if(line.find('Error') != -1 and line.find('unrecognised disk label') != -1):
            new_line = line.strip();
            tokens = new_line.split();
            if(len(tokens) > 2):
                disk =  tokens[1].replace(':','');
                subprocess.call(shlex.split('/sbin/parted -s '+disk+' mktable msdos'));
    #Now create list of disks
    process = subprocess.Popen(shlex.split('/sbin/parted -l -m'), stdout=subprocess.PIPE);
    stdout_str = process.communicate()[0];
    list = stdout_str.split('\n');
    disk_list=[];
    next_is_disk = False;
    for line in list:
        if(next_is_disk):
            new_line = line.strip();
	    if(new_line.find('loop') == -1 and new_line.find('zram') == -1):	#not a loop-back device and not a ramdisk device
	      new_line = new_line.replace(';','');
	      disk_list.append(new_line.split(':'));
            next_is_disk = False;
        if(line.find('BYT') != -1):
            next_is_disk = True;
    return disk_list;

def main(argv):
    arg_needs_value  = { '--root_partition_size':True, '--force_format':False, '--manual':False };
    param_values = { 'manual':False, 'force_format':False, 'root_partition_size':None } ;  #GB
    node_type = None;
    i = 0;
    for i in range(len(argv)):
        arg = argv[i];
        if(arg in arg_needs_value):
            cut_arg = arg.replace('--','');
            if(arg_needs_value[arg]):
                param_values[cut_arg] = argv[i+1];
                i += 1;
            else:
                param_values[cut_arg] = True;
        else:
            if(node_type):
                sys.stderr.write('Node type already assigned to '+node_type+', only 1 positional argument expected\n');
                sys.exit(-1);
            node_type = arg;
        i += 1;
    if(param_values['root_partition_size']):
        param_values['root_partition_size']  = int(param_values['root_partition_size']);
    if(not node_type):
        param_values['manual'] = True;
    #parser.add_argument("node_type", help='Type of node - Lustre server (OSS/MDS/MGS), compute etc');
    #parser.add_argument("--root_partition_size", help="Root partition size in GB(integer)", default=100, type=int); #GB
    #group = parser.add_mutually_exclusive_group()
    #group.add_argument("--force_format", help='Force format of whole OS disk', action="store_true");
    #group.add_argument("--manual", help='Manual format', action="store_true");
    #args = parser.parse_args();
    file = open('/tmp/user_partition_info', 'wb')
    #Manual format if manual_format or (Lustre servers and not force_format)
    if param_values['manual'] or (node_type == 'lustre_server' and not param_values['force_format']):
        file.write('rocks manual\n');
        file.close();
        sys.exit(0);
    disks = get_parted_disk_list();
    os_disk_tuple = find_os_disk(disks);
    if(os_disk_tuple):
        doDisk(file, os_disk_tuple[0], os_disk_tuple[1], force_format=param_values['force_format'],
                root_partition_size=param_values['root_partition_size']);
    else:    #could not find a suitable disk, use manual
        file.write("rocks manual\n");
    file.close()

if __name__ == "__main__":
    main(sys.argv[1:] if len(sys.argv) > 1 else []);


text:
namespace seqan
{
// ============================================================================
// Forwards
// ============================================================================

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// Config structre for the execution of one alignment using the wave-front model.
template <typename TDPSettings>
struct WavefrontAlignmentTaskConfig
{
    // ----------------------------------------------------------------------------
    // Member Typedefs.

    // DPTrait type forwarding.
    using TDPTraits       = typename TDPSettings::TTraits;
    using TScoreValue     = typename Value<typename TDPSettings::TScoringScheme>::Type;
    using TAlgorithmType  = typename TDPTraits::TAlgorithmType;
    using TTracebackType  = typename TDPTraits::TTracebackType;
    using TGapType        = typename TDPTraits::TGapType;

    // Wavefront Alignment Context.
    using TDPCell         = DPCell_<TScoreValue, TGapType>;
    using TBufferValue    = Pair<TDPCell, typename TraceBitMap_<>::Type>;
    using TBuffer         = String<TBufferValue>;
    using TBlockBuffer    = DPTileBuffer<TBuffer>;

    // DP Execution Context.
    using TDPProfile      = DPProfile_<TAlgorithmType, TGapType, TTracebackType, Parallel>;
    using TDPCache        = DPContext<TDPCell, typename TraceBitMap_<>::Type>;
    using TDPScout        = DPScout_<TDPCell, Default>;

    // Parallel Context.
    struct IntermediateTraits_
    {
        using TScoreValue   = decltype(maxScore(std::declval<TDPScout>()));
        using THostPosition = decltype(maxHostPosition(std::declval<TDPScout>()));
    };

    using TDPIntermediate = WavefrontAlignmentResult<IntermediateTraits_>;

    struct AlignThreadLocalConfig_
    {
        using TIntermediate = TDPIntermediate;
        using TCache        = TDPCache;

        using TLocalHost    = std::tuple<TIntermediate, TCache>;
    };

    using TThreadLocal = WavefrontAlignmentThreadLocalStorage<AlignThreadLocalConfig_>;
    using TAlignEvent  = WavefrontTaskEvent;
};

#ifdef SEQAN_SIMD_ENABLED
template <typename TDPSettings>
struct WavefrontAlignmentSimdTaskConfig : public WavefrontAlignmentTaskConfig<TDPSettings>
{
    // ----------------------------------------------------------------------------
    // Member Typedefs.

    using TBase_ = WavefrontAlignmentTaskConfig<TDPSettings>;

    using TDPSimdCell        = DPCell_<typename TDPSettings::TScoreValueSimd, typename TBase_::TGapType>;
    using TDPSimdTraceValue  = typename TraceBitMap_<typename TDPSettings::TScoreValueSimd>::Type;

    using TDPSimdScoreMatrix = String<TDPSimdCell, Alloc<OverAligned>>;
    using TDPSimdTraceMatrix = String<TDPSimdTraceValue, Alloc<OverAligned>>;
    using TDPSimdCache       = DPContext<TDPSimdCell, TDPSimdTraceValue, TDPSimdScoreMatrix, TDPSimdTraceMatrix>;

    using TDPScout_          = DPScout_<TDPSimdCell, SimdAlignmentScout<> >;
    using TDPIntermediate    = WavefrontAlignmentResult<typename TBase_::IntermediateTraits_>;

    // Parallel Context.
    struct SimdAlignThreadLocalConfig_
    {

        using TIntermediate = TDPIntermediate;
        using TCache        = typename TBase_::TDPCache;
        using TSimdCache    = TDPSimdCache;

        using TLocalHost    = std::tuple<TIntermediate, TCache, TSimdCache>;
    };

    using TThreadLocal = WavefrontAlignmentThreadLocalStorage<SimdAlignThreadLocalConfig_>;
    using TAlignEvent  = WavefrontTaskEvent;
};
#endif

// Incubator to setup the alignment job.
template <typename WavefrontAlignmentTaskConfigConcept>
struct WavefrontAlignmentTaskIncubator
{
    using TWatc = WavefrontAlignmentTaskConfigConcept;

    // ----------------------------------------------------------------------------
    // Function createBlocks()
    // ----------------------------------------------------------------------------

    template <typename TSeq>
    static auto createBlocks(TSeq const & seq, size_t const blockSize)
    {
        using TIter = typename Iterator<typename Infix<TSeq const>::Type, Standard>::Type;
        String<Range<TIter>> blocks;
        resize(blocks, (length(seq) + blockSize - 1) / blockSize, Exact());

        for (unsigned id = 0; id < length(blocks); ++id)
            blocks[id] = toRange(infix(seq, id * blockSize, _min(length(seq),(id + 1) * blockSize)));
        return blocks;
    }

    // ----------------------------------------------------------------------------
    // Function createBlockBuffer()
    // ----------------------------------------------------------------------------

    template <typename TSeqHBlocks, typename TSeqVBlovcks, typename TScore>
    static auto createBlockBuffer(TSeqHBlocks const & seqHBlocks, TSeqVBlovcks const & seqVBlocks, TScore const & score)
    {
        using TDPCell = typename TWatc::TDPCell;
        typename TWatc::TBlockBuffer buffer;
        resize(buffer.horizontalBuffer, length(seqHBlocks), Exact());
        resize(buffer.verticalBuffer, length(seqVBlocks), Exact());

        typename TWatc::TBufferValue tmp;

        using TDPMetaColH = DPMetaColumn_<typename TWatc::TDPProfile, MetaColumnDescriptor<DPInnerColumn, FullColumn>>;
        using TDPMetaColV = DPMetaColumn_<typename TWatc::TDPProfile, MetaColumnDescriptor<DPInitialColumn, FullColumn>>;

        TDPCell dummyCellD;
        TDPCell dummyCellH;
        TDPCell dummyCellV;
        tmp.i2 = _computeScore(tmp.i1, dummyCellD, dummyCellH, dummyCellV,  Nothing(), Nothing(), score,
                               RecursionDirectionZero(), typename TWatc::TDPProfile());
        for (auto itH = begin(buffer.horizontalBuffer, Standard());
             itH != end(buffer.horizontalBuffer, Standard());
             ++itH)
        {
            resize(*itH, length(front(seqHBlocks)), Exact());
            for (auto it = begin(*itH, Standard()); it != end(*itH, Standard()); ++it)
            {
                it->i2 = _computeScore(it->i1, dummyCellD, tmp.i1, dummyCellV, Nothing(), Nothing(), score,
                                       typename RecursionDirection_<TDPMetaColH, FirstCell>::Type(),
                                       typename TWatc::TDPProfile());
                tmp.i1 = it->i1;
            }
        }
        tmp.i1 = decltype(tmp.i1){};
        tmp.i2 = _computeScore(tmp.i1, dummyCellD, dummyCellH, dummyCellV, Nothing(), Nothing(), score,
                               RecursionDirectionZero(), typename TWatc::TDPProfile());

        for (auto itV = begin(buffer.verticalBuffer, Standard()); itV != end(buffer.verticalBuffer, Standard()); ++itV)
        {
            resize(*itV, length(front(seqVBlocks)) + 1, Exact());
            auto it = begin(*itV, Standard());
            it->i2 = tmp.i2;
            it->i1 = tmp.i1;
            ++it;
            for (; it != end(*itV, Standard()); ++it)
            {
                it->i2 = _computeScore(it->i1, dummyCellD, dummyCellH, dummyCellV, Nothing(), Nothing(), score,
                                       typename RecursionDirection_<TDPMetaColV, InnerCell>::Type(),
                                       typename TWatc::TDPProfile());
                _setVerticalScoreOfCell(it->i1, _verticalScoreOfCell(dummyCellV));
                tmp.i1 = it->i1;
                tmp.i2 = it->i2;  // TODO(rrahn): Move out of loop.
            }
        }
        return buffer;
    }

    // ----------------------------------------------------------------------------
    // Function createTaskGraph()
    // ----------------------------------------------------------------------------

    template <typename TWavefrontTaskContext>
    static auto createTaskGraph(TWavefrontTaskContext & taskContext)
    {
        using TDagTask = WavefrontTask<TWavefrontTaskContext>;

        std::vector<std::vector<std::shared_ptr<TDagTask>>> graph;

        resize(graph, length(taskContext.seqHBlocks));
        for (int i = length(taskContext.seqHBlocks); --i >= 0;)
        {
            resize(graph[i], length(taskContext.seqVBlocks));
            for (int j = length(taskContext.seqVBlocks); --j >= 0;)
            {
                using TSize = decltype(length(taskContext.seqHBlocks));
                TDagTask * successorRight = (static_cast<TSize>(i + 1) < length(taskContext.seqHBlocks))
                                                ?  graph[i+1][j].get()
                                                : nullptr;
                TDagTask * successorDown  = (static_cast<TSize>(j + 1) < length(taskContext.seqVBlocks))
                                                ? graph[i][j+1].get()
                                                : nullptr;
                graph[i][j] = std::make_shared<TDagTask>(taskContext,
                                                         std::array<TDagTask*, 2>{{successorRight, successorDown}},
                                                         static_cast<size_t>(i), static_cast<size_t>(j),
                                                         static_cast<size_t>(((i > 0) ? 1 : 0) + ((j > 0) ? 1 : 0)),
                                                         (static_cast<TSize>(i + 1) == length(taskContext.seqHBlocks)),
                                                         (static_cast<TSize>(j + 1) == length(taskContext.seqVBlocks)));
            }
        }
        return graph;
    }
};

// The actual alignment task that is executed by the wave-front model.
template <typename TSeqH,
          typename TSeqV,
          typename TDPSettings,
          typename TConfig = WavefrontAlignmentTaskConfig<TDPSettings>>
class WavefrontAlignmentTask
{
public:

    using TIncubator    = WavefrontAlignmentTaskIncubator<TConfig>;

    using TSeqHBlocks   = decltype(TIncubator::createBlocks(std::declval<TSeqH>(), std::declval<size_t>()));
    using TSeqVBlocks   = decltype(TIncubator::createBlocks(std::declval<TSeqV>(), std::declval<size_t>()));
    using TTileBuffer   = decltype(TIncubator::createBlockBuffer(std::declval<TSeqHBlocks>(),
                                                                 std::declval<TSeqVBlocks>(),
                                                                 std::declval<typename TDPSettings::TScoringScheme>()));

    using TTaskContext  = WavefrontAlignmentContext<TSeqHBlocks, TSeqVBlocks, TTileBuffer, TDPSettings>;

    // ----------------------------------------------------------------------------
    // Member Variables.
    // ----------------------------------------------------------------------------

    size_t              alignmentId{0};
    TSeqH const &       seqH;
    TSeqV const &       seqV;
    TDPSettings const & dpSettings;
    size_t              blockSize;

    // ----------------------------------------------------------------------------
    // Constructors.
    // ----------------------------------------------------------------------------

    WavefrontAlignmentTask() = delete;

    WavefrontAlignmentTask(TSeqH const & seqH,
                           TSeqV const & seqV,
                           TDPSettings const & dpSetting,
                           size_t const & blockSize) :
        seqH(seqH),
        seqV(seqV),
        dpSettings(dpSetting),
        blockSize(blockSize)
    {}

    WavefrontAlignmentTask(size_t const id,
                           TSeqH const & seqH,
                           TSeqV const & seqV,
                           TDPSettings const & dpSetting,
                           size_t const & blockSize) :
        alignmentId(id),
        seqH(seqH),
        seqV(seqV),
        dpSettings(dpSetting),
        blockSize(blockSize)
    {}

    // ----------------------------------------------------------------------------
    // Member Functions.
    // ----------------------------------------------------------------------------

    // This function now run's in a separate thread.
    template <typename TWavefrontExecutor,
              typename TCallback>
    inline void
    operator()(uint16_t const instanceId,
               TWavefrontExecutor & executor,
               TCallback && callback)
    {
        // Initialize the strings.
        auto seqHBlocks = TIncubator::createBlocks(seqH, blockSize);
        auto seqVBlocks = TIncubator::createBlocks(seqV, blockSize);

        // Create the buffer for the matrix.
        auto buffer = TIncubator::createBlockBuffer(seqHBlocks, seqVBlocks, dpSettings.scoringScheme);

        // Setup the task context and create task graph.
        TTaskContext taskContext{instanceId, seqHBlocks, seqVBlocks, buffer, dpSettings};
        auto taskGraph = TIncubator::createTaskGraph(taskContext);

        // Prepare event.
        WavefrontTaskEvent event;
        context(*taskGraph.back().back()).ptrEvent = &event;

        // Kick off the execution.
        using TWavefrontTaskExec = WavefrontTaskExecutor<std::decay_t<decltype(*taskGraph[0][0])>, TWavefrontExecutor>;
        spawn(executor, TWavefrontTaskExec{taskGraph[0][0].get(), &executor});

        // Wait for alignment to finish.
        wait(event);

        // Reduce.
        typename TConfig::TDPIntermediate interMax{};
        auto collectAndReset = [&](auto & threadLocalStorage)
        {
            updateMax(interMax, intermediate(threadLocalStorage, instanceId));
            clear(intermediate(threadLocalStorage, instanceId));
        };
        combineEach(*executor.ptrThreadLocal, collectAndReset);
        // Continue execution.
        callback(alignmentId, interMax._maxState.first);
    }

    template <typename TWavefrontExecutor,
              typename TSimdTaskQueue,
              typename TCallback>
    inline void
    operator()(uint16_t const instanceId,
               TWavefrontExecutor & executor,
               TSimdTaskQueue & taskQueue,
               TCallback && callback)
    {
        // Initialize the strings.
        auto seqHBlocks = TIncubator::createBlocks(seqH, blockSize);
        auto seqVBlocks = TIncubator::createBlocks(seqV, blockSize);

        // Create the buffer for the matrix.
        auto buffer = TIncubator::createBlockBuffer(seqHBlocks, seqVBlocks, dpSettings.scoringScheme);

        // Setup the task context and create task graph.
        TTaskContext taskContext{instanceId, seqHBlocks, seqVBlocks, buffer, dpSettings};
        auto taskGraph = TIncubator::createTaskGraph(taskContext);

        // Prepare event.
        WavefrontTaskEvent event;
        context(*taskGraph.back().back()).ptrEvent = &event;

        // Kick off the execution.
        using TWavefrontTaskExec = WavefrontTaskExecutor<TSimdTaskQueue, TWavefrontExecutor>;
        appendValue(taskQueue, *taskGraph[0][0]);
        spawn(executor, TWavefrontTaskExec{&taskQueue, &executor});

        // Wait for alignment to finish.
        wait(event);

        // Reduce.
        typename TConfig::TDPIntermediate interMax{};
        auto collectAndReset = [&](auto & threadLocalStorage)
        {
            updateMax(interMax, intermediate(threadLocalStorage, instanceId));
            clear(intermediate(threadLocalStorage, instanceId));
        };
        combineEach(*executor.ptrThreadLocal, collectAndReset);
        callback(alignmentId, interMax._maxState.first);
    }
};

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

}  // namespace seqan

#endif  // #ifndef INCLUDE_SEQAN_ALIGN_PARALLEL_WAVEFRONT_ALIGNMENT_TASK_H_


text:
// <editor-fold defaultstate="collapsed" desc="Header/SLA">
/*******************************************************************************
  Board Support Package Header File.

  Company:
    Microchip Technology Inc.

  File Name:
    bsp_config.h

  Summary:
    Board Support Package Header file for chipKIT Wi-FIRE.

  Description:
    This file contains constants, macros, type definitions and function
    declarations required by the chipKIT Wi-FIRE BSP.
 *******************************************************************************/

/*******************************************************************************
Copyright (c) 2015 released Microchip Technology Inc.  All rights reserved.

Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).

You should refer to the license agreement accompanying this Software for
additional information regarding your rights and obligations.

SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
 *******************************************************************************/// </editor-fold>

#ifndef _BSP_CONFIG_H
#define _BSP_CONFIG_H

// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************

#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include "peripheral/ports/plib_ports.h"

// *****************************************************************************
// *****************************************************************************
// Section: Constants and Type Definitions.
// *****************************************************************************
// *****************************************************************************

#define BSP_LED_1_CHANNEL   PORT_CHANNEL_G
#define BSP_LED_2_CHANNEL   PORT_CHANNEL_B
#define BSP_LED_3_CHANNEL   PORT_CHANNEL_D
#define BSP_LED_4_CHANNEL   PORT_CHANNEL_G

// *****************************************************************************
/* BSP Switch.

  Summary:
    Defines the switches available on this board.

  Description:
    This enumeration defines the switches available on this board.

  Remarks:
    None.
*/

typedef enum
{
    /* SWITCH 2 */
     BSP_SWITCH_1 = PORTS_BIT_POS_5,

    /* SWITCH 3 */
     BSP_SWITCH_2 = PORTS_BIT_POS_4,

} BSP_SWITCH;

// *****************************************************************************
/* BSP Switch state.

  Summary:
    Defines possible states of the switches on this board.

  Description:
    This enumeration defines the possible states of the switches on this board.

  Remarks:
    None.
*/

typedef enum
{
    /* Switch pressed */
    BSP_SWITCH_STATE_PRESSED = 1,

   /* Switch not pressed */
    BSP_SWITCH_STATE_RELEASED = 0

} BSP_SWITCH_STATE;

// *****************************************************************************
/* LED Number.

  Summary:
    Defines the LEDs available on this board.

  Description:
    This enumeration defines the LEDs available on this board.

  Remarks:
    None.
*/

typedef enum
{
    /* LED 1 */
    BSP_LED_1 = PORTS_BIT_POS_6,

    /* LED 2 */
    BSP_LED_2 = PORTS_BIT_POS_4,

    /* LED 3 */
    BSP_LED_3 = PORTS_BIT_POS_11,

    /* LED 4 */
    BSP_LED_4 = PORTS_BIT_POS_15,

} BSP_LED;

// *****************************************************************************
/* LED State

  Summary:
    Enumerates the supported LED states.

  Description:
    This enumeration defines the supported LED states.

  Remarks:
    None.
*/

typedef enum
{
    /* LED State is on */
    BSP_LED_STATE_OFF = 0,

    /* LED State is off */
    BSP_LED_STATE_ON = 1,

} BSP_LED_STATE;

// *****************************************************************************
// *****************************************************************************
// Section: Interface Routines
// *****************************************************************************
// *****************************************************************************

// *****************************************************************************
/* Function:
    void BSP_Initialize(void)

  Summary:
    Performs the necessary actions to initialize a board

  Description:
    This function initializes the LED and Switch ports on the board.  This
    function must be called by the user before using any APIs present on this
    BSP.

  Precondition:
    None.

  Parameters:
    None

  Returns:
    None.

  Example:

    //Initialize the BSP
    BSP_Initialize();

  Remarks:
    None
*/

void BSP_Initialize(void);

// *****************************************************************************
/* Function:
    void BSP_LEDStateSet(BSP_LED led, BSP_LED_STATE state);

  Summary:
    Controls the state of the LED.

  Description:
    This function allows the application to specify the state of the LED.

  Precondition:
    BSP_Initialize() should have been called.

  Parameters:
    led     - The LED to operate on.
    state   - The state to be set.

  Returns:
    None.

  Example:

    // Initialize the BSP
    BSP_Initialize();

    // Switch on LED1 on the board
    BSP_LEDStateSet(BSP_LED_1, BSP_LED_STATE_ON);

    // Switch off LED2 on the board
    BSP_LEDStateSet(BSP_LED_2, BSP_LED_STATE_OFF);

  Remarks:
    None
*/

void BSP_LEDStateSet(BSP_LED led, BSP_LED_STATE state);

// *****************************************************************************
/* Function:
    BSP_LED_STATE BSP_LEDStateGet(BSP_LED led);

  Summary:
    Returns the present state of the LED.

  Description:
    This function returns the present state of the LED.

  Precondition:
    BSP_Initialize() should have been called.

  Parameters:
    led - The LED to whose status needs to be obtained.

  Returns:
    The ON/OFF state of the LED.

  Example:

    // Initialize the BSP
    BSP_Initialize();

    // Check if LED2 is off
    if(BSP_LED_STATE_OFF == BSP_LEDStateGet(BSP_LED_2)
    {
        // Switch on the LED.
        BSP_LEDStateSet(BSP_LED_2, BSP_LED_STATE_ON);
    }

  Remarks:
    None
*/

BSP_LED_STATE BSP_LEDStateGet(BSP_LED led);

// *****************************************************************************
/* Function:
    void BSP_LEDToggle(BSP_LED led);

  Summary:
    Toggles the state of the LED between BSP_LED_STATE_ON and BSP_LED_STATE_OFF.

  Description:
    This function toggles the state of the LED between BSP_LED_STATE_ON and
    BSP_LED_STATE_OFF.

  Precondition:
    BSP_Initialize() should have been called.

  Parameters:
    led - The LED to toggle.

  Returns:
    None.

  Example:

    // Initialize the BSP
    BSP_Initialize();

    // Switch on LED1 on the board
    BSP_LEDStateSet(BSP_LED_1, BSP_LED_STATE_ON);

    // Switch off LED2 on the board
    BSP_LEDStateSet(BSP_LED_2, BSP_LED_STATE_OFF);

    // Toggle state of LED3
    BSP_LEDToggle(BSP_LED_3);

  Remarks:
    None
*/

void BSP_LEDToggle(BSP_LED led);

// *****************************************************************************
/* Function:
    void BSP_LEDOn(BSP_LED led);

  Summary:
    Switches ON the specified LED.

  Description:
    This function switches ON the specified LED.

  Precondition:
    BSP_Initialize() should have been called.

  Parameters:
    led - The LED to switch on.

  Returns:
    None.

  Example:

    // Initialize the BSP
    BSP_Initialize();

    // Switch on LED1 on the board
    BSP_LEDOn(BSP_LED_1);

  Remarks:
    None
*/

void BSP_LEDOn(BSP_LED led);

// *****************************************************************************
/* Function:
    void BSP_LEDOff(BSP_LED led);

  Summary:
    Switches OFF the specified LED.

  Description:
    This function switches OFF the specified LED.

  Precondition:
    BSP_Initialize() should have been called.

  Parameters:
    led - The LED to switch off.

  Returns:
    None.

  Example:

    // Initialize the BSP
    BSP_Initialize();

    // Switch off LED1 on the board
    BSP_LEDOff(BSP_LED_1);

  Remarks:
    None
*/

void BSP_LEDOff(BSP_LED led);

// *****************************************************************************
/* Function:
    BSP_SWITCH_STATE BSP_SwitchStateGet(BSP_SWITCH switch);

  Summary:
    Returns the present state (pressed or not pressed) of the specified switch.

  Description:
    This function returns the present state (pressed or not pressed) of the
    specified switch.

  Precondition:
    BSP_Initialize() should have been called.

  Parameters:
    switch  - The switch whose state needs to be obtained.

  Returns:
    The pressed released state of the switch.

  Example:

    // Initialize the BSP
    BSP_Initialize();

    // Check the state of the switch.
    if(BSP_SWITCH_STATE_PRESSED == BSP_SwitchStateGet(BSP_SWITCH_1))
    {
        // This means that Switch 1 on the board is pressed.
    }

  Remarks:
    None
*/

BSP_SWITCH_STATE BSP_SwitchStateGet(BSP_SWITCH bspSwitch);

// *****************************************************************************
/* Function:
    bool BSP_USBVBUSPowerEnable(uint8_t port, bool enable)

  Summary:
    This function controls the USB VBUS supply.

  Description:
    This function controls the USB VBUS supply.

  Precondition:
    BSP_Initialize() should have been called.

  Parameters:
    port - This parameter is ignored.

    enable  - if true VBUS supply is enabled. If false VBUS supply is disabled.

  Returns:
    None.

  Example:

    // Initialize the BSP
    BSP_Initialize();

    // Enable the power.
    BSP_USBVBUSPowerEnable(0, true);

    // Disable the power.
    BSP_USBVBUSPowerEnable(0, false);

  Remarks:
    None.
*/

void BSP_USBVBUSPowerEnable(uint8_t port, bool enable);

// *****************************************************************************
/* Function:
    bool BSP_USBVBUSOverCurrentDetect(uint8_t port)

  Summary:
    Returns true if the over current is detected on the VBUS supply.

  Description:
    This function returns true if over current is detected on the VBUS supply.

  Precondition:
    BSP_Initialize() should have been called.

  Parameters:
    port - This parameter is ignored.

  Returns:
    true - VBUS supply over current is detected.
    false - VBUS supply over current is not detected.

  Example:

    // Initialize the BSP
    BSP_Initialize();

    // Enable the power.
    BSP_USBVBUSPowerEnable(0, true);

    if(BSP_USBVBUSOverCurrentDetect(0))
    {
        // Disable the power.
        BSP_USBVBUSPowerEnable(0, false);
    }

  Remarks:
    None.
*/

bool BSP_USBVBUSSwitchOverCurrentDetect(uint8_t port);

#endif //_BSP_CONFIG_H

/*******************************************************************************
 End of File
*/


text:
from django.contrib import admin

from .models import Challenge, ChallengeRequest

admin.site.register(Challenge)
admin.site.register(ChallengeRequest)


text:
module Songkick
  module Api
    module InstanceMethods
      attr_accessor :client
      def initialize(client)
        @client = client
      end
    end
  end
end


text:
package com.serphacker.serposcope.scraper.http.extensions;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.security.auth.x500.X500Principal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.apache.http.annotation.Contract;
import org.apache.http.annotation.ThreadingBehavior;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.Args;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Allow to switch from secure SSL (with host verification) to unsafe SSL
 */
@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
public class ScrapClientSSLConnectionFactory implements LayeredConnectionSocketFactory {

    private static final Logger LOG = LoggerFactory.getLogger(ScrapClientSSLConnectionFactory.class);
    static SSLSocketFactory DEFAULT_SSL_SOCKET_FACTORY = null;
    static SSLSocketFactory INSECURE_SSL_SOCKET_FACTORY = null;
    static HostnameVerifier DEFAULT_HOSTNAME_VERIFIER = new DefaultHostnameVerifier();
    static HostnameVerifier INSECURE_HOSTNAME_VERIFIER = (String string, SSLSession ssls) -> true;

    static {
        try {
            INSECURE_SSL_SOCKET_FACTORY = SSLContexts.custom()
                .loadTrustMaterial(null, (X509Certificate[] chain, String authType) -> true)
                .build()
                .getSocketFactory();
            DEFAULT_SSL_SOCKET_FACTORY = SSLContexts.createDefault().getSocketFactory();
        } catch (Exception ex) {
            LOG.error("ex in ssl socket initialization", ex);
        }
    }

    public static final String TLS = "TLS";
    public static final String SSL = "SSL";
    public static final String SSLV2 = "SSLv2";

    private final Log log = LogFactory.getLog(getClass());

    private static String[] split(final String s) {
        if (TextUtils.isBlank(s)) {
            return null;
        }
        return s.split(" *, *");
    }

    private final ScrapClientPlainConnectionFactory plainConnectionSocketFactory;
    private final javax.net.ssl.SSLSocketFactory defaultSSLSocketFactory;
    private final javax.net.ssl.SSLSocketFactory insecoreSSLSocketfactory;
    private final HostnameVerifier defaultHostnameVerifier;
    private final HostnameVerifier insecureHostnameVerifier;
    private final String[] supportedProtocols;
    private final String[] supportedCipherSuites;
    private boolean insecure;

    public ScrapClientSSLConnectionFactory(ScrapClientPlainConnectionFactory plainConnectionSocketFactory) {
        this(plainConnectionSocketFactory, false);
    }

    public ScrapClientSSLConnectionFactory(ScrapClientPlainConnectionFactory plainConnectionSocketFactory, boolean insecure) {
        this(
            plainConnectionSocketFactory,
            DEFAULT_SSL_SOCKET_FACTORY,
            INSECURE_SSL_SOCKET_FACTORY,
            DEFAULT_HOSTNAME_VERIFIER,
            INSECURE_HOSTNAME_VERIFIER,
            null, null, insecure
        );
    }

    public ScrapClientSSLConnectionFactory(
        ScrapClientPlainConnectionFactory plainConnectionSocketFactory,
        javax.net.ssl.SSLSocketFactory defaultSSLSocketFactory,
        javax.net.ssl.SSLSocketFactory insecoreSSLSocketfactory,
        HostnameVerifier defaultHostnameVerifier,
        HostnameVerifier insecureHostnameVerifier,
        String[] supportedProtocols,
        String[] supportedCipherSuites,
        boolean insecure
    ) {
        this.plainConnectionSocketFactory = plainConnectionSocketFactory;
        this.defaultSSLSocketFactory = defaultSSLSocketFactory;
        this.insecoreSSLSocketfactory = insecoreSSLSocketfactory;
        this.defaultHostnameVerifier = defaultHostnameVerifier;
        this.insecureHostnameVerifier = insecureHostnameVerifier;
        this.supportedProtocols = supportedProtocols;
        this.supportedCipherSuites = supportedCipherSuites;
        this.insecure = insecure;
    }

    /**
     * Performs any custom initialization for a newly created SSLSocket (before the SSL handshake happens).
     *
     * The default implementation is a no-op, but could be overridden to, e.g., call
     * {@link javax.net.ssl.SSLSocket#setEnabledCipherSuites(String[])}.
     *
     * @throws IOException may be thrown if overridden
     */
    protected void prepareSocket(final SSLSocket socket) throws IOException {
    }

    @Override
    public Socket createSocket(final HttpContext context) throws IOException {
        return plainConnectionSocketFactory.createSocket(context);
    }

    @Override
    public Socket connectSocket(
        final int connectTimeout,
        final Socket socket,
        final HttpHost host,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpContext context) throws IOException {
        Args.notNull(host, "HTTP host");
        Args.notNull(remoteAddress, "Remote address");
        final Socket sock = socket != null ? socket : createSocket(context);
        if (localAddress != null) {
            sock.bind(localAddress);
        }
        try {
            if (connectTimeout > 0 && sock.getSoTimeout() == 0) {
                sock.setSoTimeout(connectTimeout);
            }
            if (this.log.isDebugEnabled()) {
                this.log.debug("Connecting socket to " + remoteAddress + " with timeout " + connectTimeout);
            }
            sock.connect(remoteAddress, connectTimeout);
        } catch (final IOException ex) {
            try {
                sock.close();
            } catch (final IOException ignore) {
            }
            throw ex;
        }
        // Setup SSL layering if necessary
        if (sock instanceof SSLSocket) {
            final SSLSocket sslsock = (SSLSocket) sock;
            this.log.debug("Starting handshake");
            sslsock.startHandshake();
            verifyHostname(sslsock, host.getHostName());
            return sock;
        } else {
            return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
        }
    }

    @Override
    public Socket createLayeredSocket(
        final Socket socket,
        final String target,
        final int port,
        final HttpContext context) throws IOException {

        SSLSocketFactory sslSocketFactory = insecure ? insecoreSSLSocketfactory : defaultSSLSocketFactory;

        final SSLSocket sslsock = (SSLSocket) sslSocketFactory.createSocket(
            socket,
            target,
            port,
            true);

        if (supportedProtocols != null) {
            sslsock.setEnabledProtocols(supportedProtocols);
        } else {
            // If supported protocols are not explicitly set, remove all SSL protocol versions
            final String[] allProtocols = sslsock.getEnabledProtocols();
            final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
            for (String protocol : allProtocols) {
                if (!protocol.startsWith("SSL")) {
                    enabledProtocols.add(protocol);
                }
            }
            if (!enabledProtocols.isEmpty()) {
                sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
            }
        }
        if (supportedCipherSuites != null) {
            sslsock.setEnabledCipherSuites(supportedCipherSuites);
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols()));
            this.log.debug("Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites()));
        }

        prepareSocket(sslsock);
        this.log.debug("Starting handshake");
        sslsock.startHandshake();
        verifyHostname(sslsock, target);
        return sslsock;
    }

    private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
        try {
            SSLSession session = sslsock.getSession();
            if (session == null) {
                // In our experience this only happens under IBM 1.4.x when
                // spurious (unrelated) certificates show up in the server'
                // chain.  Hopefully this will unearth the real problem:
                final InputStream in = sslsock.getInputStream();
                in.available();
                // If ssl.getInputStream().available() didn't cause an
                // exception, maybe at least now the session is available?
                session = sslsock.getSession();
                if (session == null) {
                    // If it's still null, probably a startHandshake() will
                    // unearth the real problem.
                    sslsock.startHandshake();
                    session = sslsock.getSession();
                }
            }
            if (session == null) {
                throw new SSLHandshakeException("SSL session not available");
            }

            if (this.log.isDebugEnabled()) {
                this.log.debug("Secure session established");
                this.log.debug(" negotiated protocol: " + session.getProtocol());
                this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

                try {

                    final Certificate[] certs = session.getPeerCertificates();
                    final X509Certificate x509 = (X509Certificate) certs[0];
                    final X500Principal peer = x509.getSubjectX500Principal();

                    this.log.debug(" peer principal: " + peer.toString());
                    final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                    if (altNames1 != null) {
                        final List<String> altNames = new ArrayList<String>();
                        for (final List<?> aC : altNames1) {
                            if (!aC.isEmpty()) {
                                altNames.add((String) aC.get(1));
                            }
                        }
                        this.log.debug(" peer alternative names: " + altNames);
                    }

                    final X500Principal issuer = x509.getIssuerX500Principal();
                    this.log.debug(" issuer principal: " + issuer.toString());
                    final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                    if (altNames2 != null) {
                        final List<String> altNames = new ArrayList<String>();
                        for (final List<?> aC : altNames2) {
                            if (!aC.isEmpty()) {
                                altNames.add((String) aC.get(1));
                            }
                        }
                        this.log.debug(" issuer alternative names: " + altNames);
                    }
                } catch (Exception ignore) {
                }
            }

            HostnameVerifier hostnameVerifier = insecure ? insecureHostnameVerifier : defaultHostnameVerifier;
            if (!hostnameVerifier.verify(hostname, session)) {
                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal x500Principal = x509.getSubjectX500Principal();
                throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
            }
            // verifyHostName() didn't blowup - good!
        } catch (final IOException iox) {
            // close the socket before re-throwing the exception
            try {
                sslsock.close();
            } catch (final Exception x) {
                /*ignore*/ }
            throw iox;
        }
    }

    public boolean isInsecure() {
        return insecure;
    }

    public void setInsecure(boolean insecure) {
        this.insecure = insecure;
    }

}


text:
package sh

import (
	"os"
	"path/filepath"
)

func filetest(name string, modemask os.FileMode) (match bool, err error) {
	fi, err := os.Stat(name)
	if err != nil {
		return
	}
	match = (fi.Mode() & modemask) == modemask
	return
}

func (s *Session) Getwd() string {
	dir := string(s.dir)
	if dir == "" {
		dir, _ = os.Getwd()
	}
	return dir
}

func (s *Session) abspath(name string) string {
	if filepath.IsAbs(name) {
		return name
	}
	return filepath.Join(s.Getwd(), name)
}

func init() {
	//log.SetFlags(log.Lshortfile | log.LstdFlags)
}

// expression can be dir, file, link
func (s *Session) Test(expression string, argument string) bool {
	var err error
	var fi os.FileInfo
	fi, err = os.Lstat(s.abspath(argument))
	switch expression {
	case "d", "dir":
		return err == nil && fi.IsDir()
	case "f", "file":
		return err == nil && fi.Mode().IsRegular()
	case "x", "executable":
		/*
			fmt.Println(expression, argument)
			if err == nil {
				fmt.Println(fi.Mode())
			}
		*/
		return err == nil && fi.Mode()&os.FileMode(0100) != 0
	case "L", "link":
		return err == nil && fi.Mode()&os.ModeSymlink != 0
	}
	return false
}

// expression can be d,dir, f,file, link
func Test(exp string, arg string) bool {
	s := NewSession()
	return s.Test(exp, arg)
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'Intervention Imprimantes');
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

        <?= Html::a(Yii::t('app', 'Create Intervention Imprimante'), ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'collaborator_name',
            'tonner',
            'tambour',
            'bac_Alimentation',
            // 'alimentation',
            // 'driver',
            // 'connexion_serveur_impression',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
// .NAME vtkDataSetToDataSetFilter - abstract filter class
// .SECTION Description
// vtkDataSetToDataSetFilter is an abstract filter class. Subclasses of
// vtkDataSetToDataSetFilter take a dataset as input and create a dataset as
// output. The form of the input geometry is not changed in these filters,
// only the point attributes (e.g. scalars, vectors, etc.).
//
// This is an abstract filter type. What that means is that the output of the
// filter is an abstract type (i.e., vtkDataSet), no matter what the input of
// the filter is. This can cause problems connecting together filters due to
// the change in dataset type. (For example, in a series of filters
// processing vtkPolyData, when a vtkDataSetToDataSetFilter or subclass is
// introduced into the pipeline, if the filter downstream of it takes
// vtkPolyData as input, the pipeline connection cannot be made.) To get
// around this problem, use one of the convenience methods to return a
// concrete type (e.g., vtkGetPolyDataOutput(), GetStructuredPointsOutput(),
// etc.).

// .SECTION See Also
// vtkBrownianPoints vtkProbeFilter vtkThresholdTextureCoords vtkDicer
// vtkElevationFilter vtkImplicitTextureCoords vtkTextureMapToBox
// vtkTextureMapToPlane vtkVectorDot vtkVectorNorm

#ifndef __vtkDataSetToDataSetFilter_h
#define __vtkDataSetToDataSetFilter_h

#include "vtkDataSetSource.h"

class vtkDataSet;
class vtkPolyData;
class vtkRectilinearGrid;
class vtkStructuredGrid;
class vtkStructuredPoints;
class vtkUnstructuredGrid;

class VTK_FILTERING_EXPORT vtkDataSetToDataSetFilter : public vtkDataSetSource
{

public:
  vtkTypeRevisionMacro(vtkDataSetToDataSetFilter,vtkDataSetSource);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Specify the input data or filter.
  void SetInput(vtkDataSet *input);

  // Description:
  // Get the output of this filter. If output is NULL then input
  // hasn't been set which is necessary for abstract objects.
  vtkDataSet *GetOutput();
  vtkDataSet *GetOutput(int idx);

  // Description:
  // Get the output as vtkPolyData.
  virtual vtkPolyData *GetPolyDataOutput();

  // Description:
  // Get the output as vtkStructuredPoints.
  virtual vtkStructuredPoints *GetStructuredPointsOutput();

  // Description:
  // Get the output as vtkStructuredGrid.
  virtual vtkStructuredGrid *GetStructuredGridOutput();

  // Description:
  // Get the output as vtkUnstructuredGrid.
  virtual vtkUnstructuredGrid *GetUnstructuredGridOutput();

  // Description:
  // Get the output as vtkRectilinearGrid.
  virtual vtkRectilinearGrid *GetRectilinearGridOutput();

  // Description:
  // Get the input data or filter.
  vtkDataSet *GetInput();

  // Description:
  // By default copy the output update extent to the input
  virtual void ComputeInputUpdateExtents( vtkDataObject *output );

  // Description:
  // Transform pipeline requests from executives into old-style
  // pipeline calls.  This works with the
  // vtkStreamingDemandDrivenPipeline executive to maintain backward
  // compatibility for filters written as subclasses of vtkSource.
  virtual int ProcessRequest(vtkInformation*,
                             vtkInformationVector**,
                             vtkInformationVector*);

protected:
  vtkDataSetToDataSetFilter();
  ~vtkDataSetToDataSetFilter();

  void ExecuteInformation();

  virtual int FillInputPortInformation(int, vtkInformation*);

  // This is called by the superclass.
  // This is the method you should override.
  virtual int RequestDataObject(vtkInformation* request,
                           vtkInformationVector** inputVector,
                           vtkInformationVector* outputVector);

private:
  vtkDataSetToDataSetFilter(const vtkDataSetToDataSetFilter&);  // Not implemented.
  void operator=(const vtkDataSetToDataSetFilter&);  // Not implemented.
};

#endif


text:
#ifndef __GATT_CLIENT_H__
#define __GATT_CLIENT_H__

#include "Gap.h"
#include "GattAttribute.h"
#include "ServiceDiscovery.h"

#include "GattCallbackParamTypes.h"

class GattClient {
public:
    typedef void (*ReadCallback_t)(const GattReadCallbackParams *params);

    enum WriteOp_t {
        GATT_OP_WRITE_REQ = 0x01,  /**< Write Request. */
        GATT_OP_WRITE_CMD = 0x02,  /**< Write Command. */
    };

    typedef void (*WriteCallback_t)(const GattWriteCallbackParams *params);

    typedef void (*HVXCallback_t)(const GattHVXCallbackParams *params);

    /*
     * The following functions are meant to be overridden in the platform-specific sub-class.
     */
public:
    /**
     * Launch service discovery. Once launched, application callbacks will be
     * invoked for matching services/characteristics. isServiceDiscoveryActive()
     * can be used to determine status; and a termination callback (if setup)
     * will be invoked at the end. Service discovery can be terminated prematurely
     * if needed using terminateServiceDiscovery().
     *
     * @param  connectionHandle
     *           Handle for the connection with the peer.
     * @param  sc
     *           This is the application callback for matching service. Taken as
     *           NULL by default. Note: service discovery may still be active
     *           when this callback is issued; calling asynchronous BLE-stack
     *           APIs from within this application callback might cause the
     *           stack to abort service discovery. If this becomes an issue, it
     *           may be better to make local copy of the discoveredService and
     *           wait for service discovery to terminate before operating on the
     *           service.
     * @param  cc
     *           This is the application callback for matching characteristic.
     *           Taken as NULL by default. Note: service discovery may still be
     *           active when this callback is issued; calling asynchronous
     *           BLE-stack APIs from within this application callback might cause
     *           the stack to abort service discovery. If this becomes an issue,
     *           it may be better to make local copy of the discoveredCharacteristic
     *           and wait for service discovery to terminate before operating on the
     *           characteristic.
     * @param  matchingServiceUUID
     *           UUID based filter for specifying a service in which the application is
     *           interested. By default it is set as the wildcard UUID_UNKNOWN,
     *           in which case it matches all services. If characteristic-UUID
     *           filter (below) is set to the wildcard value, then a service
     *           callback will be invoked for the matching service (or for every
     *           service if the service filter is a wildcard).
     * @param  matchingCharacteristicUUIDIn
     *           UUID based filter for specifying characteristic in which the application
     *           is interested. By default it is set as the wildcard UUID_UKNOWN
     *           to match against any characteristic. If both service-UUID
     *           filter and characteristic-UUID filter are used with non- wildcard
     *           values, then only a single characteristic callback is
     *           invoked for the matching characteristic.
     *
     * @note     Using wildcard values for both service-UUID and characteristic-
     *           UUID will result in complete service discovery--callbacks being
     *           called for every service and characteristic.
     *
     * @note     Providing NULL for the characteristic callback will result in
     *           characteristic discovery being skipped for each matching
     *           service. This allows for an inexpensive method to discover only
     *           services.
     *
     * @return
     *           BLE_ERROR_NONE if service discovery is launched successfully; else an appropriate error.
     */
    virtual ble_error_t launchServiceDiscovery(Gap::Handle_t                               connectionHandle,
                                               ServiceDiscovery::ServiceCallback_t         sc                           = NULL,
                                               ServiceDiscovery::CharacteristicCallback_t  cc                           = NULL,
                                               const UUID                                 &matchingServiceUUID          = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN),
                                               const UUID                                 &matchingCharacteristicUUIDIn = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) {
        /* avoid compiler warnings about unused variables */
        (void)connectionHandle;
        (void)sc;
        (void)cc;
        (void)matchingServiceUUID;
        (void)matchingCharacteristicUUIDIn;

        return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
    }

    /**
     * Launch service discovery for services. Once launched, service discovery will remain
     * active with service-callbacks being issued back into the application for matching
     * services. isServiceDiscoveryActive() can be used to
     * determine status; and a termination callback (if setup) will be invoked
     * at the end. Service discovery can be terminated prematurely if needed
     * using terminateServiceDiscovery().
     *
     * @param  connectionHandle
     *           Handle for the connection with the peer.
     * @param  sc
     *           This is the application callback for matching service. Note: service discovery may still be active
     *           when this callback is issued; calling asynchronous BLE-stack
     *           APIs from within this application callback might cause the
     *           stack to abort service discovery. If this becomes an issue, it
     *           may be better to make local copy of the discoveredService and
     *           wait for service discovery to terminate before operating on the
     *           service.
     * @param  matchingServiceUUID
     *           UUID based filter for specifying a service in which the application is
     *           interested. By default it is set as the wildcard UUID_UNKNOWN,
     *           in which case it matches all services.
     *
     * @return
     *           BLE_ERROR_NONE if service discovery is launched successfully; else an appropriate error.
     */
    virtual ble_error_t discoverServices(Gap::Handle_t                        connectionHandle,
                                         ServiceDiscovery::ServiceCallback_t  callback,
                                         const UUID                          &matchingServiceUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) {
        return launchServiceDiscovery(connectionHandle, callback, NULL, matchingServiceUUID); /* We take advantage of the property
                                                                * that providing NULL for the characteristic callback will result in
                                                                * characteristic discovery being skipped for each matching
                                                                * service. This allows for an inexpensive method to discover only
                                                                * services. Porter(s) are free to override this. */
    }

    /**
     * Launch service discovery for services. Once launched, service discovery will remain
     * active with service-callbacks being issued back into the application for matching
     * services. isServiceDiscoveryActive() can be used to
     * determine status; and a termination callback (if setup) will be invoked
     * at the end. Service discovery can be terminated prematurely if needed
     * using terminateServiceDiscovery().
     *
     * @param  connectionHandle
     *           Handle for the connection with the peer.
     * @param  sc
     *           This is the application callback for matching service. Note: service discovery may still be active
     *           when this callback is issued; calling asynchronous BLE-stack
     *           APIs from within this application callback might cause the
     *           stack to abort service discovery. If this becomes an issue, it
     *           may be better to make local copy of the discoveredService and
     *           wait for service discovery to terminate before operating on the
     *           service.
     * @param  startHandle, endHandle
     *           Handle range within which to limit the search
     *
     * @return
     *           BLE_ERROR_NONE if service discovery is launched successfully; else an appropriate error.
     */
    virtual ble_error_t discoverServices(Gap::Handle_t                        connectionHandle,
                                         ServiceDiscovery::ServiceCallback_t  callback,
                                         GattAttribute::Handle_t              startHandle,
                                         GattAttribute::Handle_t              endHandle) {
        /* avoid compiler warnings about unused variables */
        (void)connectionHandle;
        (void)callback;
        (void)startHandle;
        (void)endHandle;

        return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
    }

    /**
     * Is service-discovery currently active?
     */
    virtual bool isServiceDiscoveryActive(void) const {
        return false; /* Requesting action from porter(s): override this API if this capability is supported. */
    }

    /**
     * Terminate an ongoing service-discovery. This should result in an
     * invocation of the TerminationCallback if service-discovery is active.
     */
    virtual void terminateServiceDiscovery(void) {
        /* Requesting action from porter(s): override this API if this capability is supported. */
    }

    /* Initiate a Gatt Client read procedure by attribute-handle. */
    virtual ble_error_t read(Gap::Handle_t connHandle, GattAttribute::Handle_t attributeHandle, uint16_t offset) const {
        /* avoid compiler warnings about unused variables */
        (void)connHandle;
        (void)attributeHandle;
        (void)offset;

        return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
    }

    /**
     * Initiate a GATT Client write procedure.
     *
     * @param[in] cmd
     *              Command can be either a write-request (which generates a
     *              matching response from the peripheral), or a write-command,
     *              which doesn't require the connected peer to respond.
     * @param[in] connHandle
     *              Connection handle.
     * @param[in] attributeHandle
     *              handle for the target attribtue on the remote GATT server.
     * @param[in] length
     *              length of the new value.
     * @param[in] value
     *              new value being written.
     */
    virtual ble_error_t write(GattClient::WriteOp_t    cmd,
                              Gap::Handle_t            connHandle,
                              GattAttribute::Handle_t  attributeHandle,
                              size_t                   length,
                              const uint8_t           *value) const {
        /* avoid compiler warnings about unused variables */
        (void)cmd;
        (void)connHandle;
        (void)attributeHandle;
        (void)length;
        (void)value;

        return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
    }

    /* Event callback handlers. */
public:
    /**
     * Setup a callback for read response events.
     */
    void onDataRead(ReadCallback_t callback) {
        onDataReadCallback = callback;
    }

    /**
     * Setup a callback for write response events.
     * @Note: write commands (issued using writeWoResponse) don't generate a response.
     */
    void onDataWrite(WriteCallback_t callback) {
        onDataWriteCallback = callback;
    }

    /**
     * Setup callback for when serviceDiscovery terminates.
     */
    virtual void onServiceDiscoveryTermination(ServiceDiscovery::TerminationCallback_t callback) {
        (void)callback; /* avoid compiler warnings about ununsed variables */

        /* Requesting action from porter(s): override this API if this capability is supported. */
    }

    /**
     * Setup a callback for when GattClient receives an update event
     * corresponding to a change in value of a characteristic on the remote
     * GattServer.
     */
    void onHVX(HVXCallback_t callback) {
        onHVXCallback = callback;
    }

protected:
    GattClient() {
        /* empty */
    }

    /* Entry points for the underlying stack to report events back to the user. */
public:
    void processReadResponse(const GattReadCallbackParams *params) {
        if (onDataReadCallback) {
            onDataReadCallback(params);
        }
    }

    void processWriteResponse(const GattWriteCallbackParams *params) {
        if (onDataWriteCallback) {
            onDataWriteCallback(params);
        }
    }

    void processHVXEvent(const GattHVXCallbackParams *params) {
        if (onHVXCallback) {
            onHVXCallback(params);
        }
    }

protected:
    ReadCallback_t  onDataReadCallback;
    WriteCallback_t onDataWriteCallback;
    HVXCallback_t   onHVXCallback;

private:
    /* disallow copy and assignment */
    GattClient(const GattClient &);
    GattClient& operator=(const GattClient &);
};

#endif // ifndef __GATT_CLIENT_H__


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ethier.alex.core.processor;

import ethier.alex.core.data.Bit;
import ethier.alex.core.data.BitList;
import ethier.alex.core.data.Matches;
import ethier.alex.core.data.Partition;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.log4j.Logger;

/**

 @author alex
 */
public class SimpleProcessor {

    private static Logger logger = Logger.getLogger(SimpleProcessor.class);

    private Collection<Partition> incompletePartitions;
    private Collection<BitList> finalCombinations;

    public SimpleProcessor(Partition myPartition) {
        incompletePartitions = new ArrayList<Partition>();
        incompletePartitions.add(myPartition);
        finalCombinations = new ArrayList<BitList>();
    }

    public SimpleProcessor(Collection<Partition> myPartitions) {
        incompletePartitions = myPartitions;
        finalCombinations = new ArrayList<BitList>();
    }

    public Collection<BitList> getCompletedPartitions() {
        return finalCombinations;
    }

    public void runAll() {
        while(incompletePartitions.size() > 0) {
            this.runSet();
        }
    }

    public void runSet() {
        logger.debug("Processing " + incompletePartitions.size() + " partitions");
        Collection<Partition> newPartitionSet = new ArrayList<Partition>();

        Iterator<Partition> it = incompletePartitions.iterator();
        while(it.hasNext()) {
            Partition partition = it.next();
            if(partition.getCombination().hasSplit()) {
                Collection<Partition> splitPartitions = this.splitPartition(partition);
                newPartitionSet.addAll(splitPartitions);
            } else {
                finalCombinations.add(partition.getCombination());
            }

            it.remove();
        }

        logger.debug(newPartitionSet.size() + " new incomplete partitions created.");
        incompletePartitions = newPartitionSet;
    }

    public Collection<Partition> splitPartition(Partition partition) {
        logger.debug("Splitting partition with combination: " + partition.getCombination());

        Collection<Partition> newPartitions = new ArrayList<Partition>();

        BitList combination = partition.getCombination();

        BitList[] bitLists = combination.getSplits();

        BitList zeroList = bitLists[0];
        BitList oneList = bitLists[1];

        Collection<BitList> filters = partition.getFilters();
        int splitIndex = combination.getSplitIndex();

        Collection<BitList> zeroFilters = new ArrayList<BitList>();
        Collection<BitList> oneFilters = new ArrayList<BitList>();

        boolean allBothFilters = true;
        for(BitList filter : filters) {
            Bit filterBit = filter.getBitArray()[splitIndex];
            if(filterBit == Bit.BOTH) {
                zeroFilters.add(filter);
                oneFilters.add(filter);
            } else if(filterBit == Bit.ZERO) {
                zeroFilters.add(filter);
                allBothFilters = false;
            } else if(filterBit == Bit.ONE) {
                oneFilters.add(filter);
                allBothFilters = false;
            }
        }

        // In the special case that all filters contain a '*' then we don't need to return two splits.
        if(allBothFilters) {
            zeroList.getBitArray()[splitIndex] = Bit.BOTH;
            Partition bothPartition = new Partition(zeroList, zeroFilters);

            if(!matchExists(bothPartition)) {
                newPartitions.add(bothPartition);
            }

        } else {

            Partition zeroPartition = new Partition(zeroList, zeroFilters);
            Partition onePartition = new Partition(oneList, oneFilters);

            if(!matchExists(zeroPartition)) {
                newPartitions.add(zeroPartition);
            }

            if(!matchExists(onePartition)) {
                newPartitions.add(onePartition);
            }
        }

        for(Partition newPartition : newPartitions) {
            if(newPartition.verifyIntegrity() == false) {
                logger.error("Integrity not maintained for partition: "  + newPartition.getCombination());
            } else {
                logger.debug("New Partition: " + newPartition.getCombination());
            }
        }

        return newPartitions;
    }

    private boolean matchExists(Partition partition) {

        BitList combination = partition.getCombination();

        for(BitList filter : partition.getFilters()) {
            Matches matchOutcome = combination.getMatch(filter);

            if(matchOutcome == Matches.ENTIRELY) {
                return true;
            }
        }

        return false;
    }
}


text:
set -ex

sudo apt-get update
sudo apt-get install -y --no-install-recommends tdsodbc unixodbc-dev

set +ex


text:
/*
 * @test
 * @bug 6402062 6487891
 * @summary Tests SoftBevelBorder encoding
 * @author Sergey Malenkov
 */

import java.awt.Color;
import javax.swing.border.BevelBorder;
import javax.swing.border.SoftBevelBorder;

public final class javax_swing_border_SoftBevelBorder extends AbstractTest<SoftBevelBorder> {
    public static void main(String[] args) {
        new javax_swing_border_SoftBevelBorder().test(true);
    }

    protected SoftBevelBorder getObject() {
        return new SoftBevelBorder(BevelBorder.RAISED, Color.RED, Color.GREEN, Color.BLUE, Color.WHITE);
    }

    protected SoftBevelBorder getAnotherObject() {
        return null; // TODO: could not update property
        // return new SoftBevelBorder(BevelBorder.LOWERED);
    }
}


text:
require_relative 'carriage.rb'

class CargoCarriage < Carriage
  def initialize
    @type = :cargo
  end
end


text:
NSString *TDJSStringGetNSString(JSStringRef str) {
    return [(id)JSStringCopyCFString(NULL, str) autorelease];
}

JSStringRef TDJSStringCreateWithNSString(NSString *nsstring) {
    return JSStringCreateWithCFString((CFStringRef)nsstring);
}

JSValueRef TDCFTypeToJSValue(JSContextRef ctx, CFTypeRef value, JSValueRef *ex) {
    JSValueRef result = NULL;
    CFTypeID typeID = CFGetTypeID(value);

    if (CFNumberGetTypeID() == typeID) {
        double d;
        CFNumberGetValue(value, kCFNumberDoubleType, &d);
        result = JSValueMakeNumber(ctx, d);
    } else if (CFBooleanGetTypeID() == typeID) {
        Boolean b = CFBooleanGetValue(value);
        result = JSValueMakeBoolean(ctx, b);
    } else if (CFStringGetTypeID() == typeID) {
        result = TDCFStringToJSValue(ctx, value, ex);
    } else if (CFArrayGetTypeID() == typeID) {
        result = TDCFArrayToJSObject(ctx, value, ex);
    } else if (CFDictionaryGetTypeID() == typeID) {
        result = TDCFDictionaryToJSObject(ctx, value, ex);
    } else {
        result = JSValueMakeNull(ctx);
    }

    return result;
}

JSValueRef TDCFStringToJSValue(JSContextRef ctx, CFStringRef cfStr, JSValueRef *ex) {
    JSStringRef str = JSStringCreateWithCFString(cfStr);
    JSValueRef result = JSValueMakeString(ctx, str);
    JSStringRelease(str);
    return result;
}

JSValueRef TDNSStringToJSValue(JSContextRef ctx, NSString *nsStr, JSValueRef *ex) {
    return TDCFStringToJSValue(ctx, (CFStringRef)nsStr, ex);
}

JSObjectRef TDCFArrayToJSObject(JSContextRef ctx, CFArrayRef cfArray, JSValueRef *ex) {
    JSObjectRef globalObj = JSContextGetGlobalObject(ctx);
    JSStringRef className = JSStringCreateWithUTF8CString("Array");
    JSObjectRef arrayConstr = (JSObjectRef)JSObjectGetProperty(ctx, globalObj, className, NULL);
    JSStringRelease(className);

    JSObjectRef obj = (JSObjectRef)JSObjectCallAsConstructor(ctx, arrayConstr, 0, NULL, NULL);

    CFIndex len = 0;
    if (NULL != cfArray) {
        len = CFArrayGetCount(cfArray);
    }

    CFIndex i = 0;
    for ( ; i < len; i++) {
        CFTypeRef value = CFArrayGetValueAtIndex(cfArray, i);
        JSValueRef propVal = TDCFTypeToJSValue(ctx, value, ex);
        JSObjectSetPropertyAtIndex(ctx, obj, (unsigned int)i, propVal, NULL);
    }

    return obj;
}

JSObjectRef TDNSArrayToJSObject(JSContextRef ctx, NSArray *nsArray, JSValueRef *ex) {
    return TDCFArrayToJSObject(ctx, (CFArrayRef)nsArray, ex);
}

JSObjectRef TDCFDictionaryToJSObject(JSContextRef ctx, CFDictionaryRef cfDict, JSValueRef *ex) {
    JSObjectRef globalObj = JSContextGetGlobalObject(ctx);
    JSStringRef className = JSStringCreateWithUTF8CString("Object");
    JSObjectRef objConstr = (JSObjectRef)JSObjectGetProperty(ctx, globalObj, className, NULL);
    JSStringRelease(className);

    JSObjectRef obj = (JSObjectRef)JSObjectCallAsConstructor(ctx, objConstr, 0, NULL, NULL);

    if (NULL != cfDict) {
        CFIndex len = CFDictionaryGetCount(cfDict);
        CFStringRef keys[len];
        CFTypeRef values[len];
        CFDictionaryGetKeysAndValues(cfDict, (const void**)keys, (const void**)values);

        CFIndex i = 0;
        for ( ; i < len; i++) {
            CFStringRef key = keys[i];
            CFTypeRef value = values[i];

            JSStringRef propName = JSStringCreateWithCFString(key);
            JSValueRef propVal = TDCFTypeToJSValue(ctx, value, ex);
            JSObjectSetProperty(ctx, obj, propName, propVal, kJSPropertyAttributeNone, NULL);
            JSStringRelease(propName);
        }
    }

    return obj;
}

JSObjectRef TDNSDictionaryToJSObject(JSContextRef ctx, NSDictionary *nsDict, JSValueRef *ex) {
    return TDCFDictionaryToJSObject(ctx, (CFDictionaryRef)nsDict, ex);
}

CFTypeRef TDJSValueCopyCFType(JSContextRef ctx, JSValueRef value, JSValueRef *ex) {
    CFTypeRef result = NULL;

    if (JSValueIsBoolean(ctx, value)) {
        Boolean b = JSValueToBoolean(ctx, value);
        result = (b ? kCFBooleanTrue : kCFBooleanFalse);
    } else if (JSValueIsNull(ctx, value)) {
        result = NULL;
    } else if (JSValueIsNumber(ctx, value)) {
        CGFloat d = JSValueToNumber(ctx, value, NULL);
        result = CFNumberCreate(NULL, kCFNumberCGFloatType, &d);
    } else if (JSValueIsString(ctx, value)) {
        result = TDJSValueCopyCFString(ctx, value, ex);
    } else if (JSValueIsObject(ctx, value)) {
        if (TDJSValueIsInstanceOfClass(ctx, value, "Array", NULL)) {
            result = TDJSObjectCopyCFArray(ctx, (JSObjectRef)value, ex);
        } else {
            result = TDJSObjectCopyCFDictionary(ctx, (JSObjectRef)value, ex);
        }
    }

    return result;
}

id TDJSValueGetId(JSContextRef ctx, JSValueRef value, JSValueRef *ex) {
    return [(id)TDJSValueCopyCFType(ctx, value, ex) autorelease];
}

CFStringRef TDJSValueCopyCFString(JSContextRef ctx, JSValueRef value, JSValueRef *ex) {
    JSStringRef str = JSValueToStringCopy(ctx, value, ex);
    CFStringRef result = JSStringCopyCFString(NULL, str);
    JSStringRelease(str);
    return result;
}

NSString *TDJSValueGetNSString(JSContextRef ctx, JSValueRef value, JSValueRef *ex) {
    return [(id)TDJSValueCopyCFString(ctx, value, ex) autorelease];
}

CFArrayRef TDJSObjectCopyCFArray(JSContextRef ctx, JSObjectRef obj, JSValueRef *ex) {
    JSStringRef propName = JSStringCreateWithUTF8CString("length");
    JSValueRef propVal = JSObjectGetProperty(ctx, obj, propName, NULL);
    JSStringRelease(propName);
    CFIndex len = (CFIndex)JSValueToNumber(ctx, propVal, NULL);

    CFMutableArrayRef cfArray = CFArrayCreateMutable(NULL, len, NULL);

    CFIndex i = 0;
    for ( ; i < len; i++) {
        JSValueRef val = JSObjectGetPropertyAtIndex(ctx, obj, (unsigned int)i, NULL);
        CFTypeRef cfType = TDJSValueCopyCFType(ctx, val, ex);
        CFArraySetValueAtIndex(cfArray, i, cfType);

        CFRelease(cfType);
    }

    CFArrayRef result = CFArrayCreateCopy(NULL, cfArray);
    CFRelease(cfArray);

    return result;
}

CFDictionaryRef TDJSObjectCopyCFDictionary(JSContextRef ctx, JSObjectRef obj, JSValueRef *ex) {
    JSPropertyNameArrayRef propNames = JSObjectCopyPropertyNames(ctx, obj);
    CFIndex len = JSPropertyNameArrayGetCount(propNames);

    CFMutableDictionaryRef cfDict = CFDictionaryCreateMutable(NULL, len, NULL, NULL);

    CFIndex i = 0;
    for ( ; i < len; i++) {
        JSStringRef propName = JSPropertyNameArrayGetNameAtIndex(propNames, i);
        JSValueRef val = JSObjectGetProperty(ctx, obj, propName, NULL);
        CFTypeRef cfType = TDJSValueCopyCFType(ctx, val, ex);

        CFStringRef key = JSStringCopyCFString(NULL, propName);
        CFDictionarySetValue(cfDict, (const void *)key, (const void *)cfType);

        CFRelease(key);
        CFRelease(cfType);
    }

    JSPropertyNameArrayRelease(propNames);
    CFDictionaryRef result = CFDictionaryCreateCopy(NULL, cfDict);
    CFRelease(cfDict);

    return result;
}

JSObjectRef TDNSErrorToJSObject(JSContextRef ctx, NSError *nsErr, JSValueRef *ex) {
    JSObjectRef globalObj = JSContextGetGlobalObject(ctx);
    JSStringRef className = JSStringCreateWithUTF8CString("Error");
    JSObjectRef errConstr = (JSObjectRef)JSObjectGetProperty(ctx, globalObj, className, ex);
    JSStringRelease(className);

    JSObjectRef obj = (JSObjectRef)JSObjectCallAsConstructor(ctx, errConstr, 0, NULL, ex);

    if (nsErr) {
        JSStringRef nameStr = JSStringCreateWithUTF8CString("ParseKitError");
        JSValueRef name = JSValueMakeString(ctx, nameStr);
        JSStringRelease(nameStr);

        JSStringRef msgStr = JSStringCreateWithCFString((CFStringRef)[nsErr localizedDescription]);
        JSValueRef msg = JSValueMakeString(ctx, msgStr);
        JSStringRelease(msgStr);

        JSValueRef code = JSValueMakeNumber(ctx, [nsErr code]);

        JSStringRef propName = JSStringCreateWithUTF8CString("name");
        JSObjectSetProperty(ctx, obj, propName, name, kJSPropertyAttributeReadOnly|kJSPropertyAttributeDontDelete, ex);
        JSStringRelease(propName);

        propName = JSStringCreateWithUTF8CString("message");
        JSObjectSetProperty(ctx, obj, propName, msg, kJSPropertyAttributeReadOnly|kJSPropertyAttributeDontDelete, ex);
        JSStringRelease(propName);

        propName = JSStringCreateWithUTF8CString("code");
        JSObjectSetProperty(ctx, obj, propName, code, kJSPropertyAttributeReadOnly|kJSPropertyAttributeDontDelete, ex);
        JSStringRelease(propName);
    }

    return obj;
}

bool TDJSValueIsInstanceOfClass(JSContextRef ctx, JSValueRef value, char *className, JSValueRef* ex) {
    JSObjectRef globalObj = JSContextGetGlobalObject(ctx);
    JSStringRef classNameStr = JSStringCreateWithUTF8CString(className);
    JSObjectRef constr = (JSObjectRef)JSObjectGetProperty(ctx, globalObj, classNameStr, ex);
    JSStringRelease(classNameStr);

    return JSValueIsInstanceOfConstructor(ctx, value, constr, NULL);
}

JSValueRef TDEvaluateScript(JSGlobalContextRef ctx, NSString *script, NSString *sourceURLString, NSString **outErrMsg) {
    JSValueRef result = NULL;

    // get context
    if (!ctx) {
        ctx = JSGlobalContextCreate(NULL);
    }

    JSStringRef scriptStr = JSStringCreateWithCFString((CFStringRef)script);

    // setup source url string
    JSStringRef sourceURLStr = NULL;
    if ([sourceURLString length]) {
        sourceURLStr = JSStringCreateWithCFString((CFStringRef)sourceURLString);
    }

    // check syntax
    JSValueRef e = NULL;
    JSCheckScriptSyntax(ctx, scriptStr, sourceURLStr, 0, &e);

    // if syntax error...
    if (e) {
        if (outErrMsg) {
            NSString *msg = TDJSValueGetNSString(ctx, e, NULL);
            *outErrMsg = [NSString stringWithFormat:NSLocalizedString(@"JavaScript syntax error:\n\n%@", @""), msg];
            NSLog(@"%@", *outErrMsg);
        }
        goto done;
    }

    // eval the script
    result = JSEvaluateScript(ctx, scriptStr, NULL, sourceURLStr, 0, &e);
    if (e) {
        if (outErrMsg) {
            NSString *msg = TDJSValueGetNSString(ctx, e, NULL);
            *outErrMsg = [NSString stringWithFormat:NSLocalizedString(@"JavaScript runtime error:\n\n%@", @""), msg];
            NSLog(@"%@", *outErrMsg);
        }
        goto done;
    }

    // memory management
done:
    if (scriptStr) JSStringRelease(scriptStr);
    if (sourceURLStr) JSStringRelease(sourceURLStr);

    return result;
}

BOOL TDBooleanForScript(JSGlobalContextRef ctx, NSString *script, NSString *sourceURLString, NSString **outErrMsg) {
    // wrap source in boolean cast
    NSString *fmt = @"(function(){return Boolean(%@)})();";
    script = [NSString stringWithFormat:fmt, script];

    JSValueRef res = TDEvaluateScript(ctx, script, sourceURLString, outErrMsg);

    // convert result to boolean
    BOOL result = NO;
    if (res) {
        result = JSValueToBoolean(ctx, res);
    }

    return result;
}


text:
package net.jforum.entities;

/**
 * @author Rafael Steil
 * @version $Id$
 */
public class QuotaLimit
{
	public static final int KB = 1;
	public static final int MB = 2;

	private int id;
	private String description;
	private int size;
	private int type;

	/**
	 * Checks if the size passed as argument
	 * is greater than the quota's limit.
	 *
	 * @param size The size to check
	 * @return true if the size is greater than
	 * quota's limit.
	 */
	public boolean exceedsQuota(long size)
	{
		if (this.type == QuotaLimit.KB) {
			return (size > this.size * 1024);
		}

		return (size > this.size * 1024L * 1024);
	}

	public int getSizeInBytes()
	{
		if (this.type == QuotaLimit.KB) {
			return (this.size * 1024);
		}

		return (this.size * 1024 * 1024);
	}

	/**
	 * @return Returns the description.
	 */
	public String getDescription()
	{
		return this.description;
	}

	/**
	 * @param description The description to set.
	 */
	public void setDescription(String description)
	{
		this.description = description;
	}

	/**
	 * @return Returns the id.
	 */
	public int getId()
	{
		return this.id;
	}

	/**
	 * @param id The id to set.
	 */
	public void setId(int id)
	{
		this.id = id;
	}

	/**
	 * @return Returns the size.
	 */
	public int getSize()
	{
		return this.size;
	}

	/**
	 * @param size The size to set.
	 */
	public void setSize(int size)
	{
		this.size = size;
	}

	/**
	 * @return Returns the type.
	 */
	public int getType()
	{
		return this.type;
	}

	/**
	 * @param type The type to set.
	 */
	public void setType(int type)
	{
		this.type = type;
	}
}


text:
namespace System.ComponentModel.DataAnnotations.Schema
{
    /// <summary>
    /// Denotes that a property or class should be excluded from database mapping.
    /// </summary>
    [Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class, AllowMultiple = false)]
    [Bridge.External]
    [Bridge.NonScriptable]
    public class NotMappedAttribute : Attribute { }
}