text:
<!DOCTYPE html>

    <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
  File: README

    — Documentation by YARD 0.9.10

</title>

  <link rel="stylesheet" href="css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="css/common.css" type="text/css" charset="utf-8" />

    Index »
    File: README

        <svg width="24" height="24">
          <rect x="0" y="4" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="12" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="20" width="24" height="4" rx="1" ry="1"></rect>
        </svg>

rabbitmq

Table of Contents

Overview

Module Description - What the module does and why it is useful

Setup - The basics of getting started with rabbitmq

What rabbitmq affects

Setup requirements

Usage - Configuration options and additional functionality

Reference - An under-the-hood peek at what the module is doing and how

Limitations - OS compatibility, etc.

RedHat module dependencies

Development - Guide for contributing to the module

Overview

This module manages RabbitMQ (www.rabbitmq.com)

Module Description

The rabbitmq module sets up rabbitmq and has a number of providers to manage
everything from vhosts to exchanges after setup.

This module has been tested against 3.5.x and 3.6.x (as well as earlier
versions) and is known to not support all features against versions
prior to 2.7.1.

Setup

What rabbitmq affects

rabbitmq repository files.

rabbitmq package.

rabbitmq configuration file.

rabbitmq service.

Usage

All options and configuration can be done through interacting with the parameters
on the main rabbitmq class.
These are now documented via Puppet Strings

For convenience, some examples are duplicated here:

rabbitmq class

To begin with the rabbitmq class controls the installation of rabbitmq.  In here
you can control many parameters relating to the package and service, such as
disabling puppet support of the service:

class { 'rabbitmq':
  service_manage    => false,
  port              => '5672',
  delete_guest_user => true,
}

Environment Variables

To use RabbitMQ Environment Variables, use the parameters environment_variables e.g.:

class { 'rabbitmq':
  port                  => 5672,
  environment_variables => {
    'NODENAME'    => 'node01',
    'SERVICENAME' => 'RabbitMQ'
  }
}

Variables Configurable in rabbitmq.config

To change RabbitMQ Config Variables in rabbitmq.config, use the parameters config_variables e.g.:

class { 'rabbitmq':
  port             => 5672,
  config_variables => {
    'hipe_compile' => true,
    'frame_max'    => 131072,
    'log_levels'   => "[{connection, info}]"
  }
}

To change Erlang Kernel Config Variables in rabbitmq.config, use the parameters
config_kernel_variables e.g.:

class { 'rabbitmq':
  port                    => 5672,
  config_kernel_variables => {
    'inet_dist_listen_min' => 9100,
    'inet_dist_listen_max' => 9105,
  }
}

To change Management Plugin Config Variables in rabbitmq.config, use the parameters
config_management_variables e.g.:

class { 'rabbitmq':
  config_management_variables => {
    'rates_mode' => 'basic',
  }
}

Additional Variables Configurable in rabbitmq.config

To change Additional Config Variables in rabbitmq.config, use the parameter
config_additional_variables e.g.:

class { 'rabbitmq':
  config_additional_variables => {
    'autocluster' => '[{consul_service, "rabbit"},{cluster_name, "rabbit"}]',
    'foo'         => '[{bar, "baz"}]'
  }
}

This will result in the following config appended to the config file:

% Additional config
  {autocluster, [{consul_service, "rabbit"},{cluster_name, "rabbit"}]},
  {foo, [{bar, "baz"}]}

(This is required for the autocluster plugin

Clustering

To use RabbitMQ clustering facilities, use the rabbitmq parameters
config_cluster, cluster_nodes, and cluster_node_type, e.g.:

class { 'rabbitmq':
  config_cluster           => true,
  cluster_nodes            => ['rabbit1', 'rabbit2'],
  cluster_node_type        => 'ram',
  erlang_cookie            => 'A_SECRET_COOKIE_STRING',
  wipe_db_on_cookie_change => true,
}

rabbitmq_user

query all current users: $ puppet resource rabbitmq_user

rabbitmq_user { 'dan':
  admin    => true,
  password => 'bar',
}

Optional parameter tags will set further rabbitmq tags like monitoring, policymaker, etc.
To set the administrator tag use admin-flag.

rabbitmq_user { 'dan':
  admin    => true,
  password => 'bar',
  tags     => ['monitoring', 'tag1'],
}

rabbitmq_vhost

query all current vhosts: $ puppet resource rabbitmq_vhost

rabbitmq_vhost { 'myvhost':
  ensure => present,
}

rabbitmq_exchange

rabbitmq_exchange { 'myexchange@myvhost':
  ensure      => present,
  user        => 'dan',
  password    => 'bar',
  type        => 'topic',
  internal    => false,
  auto_delete => false,
  durable     => true,
  arguments   => {
    hash-header => 'message-distribution-hash'
  }
}

rabbitmq_queue

rabbitmq_queue { 'myqueue@myvhost':
  ensure      => present,
  user        => 'dan',
  password    => 'bar',
  durable     => true,
  auto_delete => false,
  arguments   => {
    x-message-ttl          => 123,
    x-dead-letter-exchange => 'other'
  },
}

rabbitmq_binding

rabbitmq_binding { 'myexchange@myqueue@myvhost':
  ensure           => present,
  user             => 'dan',
  password         => 'bar',
  destination_type => 'queue',
  routing_key      => '#',
  arguments        => {},
}

rabbitmq_binding { 'binding 1':
  ensure           => present,
  source           => 'myexchange',
  destination      => 'myqueue',
  vhost            => 'myvhost',
  user             => 'dan',
  password         => 'bar',
  destination_type => 'queue',
  routing_key      => 'key1',
  arguments        => {},
}

rabbitmq_binding { 'binding 2':
  ensure           => present,
  source           => 'myexchange',
  destination      => 'myqueue',
  vhost            => 'myvhost',
  user             => 'dan',
  password         => 'bar',
  destination_type => 'queue',
  routing_key      => 'key2',
  arguments        => {},
}

rabbitmq_user_permissions

rabbitmq_user_permissions { 'dan@myvhost':
  configure_permission => '.*',
  read_permission      => '.*',
  write_permission     => '.*',
}

rabbitmq_policy

rabbitmq_policy { 'ha-all@myvhost':
  pattern    => '.*',
  priority   => 0,
  applyto    => 'all',
  definition => {
    'ha-mode'      => 'all',
    'ha-sync-mode' => 'automatic',
  },
}

rabbitmq_plugin

query all currently enabled plugins $ puppet resource rabbitmq_plugin

rabbitmq_plugin {'rabbitmq_stomp':
  ensure => present,
}

rabbitmq_parameter

  rabbitmq_parameter { 'documentumShovel@/':
    component_name => '',
    value          => {
        'src-uri'    => 'amqp://',
        'src-queue'  => 'my-queue',
        'dest-uri'   => 'amqp://remote-server',
        'dest-queue' => 'another-queue',
    },
  }

  rabbitmq_parameter { 'documentumFed@/':
    component_name => 'federation-upstream',
    value          => {
        'uri'     => 'amqp://myserver',
        'expires' => '360000',
    },
  }

Reference

Classes

rabbitmq: Main class for installation and service management.

rabbitmq::config: Main class for rabbitmq configuration/management.

rabbitmq::install: Handles package installation.

rabbitmq::params: Different configuration data for different systems.

rabbitmq::service: Handles the rabbitmq service.

rabbitmq::repo::apt: Handles apt repo for Debian systems.

rabbitmq::repo::rhel: Handles rpm repo for Redhat systems.

Module dependencies

If running CentOS/RHEL, ensure the epel repo, or another repo containing a
suitable Erlang version, is present. On Debian systems, puppetlabs/apt
(>=2.0.0 < 5.0.0) is a soft dependency.

To have a suitable erlang version installed on RedHat and Debian systems,
you have to install another puppet module from http://forge.puppetlabs.com/garethr/erlang with:

puppet module install garethr-erlang

This module handles the packages for erlang.
To use the module, add the following snippet to your site.pp or an appropriate profile class:

For RedHat systems:

include 'erlang'
class { 'erlang': epel_enable => true}

For Debian systems:

include 'erlang'
package { 'erlang-base':
  ensure => 'latest',
}

This module also depends on voxpupuli/archive to install rabbitmqadmin.

Development

This module is maintained by Vox Pupuli. Voxpupuli
welcomes new contributions to this module, especially those that include
documentation and rspec tests. We are happy to provide guidance if necessary.

Please see CONTRIBUTING for more details.

Authors

Jeff McCune jeff@puppetlabs.com

Dan Bode dan@puppetlabs.com

RPM/RHEL packages by Vincent Janelle randomfrequency@gmail.com

Puppetlabs Module Team

Voxpupuli Team

     Generated by yard.


text:
/* Implementation of arch_loadavginfo using the common but nonstandard
 * getloadavg. */

#include <Python.h>

#ifdef SUNOS
#include <sys/loadavg.h>
#else
#include <stdlib.h>
#endif

#include "psi.h"
#include "psifuncs.h"

struct loadavginfo *
arch_loadavginfo(void)
{
    struct loadavginfo *loadi;
    double avg[3];
    int r;

    r = getloadavg(avg, 3);
    if (r == -1) {
        PyErr_SetString(PyExc_OSError, "getloadavg() failed");
        return NULL;
    } else if (r < 3) {
        PyErr_Format(PyExc_OSError,
                     "getloadavg() only returned %d numbers (expected 3)", r);
        return NULL;
    }
    loadi = psi_calloc(sizeof(struct loadavginfo));
    if (loadi == NULL)
        return NULL;
    loadi->one = avg[0];
    loadi->five = avg[1];
    loadi->fifteen = avg[2];
    loadi->loadavg_status = PSI_STATUS_OK;
    return loadi;
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const jsonCopy = require('./json_copy');
const logger = require('./log');
const of = require('./object_factory');
const Pattern = of.Pattern;

let render = require('./render'); //eslint-disable-line prefer-const

/**
 * Builds footer HTML from the general footer and user-defined footer
 * @param patternlab - global data store
 * @param patternPartial - the partial key to build this for, either viewall-patternPartial or a viewall-patternGroup-all
 * @returns A promise which resolves with the HTML
 */
module.exports = function (patternlab, patternPartial, uikit) {
  //first render the general footer
  return render(Pattern.createEmpty({ extendedTemplate: uikit.footer }), {
    patternData: JSON.stringify({
      patternPartial: patternPartial,
    }),
    cacheBuster: patternlab.cacheBuster,
  })
    .then((footerPartial) => {
      let allFooterData;
      try {
        allFooterData = jsonCopy(
          patternlab.data,
          'config.paths.source.data plus patterns data'
        );
      } catch (err) {
        logger.error('There was an error parsing JSON for patternlab.data');
        logger.error(err);
      }
      allFooterData.patternLabFoot = footerPartial;

      return render(patternlab.userFoot, allFooterData);
    })
    .catch((reason) => {
      console.log(reason);
      logger.error('Error building buildFooterHTML');
    });
};


text:
/**
 * Class that represets a Component-type-ASTNode.
 *
 * @class ASTNodeComponent
 * @extends {ASTNode}
 */
declare class ASTNodeComponent extends ASTNode {
  /**
   * Component constructor.
   *
   * @type {ComponentClass}
   * @memberof ASTNodeComponent
   */
  ComponentCtor: ComponentClass

  /**
   * Component instance reference.
   *
   * @type {LC}
   * @memberof ASTNodeComponent
   */
  componentInstance: LC

  /**
   * Node type.
   *
   * @type {ASTNodeType}
   * @memberof ASTNodeComponent
   */
  nodeType: ASTNodeType

  /**
   * Props.
   *
   * @type {ASTNodeProps}
   * @memberof ASTNodeComponent
   */
  props: ASTNodeProps

  /**
   * Mount target component.
   *
   * @memberof ASTNodeComponent
   */
  mountComponent (): void

  /**
   * Unmuont target component.
   *
   * @memberof ASTNodeComponent
   */
  unMountComponent (): void

  /**
   * Update node by using new value.
   *
   * @param {string} [specificExpression]
   * @param {*} [newValue]
   * @memberof ASTNodeComponent
   */
  update (specificExpression?: string, newValue?: any): void

  constructor (param: IASTNodeComponent)
}

/**
 * ASTNodeComponent constructor param.
 *
 * @interface IASTNodeComponent
 * @extends {IASTNodeOption}
 */
interface IASTNodeComponent extends IASTNodeOption {
  ComponentCtor?: ComponentClass
  componentInstance?: LC
  props?: ASTNodeProps
}


text:
// <copyright file="Atkinson.cs" company="James Jackson-South">
// Copyright (c) James Jackson-South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>

namespace ImageSharp.Dithering
{
    using ImageSharp.Memory;

    /// <summary>
    /// Applies error diffusion based dithering using the Atkinson image dithering algorithm.
    /// <see href="http://www.efg2.com/Lab/Library/ImageProcessing/DHALF.TXT"/>
    /// </summary>
    public sealed class Atkinson : ErrorDiffuser
    {
        /// <summary>
        /// The diffusion matrix
        /// </summary>
        private static readonly Fast2DArray<float> AtkinsonMatrix =
            new float[,]
            {
               { 0, 0, 1, 1 },
               { 1, 1, 1, 0 },
               { 0, 1, 0, 0 }
            };

        /// <summary>
        /// Initializes a new instance of the <see cref="Atkinson"/> class.
        /// </summary>
        public Atkinson()
            : base(AtkinsonMatrix, 8)
        {
        }
    }
}


text:
from parsl.channels.errors import *
from parsl.channels.ssh.ssh import SSHChannel as SSH

def connect_and_list(hostname, username):
    conn = SSH(hostname, username=username)
    ec, out, err = conn.execute_wait("echo $HOSTNAME")
    conn.close()
    return out

def test_error_1():
    try:
        connect_and_list("bad.url.gov", "ubuntu")
    except Exception as e:
        assert type(e) == SSHException, "Excpected SSException, got :{0}".format(e)

def test_error_2():
    try:
        connect_and_list("swift.rcc.uchicago.edu", "mango")
    except SSHException:
        print("Caught the right exception")
    else:
        raise Exception("Expected SSException, got :{0}".format(e))

def test_error_3():
    ''' This should work
    '''
    try:
        connect_and_list("login.mcs.anl.gov", "yadunand")
    except AuthException as e:
        print("Caught exception : ", e)
    else:
        assert type(e) == BadHostKeyException, "Expected SSException, got :{0}".format(e)

def test_error_3():
    ''' This should work
    '''
    try:
        connect_and_list("edison.nersc.gov", "yadunand")
    except BadHostKeyException as e:
        print("Caught exception BadHostKeyException: ", e)
    else:
        assert False, "Expected SSException, got :{0}".format(e)

if __name__ == "__main__":

    tests = [test_error_1, test_error_2, test_error_3]

    for test in tests:
        print("---------Running : {0}---------------".format(test))
        test()
        print("----------------------DONE--------------------------")


text:
<?php

namespace Bolt\Storage\Database\Schema\Builder;

use Bolt\Logger\FlashLoggerInterface;
use Bolt\Storage\Database\Schema\Manager;
use Doctrine\DBAL\Connection;
use Pimple;
use Psr\Log\LoggerInterface;

/**
 * Base class for Bolt's table builders.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
abstract class BaseBuilder
{
    /** @var \Doctrine\DBAL\Connection */
    protected $connection;
    /** @var \Bolt\Storage\Database\Schema\Manager */
    protected $manager;
    /** @var \Pimple */
    protected $tables;
    /** @var string */
    protected $charset;
    /** @var string */
    protected $collate;
    /** @var \Psr\Log\LoggerInterface */
    protected $systemLog;
    /** @var \Bolt\Logger\FlashLoggerInterface */
    protected $flashLogger;

    /**
     * Constructor.
     *
     * @param Connection           $connection
     * @param Manager              $manager
     * @param Pimple               $tables
     * @param string               $charset
     * @param string               $collate
     * @param LoggerInterface      $systemLog
     * @param FlashLoggerInterface $flashLogger
     */
    public function __construct(Connection $connection, Manager $manager, Pimple $tables, $charset, $collate, LoggerInterface $systemLog, FlashLoggerInterface $flashLogger)
    {
        $this->connection = $connection;
        $this->manager = $manager;
        $this->tables = $tables;
        $this->charset = $charset;
        $this->collate = $collate;
        $this->systemLog = $systemLog;
        $this->flashLogger = $flashLogger;
    }
}


text:
/**
 * @author xiaojue
 * @email designsor@gmail.com
 * @fileoverview 进驻到系统服务中的常驻js脚本
 */
var server = require('./server/index');
var utils = require('./utils');

server.start(utils.noop);


text:
// Copyright NVIDIA Corporation 2013
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#pragma once

#include <dp/sg/xbar/culling/Config.h>
#include <dp/culling/Manager.h>
#include <dp/sg/xbar/SceneTree.h>

namespace dp
{
  namespace sg
  {
    namespace xbar
    {
      namespace culling
      {
        DEFINE_PTR_TYPES( Culling );
        DEFINE_PTR_TYPES( Result );

        class Result
        {
        public:
          DP_SG_XBAR_CULLING_API virtual ~Result();

        protected:
          DP_SG_XBAR_CULLING_API Result();
        };

        /** \brief This class provides culling on all GeoNodes in a SceneTree. It supports multiple viewports at the same time through the ResultSharedPtr.
                   After calling cull the function resultGetChangedIndices returns a list of ObjectTree indices with changed visibility. It is possible
                   to support multiple viewports by creating multiple results.
        **/
        class Culling
        {
        public:
          DP_SG_XBAR_CULLING_API virtual ~Culling();

          /** \brief Create a new Culling object for the given SceneTree **/
          DP_SG_XBAR_CULLING_API static CullingSharedPtr create( SceneTreeSharedPtr const& sceneTree, dp::culling::Mode cullingMode );

          /** \brief Create a culling result. This handle contains the visibility of all objects in the SceneTree **/
          DP_SG_XBAR_CULLING_API virtual ResultSharedPtr resultCreate() = 0;

          /** \brief Check if an object was visible during the last cull call **/
          DP_SG_XBAR_CULLING_API virtual bool resultIsVisible( ResultSharedPtr const & result, ObjectTreeIndex objectTreeIndex ) const = 0;

          /** \brief Get the list of ObjectTree indices whose visibility has changed during the last cull call **/
          DP_SG_XBAR_CULLING_API virtual std::vector<dp::sg::xbar::ObjectTreeIndex> const & resultGetChangedIndices( ResultSharedPtr const & ) const = 0;

          /** \brief Cull the SceneTree against the given world2ViewProjection matrix and update the given result **/
          DP_SG_XBAR_CULLING_API virtual void cull( ResultSharedPtr const& result, dp::math::Mat44f const & world2ViewProjection ) = 0;

          /** \brief Calculate the bounding box of the SceneTree. Currently all active and inactive objects are used to calculate the result **/
          DP_SG_XBAR_CULLING_API virtual dp::math::Box3f getBoundingBox( ) = 0;
        };

      } // namespace culling
    } // namespace xbar
  } // namespace sg
} // namespace dp


text:
import { Component, AfterViewInit, trigger, style, transition, animate } from '@angular/core';
import { AnamnesisFormService } from './anamnesis-form.service';
import { BackendService } from '../shared/backend-service/backend-service';
import { Router } from '@angular/router';

declare var paypal: any;

class PaymentButtonConfig {
  env: any;
  style: any;
  commit: boolean;
  onAuthorize: any;
  payment: any;

  constructor(backendService: BackendService, fData: FormData, onPaymentSuccess: any) {
    this.env = 'sandbox'; // Specify 'sandbox' for the test environment
    this.style = {
      size: 'medium',
      color: 'silver',
      shape: 'rect'
    };
    this.commit = true;

    this.payment = (resolve: any, reject: any) => {
      // tried to use backendService.post here, but this caused errors in checkout.js
      paypal.request.post(backendService.backendURL + '/' + 'payment')
        .then(function (data: any) { console.log(data); resolve(data.paymentId); })
        .catch(function (err: any) { console.log(err); reject(err); });
    };

    this.onAuthorize = (data: any) => {
      let paymentSuccessFunc = onPaymentSuccess;

      console.log('append form data - payerId:' + data.payerID);
      fData.append('payerId', data.payerID);

      console.log('append form data - paymentId:' + data.paymentID);
      fData.append('paymentId', data.paymentID);

      backendService.post('payment-execute', fData).then(res => {
        console.log('Payment executed successfully');
        console.log(res);
        paymentSuccessFunc(JSON.parse(res._body).id);
      }).catch(err => { console.log(err); });
    };
  };
}

@Component({
  moduleId: module.id, // this is needed to correctly resolve paths to templateUrl and Css
  templateUrl: 'payment.component.html',
  selector: 'payment',
  animations: [
    trigger('isVisibleChanged', [
      transition('no => yes', [
        style({ opacity: 0 }),
        animate('0.3s ease-out', style({ opacity: 1 }))
      ]),
      transition('yes => no', [
        animate('0.3s ease-in', style({ opacity: 0 }))
      ])
    ])
  ]
})
export class PaymentComponent implements AfterViewInit {

  // for animation
  isVisible: string = 'no';

  constructor(private router: Router, private form: AnamnesisFormService, private bs: BackendService, ) { }

  ngAfterViewInit() {
    this.isVisible = 'yes';

    let backendService = this.bs;
    let r: Router = this.router;
    let formData = new FormData();
    formData.append('image1', this.form.image1);
    formData.append('image2', this.form.image2);
    formData.append('survey', JSON.stringify(this.form.survey));

    // the function to be executed on successfully authorized payment
    let onPaymentSuccessFunc = (paymentId: string) => {
      console.log('onPaymentSuccessFunc: ' + paymentId);
      r.navigate(['result', paymentId]);
    };

    // render payment button
    paypal.Button.render(new PaymentButtonConfig(backendService, formData, onPaymentSuccessFunc), '#paypal-button');
  }
}


text:
Subscribers
===========

The following variables are available in your templates:

* csrf_token
* csrf_token_field - though it contains the complete html, you may need to
  safe quote/raw the field. In Mako, ${csrf_token_field|n}
* flash methods are provided to access this for Mako/Jinja, but, if you
  want to access it directly, it is available.


text:
#include "hashblock.h"
#include <inttypes.h>

#include <jni.h>

/*jbyteArray JNICALL scryptN(JNIEnv *env, jclass cls, jbyteArray passwd, jbyteArray salt,
    jint N, jint r, jint p, jint dkLen)
{
    jint Plen = (*env)->GetArrayLength(env, passwd);
    jint Slen = (*env)->GetArrayLength(env, salt);
    jbyte *P = (*env)->GetByteArrayElements(env, passwd, NULL);
    jbyte *S = (*env)->GetByteArrayElements(env, salt, NULL);
    uint8_t *buf = malloc(sizeof(uint8_t) * dkLen);
    jbyteArray DK = NULL;

    if (P == NULL || S == NULL || buf == NULL) goto cleanup;

    if (crypto_scrypt((uint8_t *) P, Plen, (uint8_t *) S, Slen, N, r, p, buf, dkLen)) {
        jclass e = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
        char *msg;
        switch (errno) {
            case EINVAL:
                msg = "N must be a power of 2 greater than 1";
                break;
            case EFBIG:
            case ENOMEM:
                msg = "Insufficient memory available";
                break;
            default:
                msg = "Memory allocation failed";
        }
        (*env)->ThrowNew(env, e, msg);
        goto cleanup;
    }

    DK = (*env)->NewByteArray(env, dkLen);
    if (DK == NULL) goto cleanup;

    (*env)->SetByteArrayRegion(env, DK, 0, dkLen, (jbyte *) buf);

  cleanup:

    if (P) (*env)->ReleaseByteArrayElements(env, passwd, P, JNI_ABORT);
    if (S) (*env)->ReleaseByteArrayElements(env, salt, S, JNI_ABORT);
    if (buf) free(buf);

    return DK;
}*/

jbyteArray JNICALL hash9_native(JNIEnv *env, jclass cls, jbyteArray header)
{
    jint Plen = (env)->GetArrayLength(header);
    jbyte *P = (env)->GetByteArrayElements(header, NULL);
    //uint8_t *buf = malloc(sizeof(uint8_t) * dkLen);
    jbyteArray DK = NULL;

    if (P)
	{

	uint256 result = Hash9(P, P+Plen);

    /*if (crypto_scrypt((uint8_t *) P, Plen, (uint8_t *) S, Slen, N, r, p, buf, dkLen)) {
        jclass e = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
        char *msg;
        switch (errno) {
            case EINVAL:
                msg = "N must be a power of 2 greater than 1";
                break;
            case EFBIG:
            case ENOMEM:
                msg = "Insufficient memory available";
                break;
            default:
                msg = "Memory allocation failed";
        }
        (*env)->ThrowNew(env, e, msg);
        goto cleanup;
    }*/

    DK = (env)->NewByteArray(32);
    if (DK)
	{
		(env)->SetByteArrayRegion(DK, 0, 32, (jbyte *) result.begin());
	}

    if (P) (env)->ReleaseByteArrayElements(header, P, JNI_ABORT);
    //if (buf) free(buf);
	}
    return DK;
}

static const JNINativeMethod methods[] = {
    { "hash9_native", "([B)[B", (void *) hash9_native }
};

jint JNI_OnLoad(JavaVM *vm, void *reserved) {
    JNIEnv *env;

    if ((vm)->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
        return -1;
    }

    jclass cls = (env)->FindClass("hashengineering/quark/crypto/Hash9");
    int r = (env)->RegisterNatives(cls, methods, 1);

    return (r == JNI_OK) ? JNI_VERSION_1_6 : -1;
}