text:
package kstarchoi.recyclerviewbuilder;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import kstarchoi.lib.recyclerview.builder.DefaultViewBinder;
import kstarchoi.lib.recyclerview.builder.RecyclerViewBuilder;
import kstarchoi.lib.recyclerview.builder.ViewProvider;

/**
 * @author Gwangseong Choi
 * @since 2017-07-22
 */

public class MainActivity extends AppCompatActivity {

    private int mSelectableItemBackgroundRes = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        new RecyclerViewBuilder<ActivityInfo>(recyclerView)
                .setViewBinder(new DefaultViewBinder<ActivityInfo>() {
                    @Override
                    public void bind(ViewProvider provider, int index, ActivityInfo activityInfo) {
                        TextView textView = provider.get(android.R.id.text1);
                        textView.setText(activityInfo.getTitleResId());

                        View rootView = provider.getRoot();
                        rootView.setBackgroundResource(getSelectableItemBackgroundRes());

                        final Class<?> activityClass = activityInfo.getActivityClass();
                        rootView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(v.getContext(), activityClass);
                                startActivity(intent);
                            }
                        });
                    }
                })
                .addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
                .build(createActivityInfoList());
    }

    private List<ActivityInfo> createActivityInfoList() {
        List<ActivityInfo> activityInfoList = new ArrayList<>();
        activityInfoList.add(new ActivityInfo(R.string.example_basic, BasicExampleActivity.class));
        activityInfoList.add(new ActivityInfo(R.string.example_data_control, DataControlExampleActivity.class));
        activityInfoList.add(new ActivityInfo(R.string.example_layout_manager, LayoutManagerExampleActivity.class));
        activityInfoList.add(new ActivityInfo(R.string.example_application, ApplicationExampleActivity.class));
        activityInfoList.add(new ActivityInfo(R.string.example_type_free, TypeFreeExampleActivity.class));
        return activityInfoList;
    }

    private int getSelectableItemBackgroundRes() {
        if (mSelectableItemBackgroundRes == -1) {
            TypedValue typedValue = new TypedValue();
            getTheme().resolveAttribute(R.attr.selectableItemBackground, typedValue, true);
            mSelectableItemBackgroundRes = typedValue.resourceId;
        }

        return mSelectableItemBackgroundRes;
    }

    private class ActivityInfo {

        private int mTitleResId;
        private Class<?> mActivityClass;

        ActivityInfo(@StringRes int titleResId, Class<?> activityClass) {
            mTitleResId = titleResId;
            mActivityClass = activityClass;
        }

        int getTitleResId() {
            return mTitleResId;
        }

        Class<?> getActivityClass() {
            return mActivityClass;
        }
    }
}


text:
/**
 * @file
 * Point To Point Protocol Sequential API module
 *
 */

/*
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 */

#include "netif/ppp/ppp_opts.h"

#if LWIP_PPP_API /* don't build if not configured for use in lwipopts.h */

#include "netif/ppp/pppapi.h"
#include "lwip/priv/tcpip_priv.h"
#include "netif/ppp/pppoe.h"
#include "netif/ppp/pppol2tp.h"
#include "netif/ppp/pppos.h"

#if LWIP_MPU_COMPATIBLE
LWIP_MEMPOOL_DECLARE(PPPAPI_MSG, MEMP_NUM_PPP_API_MSG, sizeof(struct pppapi_msg), "PPPAPI_MSG")
#endif

#define PPPAPI_VAR_REF(name)               API_VAR_REF(name)
#define PPPAPI_VAR_DECLARE(name)           API_VAR_DECLARE(struct pppapi_msg, name)
#define PPPAPI_VAR_ALLOC(name)             API_VAR_ALLOC_POOL(struct pppapi_msg, PPPAPI_MSG, name, ERR_MEM)
#define PPPAPI_VAR_ALLOC_RETURN_NULL(name) API_VAR_ALLOC_POOL(struct pppapi_msg, PPPAPI_MSG, name, NULL)
#define PPPAPI_VAR_FREE(name)              API_VAR_FREE_POOL(PPPAPI_MSG, name)

/**
 * Call ppp_set_default() inside the tcpip_thread context.
 */
static err_t
pppapi_do_ppp_set_default(struct tcpip_api_call_data *m)
{
  /* cast through void* to silence alignment warnings.
   * We know it works because the structs have been instantiated as struct pppapi_msg */
  struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;

  ppp_set_default(msg->msg.ppp);
  return ERR_OK;
}

/**
 * Call ppp_set_default() in a thread-safe way by running that function inside the
 * tcpip_thread context.
 */
err_t
pppapi_set_default(ppp_pcb *pcb)
{
  err_t err;
  PPPAPI_VAR_DECLARE(msg);
  PPPAPI_VAR_ALLOC(msg);

  PPPAPI_VAR_REF(msg).msg.ppp = pcb;
  err = tcpip_api_call(pppapi_do_ppp_set_default, &PPPAPI_VAR_REF(msg).call);
  PPPAPI_VAR_FREE(msg);
  return err;
}

#if PPP_NOTIFY_PHASE
/**
 * Call ppp_set_notify_phase_callback() inside the tcpip_thread context.
 */
static err_t
pppapi_do_ppp_set_notify_phase_callback(struct tcpip_api_call_data *m)
{
  /* cast through void* to silence alignment warnings.
   * We know it works because the structs have been instantiated as struct pppapi_msg */
   struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;

  ppp_set_notify_phase_callback(msg->msg.ppp, msg->msg.msg.setnotifyphasecb.notify_phase_cb);
  return ERR_OK;
}

/**
 * Call ppp_set_notify_phase_callback() in a thread-safe way by running that function inside the
 * tcpip_thread context.
 */
err_t
pppapi_set_notify_phase_callback(ppp_pcb *pcb, ppp_notify_phase_cb_fn notify_phase_cb)
{
  err_t err;
  PPPAPI_VAR_DECLARE(msg);
  PPPAPI_VAR_ALLOC(msg);

  PPPAPI_VAR_REF(msg).msg.ppp = pcb;
  PPPAPI_VAR_REF(msg).msg.msg.setnotifyphasecb.notify_phase_cb = notify_phase_cb;
  err = tcpip_api_call(pppapi_do_ppp_set_notify_phase_callback, &PPPAPI_VAR_REF(msg).call);
  PPPAPI_VAR_FREE(msg);
  return err;
}
#endif /* PPP_NOTIFY_PHASE */

#if PPPOS_SUPPORT
/**
 * Call pppos_create() inside the tcpip_thread context.
 */
static err_t
pppapi_do_pppos_create(struct tcpip_api_call_data *m)
{
  /* cast through void* to silence alignment warnings.
   * We know it works because the structs have been instantiated as struct pppapi_msg */
  struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;

  msg->msg.ppp = pppos_create(msg->msg.msg.serialcreate.pppif, msg->msg.msg.serialcreate.output_cb,
    msg->msg.msg.serialcreate.link_status_cb, msg->msg.msg.serialcreate.ctx_cb);
  return ERR_OK;
}

/**
 * Call pppos_create() in a thread-safe way by running that function inside the
 * tcpip_thread context.
 */
ppp_pcb*
pppapi_pppos_create(struct netif *pppif, pppos_output_cb_fn output_cb,
               ppp_link_status_cb_fn link_status_cb, void *ctx_cb)
{
  ppp_pcb* result;
  PPPAPI_VAR_DECLARE(msg);
  PPPAPI_VAR_ALLOC_RETURN_NULL(msg);

  PPPAPI_VAR_REF(msg).msg.ppp = NULL;
  PPPAPI_VAR_REF(msg).msg.msg.serialcreate.pppif = pppif;
  PPPAPI_VAR_REF(msg).msg.msg.serialcreate.output_cb = output_cb;
  PPPAPI_VAR_REF(msg).msg.msg.serialcreate.link_status_cb = link_status_cb;
  PPPAPI_VAR_REF(msg).msg.msg.serialcreate.ctx_cb = ctx_cb;
  tcpip_api_call(pppapi_do_pppos_create, &PPPAPI_VAR_REF(msg).call);
  result = PPPAPI_VAR_REF(msg).msg.ppp;
  PPPAPI_VAR_FREE(msg);
  return result;
}
#endif /* PPPOS_SUPPORT */

#if PPPOE_SUPPORT
/**
 * Call pppoe_create() inside the tcpip_thread context.
 */
static err_t
pppapi_do_pppoe_create(struct tcpip_api_call_data *m)
{
  /* cast through void* to silence alignment warnings.
   * We know it works because the structs have been instantiated as struct pppapi_msg */
  struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;

  msg->msg.ppp = pppoe_create(msg->msg.msg.ethernetcreate.pppif, msg->msg.msg.ethernetcreate.ethif,
    msg->msg.msg.ethernetcreate.service_name, msg->msg.msg.ethernetcreate.concentrator_name,
    msg->msg.msg.ethernetcreate.link_status_cb, msg->msg.msg.ethernetcreate.ctx_cb);
  return ERR_OK;
}

/**
 * Call pppoe_create() in a thread-safe way by running that function inside the
 * tcpip_thread context.
 */
ppp_pcb*
pppapi_pppoe_create(struct netif *pppif, struct netif *ethif, const char *service_name,
                            const char *concentrator_name, ppp_link_status_cb_fn link_status_cb,
                            void *ctx_cb)
{
  ppp_pcb* result;
  PPPAPI_VAR_DECLARE(msg);
  PPPAPI_VAR_ALLOC_RETURN_NULL(msg);

  PPPAPI_VAR_REF(msg).msg.ppp = NULL;
  PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.pppif = pppif;
  PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.ethif = ethif;
  PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.service_name = service_name;
  PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.concentrator_name = concentrator_name;
  PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.link_status_cb = link_status_cb;
  PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.ctx_cb = ctx_cb;
  tcpip_api_call(pppapi_do_pppoe_create, &PPPAPI_VAR_REF(msg).call);
  result = PPPAPI_VAR_REF(msg).msg.ppp;
  PPPAPI_VAR_FREE(msg);
  return result;
}
#endif /* PPPOE_SUPPORT */

#if PPPOL2TP_SUPPORT
/**
 * Call pppol2tp_create() inside the tcpip_thread context.
 */
static err_t
pppapi_do_pppol2tp_create(struct tcpip_api_call_data *m)
{
  /* cast through void* to silence alignment warnings.
   * We know it works because the structs have been instantiated as struct pppapi_msg */
  struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;

  msg->msg.ppp = pppol2tp_create(msg->msg.msg.l2tpcreate.pppif,
    msg->msg.msg.l2tpcreate.netif, API_EXPR_REF(msg->msg.msg.l2tpcreate.ipaddr), msg->msg.msg.l2tpcreate.port,
#if PPPOL2TP_AUTH_SUPPORT
    msg->msg.msg.l2tpcreate.secret,
    msg->msg.msg.l2tpcreate.secret_len,
#else /* PPPOL2TP_AUTH_SUPPORT */
    NULL,
#endif /* PPPOL2TP_AUTH_SUPPORT */
    msg->msg.msg.l2tpcreate.link_status_cb, msg->msg.msg.l2tpcreate.ctx_cb);
  return ERR_OK;
}

/**
 * Call pppol2tp_create() in a thread-safe way by running that function inside the
 * tcpip_thread context.
 */
ppp_pcb*
pppapi_pppol2tp_create(struct netif *pppif, struct netif *netif, ip_addr_t *ipaddr, u16_t port,
                        const u8_t *secret, u8_t secret_len,
                        ppp_link_status_cb_fn link_status_cb, void *ctx_cb)
{
  ppp_pcb* result;
  PPPAPI_VAR_DECLARE(msg);
  PPPAPI_VAR_ALLOC_RETURN_NULL(msg);

  PPPAPI_VAR_REF(msg).msg.ppp = NULL;
  PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.pppif = pppif;
  PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.netif = netif;
  PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.ipaddr = PPPAPI_VAR_REF(ipaddr);
  PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.port = port;
#if PPPOL2TP_AUTH_SUPPORT
  PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.secret = secret;
  PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.secret_len = secret_len;
#endif /* PPPOL2TP_AUTH_SUPPORT */
  PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.link_status_cb = link_status_cb;
  PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.ctx_cb = ctx_cb;
  tcpip_api_call(pppapi_do_pppol2tp_create, &PPPAPI_VAR_REF(msg).call);
  result = PPPAPI_VAR_REF(msg).msg.ppp;
  PPPAPI_VAR_FREE(msg);
  return result;
}
#endif /* PPPOL2TP_SUPPORT */

/**
 * Call ppp_connect() inside the tcpip_thread context.
 */
static err_t
pppapi_do_ppp_connect(struct tcpip_api_call_data *m)
{
  /* cast through void* to silence alignment warnings.
   * We know it works because the structs have been instantiated as struct pppapi_msg */
  struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;

  return ppp_connect(msg->msg.ppp, msg->msg.msg.connect.holdoff);
}

/**
 * Call ppp_connect() in a thread-safe way by running that function inside the
 * tcpip_thread context.
 */
err_t
pppapi_connect(ppp_pcb *pcb, u16_t holdoff)
{
  err_t err;
  PPPAPI_VAR_DECLARE(msg);
  PPPAPI_VAR_ALLOC(msg);

  PPPAPI_VAR_REF(msg).msg.ppp = pcb;
  PPPAPI_VAR_REF(msg).msg.msg.connect.holdoff = holdoff;
  err = tcpip_api_call(pppapi_do_ppp_connect, &PPPAPI_VAR_REF(msg).call);
  PPPAPI_VAR_FREE(msg);
  return err;
}

#if PPP_SERVER
/**
 * Call ppp_listen() inside the tcpip_thread context.
 */
static err_t
pppapi_do_ppp_listen(struct tcpip_api_call_data *m)
{
  /* cast through void* to silence alignment warnings.
   * We know it works because the structs have been instantiated as struct pppapi_msg */
  struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;

  return ppp_listen(msg->msg.ppp);
}

/**
 * Call ppp_listen() in a thread-safe way by running that function inside the
 * tcpip_thread context.
 */
err_t
pppapi_listen(ppp_pcb *pcb)
{
  err_t err;
  PPPAPI_VAR_DECLARE(msg);
  PPPAPI_VAR_ALLOC(msg);

  PPPAPI_VAR_REF(msg).msg.ppp = pcb;
  err = tcpip_api_call(pppapi_do_ppp_listen, &PPPAPI_VAR_REF(msg).call);
  PPPAPI_VAR_FREE(msg);
  return err;
}
#endif /* PPP_SERVER */

/**
 * Call ppp_close() inside the tcpip_thread context.
 */
static err_t
pppapi_do_ppp_close(struct tcpip_api_call_data *m)
{
  /* cast through void* to silence alignment warnings.
   * We know it works because the structs have been instantiated as struct pppapi_msg */
  struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;

  return ppp_close(msg->msg.ppp, msg->msg.msg.close.nocarrier);
}

/**
 * Call ppp_close() in a thread-safe way by running that function inside the
 * tcpip_thread context.
 */
err_t
pppapi_close(ppp_pcb *pcb, u8_t nocarrier)
{
  err_t err;
  PPPAPI_VAR_DECLARE(msg);
  PPPAPI_VAR_ALLOC(msg);

  PPPAPI_VAR_REF(msg).msg.ppp = pcb;
  PPPAPI_VAR_REF(msg).msg.msg.close.nocarrier = nocarrier;
  err = tcpip_api_call(pppapi_do_ppp_close, &PPPAPI_VAR_REF(msg).call);
  PPPAPI_VAR_FREE(msg);
  return err;
}

/**
 * Call ppp_free() inside the tcpip_thread context.
 */
static err_t
pppapi_do_ppp_free(struct tcpip_api_call_data *m)
{
  /* cast through void* to silence alignment warnings.
   * We know it works because the structs have been instantiated as struct pppapi_msg */
  struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;

  return ppp_free(msg->msg.ppp);
}

/**
 * Call ppp_free() in a thread-safe way by running that function inside the
 * tcpip_thread context.
 */
err_t
pppapi_free(ppp_pcb *pcb)
{
  err_t err;
  PPPAPI_VAR_DECLARE(msg);
  PPPAPI_VAR_ALLOC(msg);

  PPPAPI_VAR_REF(msg).msg.ppp = pcb;
  err = tcpip_api_call(pppapi_do_ppp_free, &PPPAPI_VAR_REF(msg).call);
  PPPAPI_VAR_FREE(msg);
  return err;
}

/**
 * Call ppp_ioctl() inside the tcpip_thread context.
 */
static err_t
pppapi_do_ppp_ioctl(struct tcpip_api_call_data *m)
{
  /* cast through void* to silence alignment warnings.
   * We know it works because the structs have been instantiated as struct pppapi_msg */
  struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;

  return ppp_ioctl(msg->msg.ppp, msg->msg.msg.ioctl.cmd, msg->msg.msg.ioctl.arg);
}

/**
 * Call ppp_ioctl() in a thread-safe way by running that function inside the
 * tcpip_thread context.
 */
err_t
pppapi_ioctl(ppp_pcb *pcb, u8_t cmd, void *arg)
{
  err_t err;
  PPPAPI_VAR_DECLARE(msg);
  PPPAPI_VAR_ALLOC(msg);

  PPPAPI_VAR_REF(msg).msg.ppp = pcb;
  PPPAPI_VAR_REF(msg).msg.msg.ioctl.cmd = cmd;
  PPPAPI_VAR_REF(msg).msg.msg.ioctl.arg = arg;
  err = tcpip_api_call(pppapi_do_ppp_ioctl, &PPPAPI_VAR_REF(msg).call);
  PPPAPI_VAR_FREE(msg);
  return err;
}

#endif /* LWIP_PPP_API */

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

describe Lotus::Routing::Resource::Options do
  before do
    @actions = [:index, :new, :create, :show, :edit, :update, :destroy]
  end

  it 'returns all the actions when no exceptions are requested' do
    Lotus::Routing::Resources::Options.new(@actions).actions.must_equal @actions
  end

  it 'returns only the action requested via the :only option' do
    options = Lotus::Routing::Resources::Options.new(@actions, only: :show)
    options.actions.must_equal [:show]
  end

  it 'returns only the actions requested via the :only options' do
    options = Lotus::Routing::Resources::Options.new(@actions, only: [:create, :edit])
    options.actions.must_equal [:create, :edit]
  end

  it 'returns only the action not rejected via the :except option' do
    options = Lotus::Routing::Resources::Options.new(@actions, except: :destroy)
    options.actions.must_equal [:index, :new, :create, :show, :edit, :update]
  end

  it 'returns only the actions requested via the :only options' do
    options = Lotus::Routing::Resources::Options.new(@actions, except: [:index, :new, :edit])
    options.actions.must_equal [:create, :show, :update, :destroy]
  end

  it 'allow access to values' do
    options = Lotus::Routing::Resources::Options.new(@actions, name: :lotus)
    options[:name].must_equal :lotus
  end
end


text:
namespace Waf.MusicManager.Presentation.Services.Metadata;

internal class WavSaveMetadata : SaveMetadata
{
    protected override bool IsSupported => false;
}


text:
<?php

class ServiceProvider
{

    protected static $services = array();

    /**
     *
     * @return AbstractService
     */
    public static function get($service)
    {
        $name = strtolower($service);
        if (!isset(static::$services[$name])) {
            static::$services[$name] = new $service();
        }
        return static::$services[$name];
    }

}


text:
/**
 * This plug-in will provide date sorting for the "dd/mm/YYY hh:ii:ss"
 * formatting, which is common in France and other European countries. It can
 * also be quickly adapted for other formatting as required. Furthermore, this
 * date sorting plug-in allows for empty values in the column.
 *  @name Date (dd/mm/YYY hh:ii:ss)
 *  @anchor date_euro
 *  @author Ronan Guilloux
 */

 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "date-euro-pre": function ( a ) {
        if ($.trim(a) != '') {
            var frDatea = $.trim(a).split(' ');
            var frTimea = frDatea[1].split(':');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
        } else {
            var x = 10000000000000; // = l'an 1000 ...
        }

        return x;
    },

    "date-euro-asc": function ( a, b ) {
        return a - b;
    },

    "date-euro-desc": function ( a, b ) {
        return b - a;
    }
} );


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>New York</title>
	<link rel="stylesheet"  href="../../../css/themes/default/jquery.mobile.css">
	<link rel="stylesheet" href="../_assets/css/jqm-demos.css">

New York

        Retour

        	Fermer

Bien que de nombreuses légendes existent sur l'origine du surnom de New York : la Grosse Pomme, la plupart des historiens s'accordent à dire que l'origine revient à un écrivain qui a couvert les courses de chevaux dans les années 1920. Dans Le Morning Telegraph, il a écrit que les meilleurs sont souvent appelés à New York comme la Grosse Pomme, ce qui signifie que tout pur-sang qui a couru à New York avait atteint l'apogée de la course. source: nylady.hubpages.com

        	Précédent Suivant

		Trivia


text:
// TypeScript Version: 2.0

/**
* Tests if a value is a 64-bit complex number.
*
* @param value - value to test
* @returns boolean indicating if a value is a 64-bit complex number
*
* @example
* var Complex64 = require( `@stdlib/complex/float32` );
*
* var x = new Complex64( 4.0, 2.0 );
*
* var bool = isComplex64( x );
* // returns true
*/
declare function isComplex64( value: any ): boolean;

// EXPORTS //

export = isComplex64;


text:
package org.fest.assertions.api;

import junit.framework.Assert;

import org.fest.assertions.data.Index;
import org.fest.test.ExpectedException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

/**
 * Tests for {@link BooleanArrayAssert#contains(boolean, Index)}.
 *
 * @author Alex Ruiz
 * @author Yvonne Wang
 */
public class BooleanArrayAssert_contains_at_Index_Test {

  private final Index index = Index.atIndex(0);
  @Rule
  public ExpectedException thrown = ExpectedException.none();
  private boolean[] actual = { true, false };
  private BooleanArrayAssert assertions;

  @Before
  public void setUp() {
    assertions = new BooleanArrayAssert(actual);
  }

  @Test
  public void should_return_this() {
    BooleanArrayAssert returned = assertions.contains(true, index);
    Assert.assertSame(returned, assertions);
  }

  @Test
  public void should_pass_if_actual_contains_value_at_index() {
    assertions.contains(true, index);
  }

  @Test
  public void should_fail_if_actual_does_not_contain_value_at_index() {
    thrown.expect(AssertionError.class);
    assertions.contains(false, index);
  }

  @Test
  public void should_throw_error_if_actual_is_null() {
    thrown.expect(AssertionError.class);
    actual = null;
    assertions.contains(false, index);
  }

  @Test
  public void should_throw_error_if_actual_is_empty() {
    thrown.expect(AssertionError.class);
    actual = new boolean[0];
    assertions.contains(false, index);
  }

  @Test
  public void should_fail_if_index_is_null() {
    thrown.expect(NullPointerException.class);
    assertions.contains(false, null);
  }

  @Test
  public void should_fail_if_index_is_invalid() {
    thrown.expect(IllegalArgumentException.class);
    assertions.contains(false, Index.atIndex(-1));
  }
}


text:
module Graphics.Rendering.OpenGL.Raw.NV.TextureRectangle (
   -- * Tokens
   gl_TEXTURE_RECTANGLE,
   gl_TEXTURE_BINDING_RECTANGLE,
   gl_PROXY_TEXTURE_RECTANGLE,
   gl_MAX_RECTANGLE_TEXTURE_SIZE
) where

import Graphics.Rendering.OpenGL.Raw.Core32


text:
"""
Pointer implementation.
"""

from __future__ import print_function, division, absolute_import
import ctypes

import flypy.types
from flypy import sjit, jit, ijit, cjit
from flypy.compiler import representation_type
from flypy.conversion import ctype
from flypy.runtime import formatting
from .richcompare import RichComparisonMixin
from ..lowlevel_impls import add_impl_cls

from pykit import types as ptypes

jit = cjit

#===------------------------------------------------------------------===
# Pointer
#===------------------------------------------------------------------===

@sjit('Pointer[a]')
class Pointer(RichComparisonMixin):
    layout = [] # [('p', 'Pointer[a]')]

    def __init__(self, p):
        self.p = p

    # __________________________________________________________________

    @jit('a -> int64 -> a', opaque=True)
    def __add__(self, index):
        return self.p + index

    @jit('Pointer[a] -> a', opaque=True)
    def deref(self):
        return self.p[0]

    @jit('Pointer[a] -> a -> void', opaque=True)
    def store(self, value):
        self.p[0] = value

    # __________________________________________________________________

    @jit('Pointer[a] -> Pointer[b] -> bool')
    def __eq__(self, other):
        return self.ptrtoint() == other.ptrtoint()

    @jit('a -> NullType[] -> bool')
    def __eq__(self, other):
        return self.ptrtoint() == 0

    @jit('Pointer[a] -> Pointer[b] -> bool')
    def __lt__(self, other):
        return self.ptrtoint() < other.ptrtoint()

    # __________________________________________________________________

    @jit('Pointer[a] -> int64 -> a')
    def __getitem__(self, index):
        return (self + index).deref()

    @jit('Pointer[a] -> int64 -> a -> void')
    def __setitem__(self, idx, value):
        (self + idx).store(value)

    @jit('a -> int64 -> a')
    def __sub__(self, index):
        return self + -index

    @jit('Pointer[a] -> Pointer[a] -> int64')
    def __sub__(self, index):
        return self.ptrtoint() - index.ptrtoint()

    @jit('a -> bool')
    def __nonzero__(self):
        return self != flypy.NULL

    @jit('a -> int64')
    def ptrtoint(self):
        return flypy.cast(self, flypy.types.int64)

    @jit
    def __str__(self):
        # maxlen = int(math.log10(2**64)) + 1 = 20 in a 64-bit address space
        return formatting.format_static("%p", self, 20 + 1)

    __repr__ = __str__

    # __________________________________________________________________

    @staticmethod
    def fromobject(ptr, type):
        return Pointer(make_ctypes_ptr(ptr, type))

    @classmethod
    def toctypes(cls, val, ty):
        if isinstance(val, Pointer):
            val = val.p
        return make_ctypes_ptr(val, ty)

    @classmethod
    def fromctypes(cls, val, ty):
        if isinstance(val, (int, long)):
            cty = ctype(ty)
            return cty(val)
        return val

    @classmethod
    def ctype(cls, ty):
        [base] = ty.parameters
        return ctypes.POINTER(ctype(base))

#===------------------------------------------------------------------===
# NULL
#===------------------------------------------------------------------===

@sjit
class NullType(object):
    layout = []

    @jit('a -> bool')
    def __nonzero__(self):
        return False

    @jit('a -> Pointer[b] -> bool')
    def __eq__(self, other):
        return other.ptrtoint() == 0

    #@jit('a -> b -> bool')
    #def __eq__(self, other):
    #    return False

NULL = NullType()

#===------------------------------------------------------------------===
# Low-level Implementation
#===------------------------------------------------------------------===

def pointer_add(builder, argtypes, ptr, addend):
    builder.ret(builder.ptradd(ptr, addend))

def pointer_load(builder, argtypes, ptr):
    builder.ret(builder.ptrload(ptr))

def pointer_store(builder, argtypes, ptr, value):
    builder.ptrstore(value, ptr)
    builder.ret(None)

# Determine low-level return types

def _getitem_type(argtypes):
    base = argtypes[0].parameters[0]
    return representation_type(base)

# Implement

add_impl_cls(Pointer, "__add__", pointer_add)
add_impl_cls(Pointer, "deref", pointer_load, restype_func=_getitem_type)
add_impl_cls(Pointer, "store", pointer_store, restype=ptypes.Void)

#===------------------------------------------------------------------===
# Utils
#===------------------------------------------------------------------===

def make_ctypes_ptr(ptr, type):
    from flypy.support.cffi_support import is_cffi, ffi
    from flypy.support.ctypes_support import is_ctypes_pointer_type

    cty = ctype(type)

    if is_cffi(ptr):
        addr = ffi.cast('uintptr_t', ptr)
        ctypes_ptr = ctypes.c_void_p(int(addr))
        ptr = ctypes.cast(ctypes_ptr, cty)
    else:
        ptr = ctypes.cast(ptr, cty)

    return ptr

def address(ptr):
    return ctypes.cast(ptr, ctypes.c_void_p).value


text:
'use strict';

import {TPromise} from 'vs/base/common/winjs.base';
import collections = require('vs/base/common/collections');
import {Registry} from 'vs/platform/platform';
import {IAction} from 'vs/base/common/actions';
import {KeybindingsRegistry, ICommandAndKeybindingRule} from 'vs/platform/keybinding/common/keybindingsRegistry';
import {IPartService} from 'vs/workbench/services/part/common/partService';
import {ICommandHandler} from 'vs/platform/commands/common/commands';
import {SyncActionDescriptor} from 'vs/platform/actions/common/actions';
import {IMessageService} from 'vs/platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import Severity from 'vs/base/common/severity';

export const Extensions = {
	WorkbenchActions: 'workbench.contributions.actions'
};

export interface IActionProvider {
	getActions(): IAction[];
}

export interface IWorkbenchActionRegistry {

	/**
	 * Registers a workbench action to the platform. Workbench actions are not
	 * visible by default and can only be invoked through a keybinding if provided.
	 */
	registerWorkbenchAction(descriptor: SyncActionDescriptor, alias: string, category?: string): void;

	/**
	 * Unregisters a workbench action from the platform.
	 */
	unregisterWorkbenchAction(id: string): boolean;

	/**
	 * Returns the workbench action descriptor for the given id or null if none.
	 */
	getWorkbenchAction(id: string): SyncActionDescriptor;

	/**
	 * Returns an array of registered workbench actions known to the platform.
	 */
	getWorkbenchActions(): SyncActionDescriptor[];

	/**
	 * Returns the alias associated with the given action or null iff none.
	 */
	getAlias(actionId: string): string;

	/**
	 * Returns the category for the given action or null iff none.
	 */
	getCategory(actionId: string): string;
}

interface IActionMeta {
	alias: string;
	category?: string;
}

class WorkbenchActionRegistry implements IWorkbenchActionRegistry {
	private workbenchActions: collections.IStringDictionary<SyncActionDescriptor>;
	private mapActionIdToMeta: { [id: string]: IActionMeta; };

	constructor() {
		this.workbenchActions = Object.create(null);
		this.mapActionIdToMeta = Object.create(null);
	}

	public registerWorkbenchAction(descriptor: SyncActionDescriptor, alias: string, category?: string): void {
		if (!this.workbenchActions[descriptor.id]) {
			this.workbenchActions[descriptor.id] = descriptor;
			registerWorkbenchCommandFromAction(descriptor);

			let meta: IActionMeta = { alias };
			if (typeof category === 'string') {
				meta.category = category;
			}

			this.mapActionIdToMeta[descriptor.id] = meta;
		}
	}

	public unregisterWorkbenchAction(id: string): boolean {
		if (!this.workbenchActions[id]) {
			return false;
		}

		delete this.workbenchActions[id];
		delete this.mapActionIdToMeta[id];

		return true;
	}

	public getWorkbenchAction(id: string): SyncActionDescriptor {
		return this.workbenchActions[id] || null;
	}

	public getCategory(id: string): string {
		return (this.mapActionIdToMeta[id] && this.mapActionIdToMeta[id].category) || null;
	}

	public getAlias(id: string): string {
		return (this.mapActionIdToMeta[id] && this.mapActionIdToMeta[id].alias) || null;
	}

	public getWorkbenchActions(): SyncActionDescriptor[] {
		return collections.values(this.workbenchActions);
	}

	public setWorkbenchActions(actions: SyncActionDescriptor[]): void {
		this.workbenchActions = Object.create(null);
		this.mapActionIdToMeta = Object.create(null);

		actions.forEach(action => this.registerWorkbenchAction(action, ''), this);
	}
}

Registry.add(Extensions.WorkbenchActions, new WorkbenchActionRegistry());

function registerWorkbenchCommandFromAction(descriptor: SyncActionDescriptor): void {
	let when = descriptor.keybindingContext;
	let weight = (typeof descriptor.keybindingWeight === 'undefined' ? KeybindingsRegistry.WEIGHT.workbenchContrib() : descriptor.keybindingWeight);
	let keybindings = descriptor.keybindings;

	let desc: ICommandAndKeybindingRule = {
		id: descriptor.id,
		handler: createCommandHandler(descriptor),
		weight: weight,
		when: when,
		primary: keybindings && keybindings.primary,
		secondary: keybindings && keybindings.secondary,
		win: keybindings && keybindings.win,
		mac: keybindings && keybindings.mac,
		linux: keybindings && keybindings.linux
	};

	KeybindingsRegistry.registerCommandAndKeybindingRule(desc);
}

export function createCommandHandler(descriptor: SyncActionDescriptor): ICommandHandler {
	return (accessor, args) => {

		let messageService = accessor.get(IMessageService);
		let instantiationService = accessor.get(IInstantiationService);
		let telemetryServce = accessor.get(ITelemetryService);
		let partService = accessor.get(IPartService);

		TPromise.as(triggerAndDisposeAction(instantiationService, telemetryServce, partService, descriptor, args)).done(null, (err) => {
			messageService.show(Severity.Error, err);
		});
	};
}

export function triggerAndDisposeAction(instantitationService: IInstantiationService, telemetryService: ITelemetryService, partService: IPartService, descriptor: SyncActionDescriptor, args: any): TPromise<any> {
	let actionInstance = instantitationService.createInstance(descriptor.syncDescriptor);
	actionInstance.label = descriptor.label || actionInstance.label;

	// don't run the action when not enabled
	if (!actionInstance.enabled) {
		actionInstance.dispose();
		return;
	}

	if (telemetryService) {
		telemetryService.publicLog('workbenchActionExecuted', { id: actionInstance.id, from: args && args.from || 'keybinding' });
	}

	// run action when workbench is created
	return partService.joinCreation().then(() => {
		try {
			return TPromise.as(actionInstance.run()).then(() => {
				actionInstance.dispose();
			}, (err) => {
				actionInstance.dispose();
				return TPromise.wrapError(err);
			});
		} catch (err) {
			actionInstance.dispose();
			return TPromise.wrapError(err);
		}
	});
}


text:
namespace ExecutableProject
{
  class Program
  {
    static void Main(string[] args)
    {
    }
  }
}


text:
redirect_from: /docs/1.0.0-beta.3/classes/ng1.ng1viewconfig.html
---
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Ng1ViewConfig | UI-Router</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">
	<link rel="stylesheet" href="../assets/css/typedoctheme.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					UI-Router

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					ng1

					Ng1ViewConfig

Class Ng1ViewConfig

Hierarchy

						Ng1ViewConfig

Implements

ViewConfig

Index

Constructors

constructor

Properties

$id

controller

loaded

locals

path

template

view<wbr>Decl

Methods

get<wbr>Controller

get<wbr>Template

has<wbr>Template

load

Constructors

new <wbr>Ng1<wbr>View<wbr>Config(path: PathNode[], viewDecl: Ng1ViewDeclaration): Ng1ViewConfig

Parameters

path: PathNode[]

viewDecl: Ng1ViewDeclaration

Returns Ng1ViewConfig

Defined in ng1/statebuilders/views.ts:123

Properties

$id: number

Implementation of ViewConfig.$id

Defined in ng1/statebuilders/views.ts:119

controller: Function

Defined in ng1/statebuilders/views.ts:121

loaded: boolean

Implementation of ViewConfig.loaded

Defined in ng1/statebuilders/views.ts:120

locals: any

Defined in ng1/statebuilders/views.ts:123

path: PathNode[]

Implementation of ViewConfig.path

Defined in ng1/statebuilders/views.ts:125

template: string

Defined in ng1/statebuilders/views.ts:122

view<wbr>Decl: Ng1ViewDeclaration

Implementation of ViewConfig.viewDecl

Defined in ng1/statebuilders/views.ts:125

Methods

get<wbr>Controller(context: ResolveContext): String | Function | Promise<Function | String>

 Gets the controller for a view configuration.

Gets the controller for a view configuration.

Parameters

context: ResolveContext

Returns String
									 |
									Function
									 |
									Promise<Function | String>

								:
Returns a controller, or a promise that resolves to a controller.

Defined in ng1/statebuilders/views.ts:166

get<wbr>Template(params: RawParams, $factory: TemplateFactory, context: ResolveContext): any

Parameters

params: RawParams

$factory: TemplateFactory

context: ResolveContext

Returns any

Defined in ng1/statebuilders/views.ts:157

has<wbr>Template(): boolean

 Checks a view configuration to ensure that it specifies a template.

Checks a view configuration to ensure that it specifies a template.

Returns boolean

								:
Returns true if the configuration contains a valid template, otherwise false.

Defined in ng1/statebuilders/views.ts:153

load(): Promise<this>

Returns Promise<this>

Implementation of ViewConfig.load

Defined in ng1/statebuilders/views.ts:127

						Globals

						common

						common_<wbr>hof

						common_<wbr>predicates

						common_<wbr>strings

						core

						hooks

						justjs

						ng1

								"../router"

						ng1_<wbr>directives

						ng1_<wbr>state_<wbr>events

						ng2

						ng2_<wbr>directives

						params

						path

						resolve

						state

						trace

						transition

						url

						view

						Ng1<wbr>View<wbr>Config

								constructor

								$id

								controller

								loaded

								locals

								path

								template

								view<wbr>Decl

								get<wbr>Controller

								get<wbr>Template

								has<wbr>Template

								load

						State<wbr>Provider

						Binding<wbr>Tuple

						Ng1<wbr>Controller

						Ng1<wbr>State<wbr>Declaration

						Ng1<wbr>View<wbr>Declaration

						$state

						$state<wbr>Params

						$state<wbr>Provider

						$transitions

						$transitions<wbr>Provider

						$url<wbr>Matcher<wbr>Factory

						$url<wbr>Matcher<wbr>Factory<wbr>Provider

						$url<wbr>Router

						$url<wbr>Router<wbr>Provider

						id

						router

						$<wbr>View<wbr>Scroll<wbr>Provider

						$ui<wbr>Router

						annotate<wbr>Controller

						get<wbr>Bindings

						get<wbr>Component<wbr>Inputs

						get<wbr>Locals

						get<wbr>State<wbr>Hook<wbr>Builder

						get<wbr>State<wbr>Provider

						get<wbr>Transitions<wbr>Provider

						get<wbr>Url<wbr>Router<wbr>Provider

						ng1<wbr>View<wbr>Config<wbr>Factory

						ng1<wbr>Views<wbr>Builder

						run<wbr>Block

						scope<wbr>Bindings

						watch<wbr>Digests

						$resolve

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
package com.khartec.waltz.model.database_information;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.khartec.waltz.model.SummaryStatistics;
import com.khartec.waltz.model.tally.Tally;
import org.immutables.value.Value;

import java.util.List;

@Value.Immutable
@JsonSerialize(as = ImmutableDatabaseSummaryStatistics.class)
@JsonDeserialize(as = ImmutableDatabaseSummaryStatistics.class)
public abstract class DatabaseSummaryStatistics implements SummaryStatistics {

    public abstract List<Tally<String>> environmentCounts();
    public abstract List<Tally<String>> vendorCounts();
    public abstract List<Tally<String>> endOfLifeStatusCounts();

}


text: <script src="front-web/controller/register/cadPerson_func.js"></script>


text:
[![Code Climate](https://codeclimate.com/github/jeremysklarsky/AmIRuby/badges/gpa.svg)](https://codeclimate.com/github/jeremysklarsky/AmIRuby)

# Am I Ruby?

## Description

Use this handy web app to find out whether your favorite domains have Ruby in their stack.

#### To use:

_**Step 1:**_
Type in a domain using the format "example.com".
**Do not include 'http://' or any subdomain.**

_**Step 2:**_
Hit enter or click the 'Search' button.

_**Step 3:**_
Repeat as needed.

## Development/Contribution

Contributions welcome. Please fork this repo, create a new branch, then submit changes as a pull request.

## Future

Planned feature releases:
1. Add navigation to domain's page on [BuiltWith.com](http://builtwith.com/).
2. Enhance button hover effects.
3. Enhance sound effects.
4. Expand to other languages (Javascript, Python, PHP, Perl, etc.)
5. Add full rspec test suite

## Team

Team AmIRuby is [Sophie DeBenedetto](https://github.com/SophieDeBenedetto), [Jeremy Sklarsky](https://github.com/jeremysklarsky), [Rachel Nackman](https://github.com/rnackman), and [Kate Travers](https://github.com/ktravers). Made with ♥ in NYC.

## License

AmIRuby is MIT Licensed. See LICENSE for details.


text:
package re.agiledesign.mp2.internal.statements;

import re.agiledesign.mp2.internal.Context;
import re.agiledesign.mp2.internal.Scope;

public class LoadStatement extends Statement {
	private final String mPath;

	public LoadStatement(final String aPath) {
		mPath = aPath;
	}

	public void execute(final Scope aScope) throws Exception {
		final Context context = (aScope instanceof Context) ? (Context) aScope : aScope.getPrevious();

		context.loadModule(mPath);
	}
}


text:
import sys
from setup import setup
from util import nodeenv_delegate

YARN_DEPENDENCY_MANAGEMENT_COMMANDS = [
    "add",
    "install",
    "link",
    "remove",
    "unlink",
    "upgrade",
    "upgrade-interactive",
]

if __name__ == "__main__":
    command = next((arg for arg in sys.argv[1:] if not arg.startswith("-")), "install")
    setup(skip_dependencies=(command in YARN_DEPENDENCY_MANAGEMENT_COMMANDS))
    nodeenv_delegate("yarn")


text:
use warnings;
use strict;
use Cwd 'abs_path';
use Getopt::Long;
use File::Basename;
## usage: fusions-from-star.pl  outputname Chimeric.out.junction

##IMPORTANT NOTE!  this calls 'samtools' and 'bedtools' and 'mafft'  please have these installed and in your path under those aliases.
	#It shouldn't crash without them, but you will get error messages rather than some of the outputs.
	#$ On MSSM/minerva you can just do: module load starchip

# to do:
	# blat/blast output.  blat is REALLY slow, and because of mem loading, probably faster if run in batches.
		# run all blat at once.
		# $ blat t=dna q=rna /path/to/database /path/to/query
		# the other issue is that blat/blast don't lend themselves to computational filtering easily.  taking the top hit works ok though.

if (scalar(@ARGV) != 3 ) { die "Wrong number of inputs. Usage: fusions-from-star.pl output_seed input_chimeric.out.junction params.txt \n Be sure you have samtools, bedtools, and mafft available.\n";}

##Read in User Parameters (taken from Perl Cookbook "8.16. Reading Configuration Files")
my %Configs = ();
my $configfile = $ARGV[2];
open CONFIG, "<$configfile" or die $!;
while (<CONFIG>) {
    chomp;                  # no newline
    s/#.*//;                # no comments
    s/^\s+//;               # no leading white
    s/\s+$//;               # no trailing white
    next unless length;     # anything left?
    my ($var, $value) = split(/\s*=\s*/, $_, 2);
    $Configs{$var} = $value;
}

#These shouldn't change unless the format of Chimeric.out.junction from star changes:
my $col_jxntype=6;
my $col_startposA=10;
my $col_startposB=12;
my $col_cigarA=11;
my $col_cigarB=13;
my $col_chrA=0;
my $col_chrB=3;
my $col_FusionposA=1;
my $col_FusionposB=4;
my $col_strandA=2;
my $col_strandB=5;
my $col_overlapL=7;
my $col_overlapR=8;
my $numbcolumns=14; #need this one in case you junciton.out file/input changes.  this should be a non-existant final column (ie Chimeric.junciton.out has 0-13 columns)
#should fix this to be more robust...

#set variables
my $linecount=0;
my $readlength =0;
my %fusions =();
my $script_dir=abs_path($0);
$script_dir =~ s/fusions-from-star.pl//;
my $consensusloc= $script_dir . 'consensus.sh';
my $annotateloc= $script_dir . 'coordinates2genes.sh';
my $blastscript = $script_dir . 'check-pseudogenes.sh';
my $smithwaterman = $script_dir . 'smith_waterman.pl';
my $data_dir = abs_path($0) ;
$data_dir =~ s/\/scripts\/fusions\/fusions-from-star.pl//;

my $abpartsfile = $data_dir . "/" . $Configs{abparts} ;
my $troublemakers = $data_dir . "/" . $Configs{falsepositives} ;
my $familyfile = $data_dir . "/" . $Configs{familyfile} ;
my $cnvfile = $data_dir . "/" . $Configs{cnvs} ;

unless (-e $abpartsfile ) { #if the file isn't in starchip/
	$abpartsfile = $Configs{abparts} ; #check the absolute path
	unless (-e $abpartsfile ) {
		print "Warning: Can not find your Antibody Parts File: $Configs{abparts} or $data_dir/$Configs{abparts} \n";
	}
}
unless (-e $troublemakers ) { #if the file isn't in starchip/
	$troublemakers = $Configs{falsepositives} ; #check the absolute path
	unless (-e $troublemakers ) {
		print "Warning: Can not find your False Positives File: $Configs{falsepositives} $data_dir/$troublemakers\n";
	}
}
unless (-e $familyfile ) { #if the file isn't in starchip/
	$familyfile = $Configs{familyfile} ; #check the absolute path
	unless (-e $familyfile ) {
		print "Warning: Can not find your Gene Families File: $Configs{familyfile} or $data_dir/$familyfile\n";
	}
}
unless (-e $cnvfile ) { #if the file isn't in starchip/
	$cnvfile = $Configs{cnvs} ; #check the absolute path
	unless (-e $cnvfile ) {
		print "Warning: Can not find your Copy Number Variants File: $Configs{cnvs}\n or $data_dir/$cnvfile \n";
	}
}

#file management
my $outbase = $ARGV[0];
#$outbase =~ 's/\'//' ;
my $outsumm = $outbase . ".summary";
my $outsummtemp = $outsumm . ".temp";
my $outannotemp = $outsummtemp . ".annotated" ;
my $outanno = $outsumm . ".annotated";
my $junction = $ARGV[1];
my $sam = $junction;
$sam =~ s/junction$/sam/ ;
my $starbase = $junction ;
$starbase =~ s/Chimeric.out.junction//;

#index the antibody regions for this genome:
open ABS, "<$abpartsfile" or die $!;
my @AbParts;
my $abindex=0;
while (my $x = <ABS>) {
	$x =~ s/^chr// ; #we strip out chr beginings to make everything line up ok.
        my @line = split(/\s+/, $x); #AbParts lines are formatted: chrm pos1 pos2
        $AbParts[$abindex][0]{$line[0]} = $line[1]; ##data format: $AbParts[index][0=lower/1=upper position]{chrom}
        $AbParts[$abindex][1]{$line[0]} = $line[2]; ##data format: $AbParts[index][0=lower/1=upper position]{chrom}
        $abindex++;
}

### AUTOMATIC THRESHOLDING
#determine the number of uniquely mapped reads
my $logfinalout = $starbase . "Log.final.out" ;
open LOGFINAL, "<$logfinalout" or die "cannot open $logfinalout\nHave you moved Chimeric.out.junction out of the original STAR output directory?  STARChip uses several files automatically generated by STAR\n";
my @loglines = <LOGFINAL> ;
my @uniqreadcount = grep(/Uniquely mapped reads number/, @loglines);
my ($trashtext, $readcount) = split(/\|/, $uniqreadcount[0]);
$readcount =~ s/^\s+|\s+$//g; #strip whitespace

if ( lc $Configs{"splitReads"} eq "auto" || lc $Configs{"splitReads"} eq "highsensitivity" || lc $Configs{"splitReads"} eq "highprecision" ) {
	print "Performing Automatic Threshold Targeting For Split Reads\n";
	#my $cutoff = $readcount / 3000000 ;
	my $cutoff = $readcount / 3571429 ; # 0.28 reads per million mapped
	if ( lc $Configs{"splitReads"} eq "highsensitivity" ) {
                $cutoff = $readcount / 20000000 ; ## 0.05 reads per million mapped
        }
        if ( lc $Configs{"splitReads"} eq "highprecision" ) {
                $cutoff = $readcount / 847458 ;  ## 1.18 reads per million mapped
        }
	$cutoff = sprintf "%.0f", $cutoff;
	if ($cutoff < 0 ) { die "Error Calculating read based cutoffs. STAR output Log.final.out reports $readcount reads\n" }
	if ($cutoff == 0 ) { $cutoff++; }
	print "Uniquely Mapped Reads:$readcount\nSelected Cutoff: $cutoff\n";
	$Configs{splitReads} = $cutoff;
}
##do the same for spanning (paired) reads
if ( lc $Configs{"spancutoff"} eq "auto" || lc $Configs{"spancutoff"} eq "highsensitivity" || lc $Configs{"spancutoff"} eq "highprecision" ) {EXITER:{
        print "Performing Automatic Threshold Targeting For Spanning Reads\n";
	if ( lc $Configs{"pairedend"} ne "true" ) { $Configs{spancutoff} =0; print "Paired-End config not set to TRUE, setting limits for single-end data\n" ; last EXITER;}
	my $cutoff = $readcount / 3000000 ; # 0.33 reads per million mapped
	#this choice of reads/7.5M is somewhate arbitrary.  The ratio of split/span reads should be a function of:
	#read length and fragment/insert length.
	#High Sensitivity Mode
	if ( lc $Configs{"spancutoff"} eq "highsensitivity" ) {
		$cutoff = $readcount / 20000000 ; ## 0.05 reads per million mapped
	}
	if ( lc $Configs{"spancutoff"} eq "highprecision" ) {
		$cutoff = $readcount / 847458 ;  ## 1.18 reads per million mapped
	}
        $cutoff = sprintf "%.0f", $cutoff;
        if ($cutoff < 0	) { die	"Error Calculating read based cutoffs. STAR output Log.final.out reports $readcount reads\n" }
        if ($cutoff == 0 ) { $cutoff++;	}
        print "Uniquely Mapped Reads:$readcount\nSelected Cutoff: $cutoff\n";
        $Configs{spancutoff} = $cutoff;
} }
print "\nUsing the following variables:\nPaired-End: $Configs{pairedend}\nSplit Reads Cutoff: $Configs{splitReads}\nUnique Support Values Min: $Configs{uniqueReads}\nSpanning Reads Cutoff: $Configs{spancutoff}\nLocation Wiggle Room (spanning reads): $Configs{wiggle} bp\nLocation Wiggle Room (split reads) : $Configs{overlapLimit} bp\nMin-distance : $Configs{samechrom_wiggle} bp\nRead Distribution upper limit: $Configs{lopsidedupper} X\nRead Distribution lower limit: $Configs{lopsidedlower} X\n";
if ( $Configs{splitReads} !~ /^[0-9,.E]+$/ ) {
	die "ERROR: Split Reads value $Configs{splitReads} is not numeric.  Acceptable arguments are: 'auto', 'highprecision', 'highsensitivity', or any number\n";
}
if ( $Configs{spancutoff} !~ /^[0-9,.E]+$/ ) {
	die "ERROR: Spanning Reads value $Configs{spancutoff} is not numeric.  Acceptable arguments are: 'auto', 'highprecision', 'highsensitivity', or any number\n";
}

# primary data format; $chr1_pos1_chr2_pos2_strandA_strandB[0/1/2][0-RL]
	#where strand is + or -
	#and [0/1/2] indicates left-side/right-side of fusion/non-split reads
	#0-Read length starts at the fusion site =0 and expands outwards from there, to pos2+RL on right side, pos1-RL on left side.
	# in most cases, we will use + strand notation for positions.
print "\nNow catologuing all chimeric reads\n";
open JUNCTION, "<$junction" or die $!;
EXITHERE: while (my $x = <JUNCTION>) {
	my @line = split(/\s+/, $x);
##some filtering
	next if ($line[$col_chrA] eq "chrM");
	next if ($line[$col_chrB] eq "chrM");
	next if ($line[$col_chrA] eq "MT");
	next if ($line[$col_chrB] eq "MT");
	next if ($line[$col_chrA] =~ m/GL*/);
	next if ($line[$col_chrB] =~ m/GL*/);
	next if ($line[$col_overlapL] > $Configs{overlapLimit});
	next if ($line[$col_overlapR] > $Configs{overlapLimit});

#calculate read length (where read length == the length of one pair of the sequencing if paired end)
	if ($linecount < 1 ) {
		my $cigarA=$line[$col_cigarA];
		my $cigarB=$line[$col_cigarB];
		my $lengthA = &splitCigar($cigarA);
		my $lengthB = &splitCigar($cigarB);
		if ($lengthA == $lengthB) {
			$readlength=$lengthA;
			print "Read length appears to be $readlength\n";
		}
		elsif ($lengthA == (2*$lengthB)) {
			$readlength=$lengthB;
			print "Read length appears to be $readlength\n";
		}
		elsif ($lengthB == (2*$lengthA)) {
			$readlength=$lengthA;
			print "Read length appears to be $readlength\n";
		}
		else { print "read length error, please check input\nCigar String $cigarA (length $lengthA ) and $cigarB (length $lengthB ) indicate different lengths\nWill try again with the next line of your junctions file\n";
			$readlength=100;
			$linecount=-1;
		}
	}
#Skip antibody Parts regions: ab files have chr stripped if they have it.  so i'll strip it from the reads here.
	my $chrA = $line[$col_chrA] ;
	my $chrB = $line[$col_chrB] ;
	$chrA =~ s/^chr//; $chrB =~ s/^chr// ;
        foreach my $z (0..$abindex) {
                no warnings 'uninitialized' ;
                if ($AbParts[$z][0]{$chrA} <= $line[$col_FusionposA] && $line[$col_FusionposA] <= $AbParts[$z][1]{$chrA}) {
                        #print "pos1 match\n";
                        foreach my $y (0..$abindex) {
                                if ($AbParts[$y][0]{$chrB} <= $line[$col_FusionposB] && $line[$col_FusionposB]<= $AbParts[$y][1]{$chrB}) {
                                        #print "Skipping $line[$col_chrA]:$line[$col_FusionposA] $line[$col_chrB]:$line[$col_FusionposB]";
                                        next EXITHERE;
                                }
                        }
                }
        }

#Create two 'names' and check if they exist.  Checking the written + reverse allows us to collapse reads on opposite strands
	my $fusionname=$line[$col_chrA] . "__" . $line[$col_FusionposA] . "__" . $line[$col_chrB] . "__" . $line[$col_FusionposB] . "__" . $line[$col_strandA] . "__" . $line[$col_strandB] ;
	my $invStrandA = &reversestrand($line[$col_strandA]);
	my $invStrandB = &reversestrand($line[$col_strandB]);
	my $fusionnameInv=$line[$col_chrB] . "__" . $line[$col_FusionposB] . "__" . $line[$col_chrA] . "__" . $line[$col_FusionposA] . "__" . $invStrandB . "__" . $invStrandA ;
	## chrA_pos1_+ fused to chrB_pos2_+ equals chrB_pos2_- fused to chrA_pos_- etc.
	##check the existence
	if (exists $fusions{$fusionname}) {
		&supportCigar(@line, $fusionname, "1");

	}
	elsif (exists $fusions{$fusionnameInv}) {
	  #because this is the reverse compliment of the already indexed read, we'll feed in a rearranged line from Chimeric.out.junction, with the strands flipped.
		$chrA=$line[$col_chrB];
		my $posA=$line[$col_FusionposB];
		my $strandA = &reversestrand($line[$col_strandB]);
		$chrB=$line[$col_chrA];
		my $posB=$line[$col_FusionposA];
		my $strandB = &reversestrand($line[$col_strandA]);
		#6 7,8,9 unchanged/unimportant here
		my $startposA = $line[$col_startposB];
		my $cigarA = $line[$col_cigarB];
		my $starposB = $line[$col_startposA];
		my $cigarB = $line[$col_cigarA];
		#print "@line\n";
		#print "$chrA $posA $strandA $chrB $posB $strandB $line[7] $line[8] $line[9] $startposA $cigarA $starposB $cigarB\n";
		&supportCigar($chrA, $posA, $strandA, $chrB, $posB, $strandB, $line[6], $line[7], $line[8], $line[9], $startposA, $cigarA, $starposB, $cigarB, $fusionnameInv, "2" );
	}
	else {
		#create the array in the fusions hash
		for my $x (0..($readlength-1)) {
			$fusions{$fusionname}[0][$x] =0; #jxn crossing read support (Left side)
			$fusions{$fusionname}[1][$x] =0; #jxn crossing read support (Right side)
		}
		$fusions{$fusionname}[2][0] = 0; #jxn spanning read support on the strands as named
		$fusions{$fusionname}[2][1] = 0; # strand distribution (jxn crossing reads in 'fusionname' orientaiton with first listed chrm on the left)
		$fusions{$fusionname}[2][2] = 0; # strand distribution (jxn crossing reads in 'fusionnameInv' orientation with first listed chrm on the right)
		$fusions{$fusionname}[2][3] = 0; # A chrom anchored (for split reads, the pair lies on chromosome A)
		$fusions{$fusionname}[2][4] = 0; # B chrom anchored (for split reads, the matepair lies on chromosome B)
		$fusions{$fusionname}[2][5] = 0; #jxn spanning read support inverse strands
		&supportCigar(@line, $fusionname, "1");
	}
	$linecount++;
	#print "$fusionname\t$fusions{$fusionname}[0][0]\t$fusions{$fusionname}[1][0]\n";
	#if ($linecount > 10 ) { die; }
}
my $numbkeys = scalar keys %fusions;
print "Finished catologing fusion reads, now processing over $numbkeys potential fusion sites\n";
close(JUNCTION);
##Post Processing and Filtering
##currently, the process goes: create file.summary this file gets annotated (file.summary.annotated), and then this annotated file gets filtered and reduced to a new file, named file.summary
##it's somewhat confusing, but I think the output is most understandable this way.
#SETUP
my $fusioncounter =0;
open (SUMMTEMP, ">$outsummtemp") or die;
print SUMMTEMP "Partner1\tPartner2\tScore\tSpanningReads\tSplitReads\tTopsideCrossing\tBottomsideCrossing\tChromAAnchors\tChromBAnchors\tUniqueSupportLeft\tUniqueSupportRight\tKurtosis\tSkew\tLeftAnchor\tRightAnchor\tTopsideSpanning\tBottomsideSpanning\n";
my $keycount ;

#Join and Evaluate Fusions
for my $key (keys %fusions) {#go through all 'fusions'
	$keycount++ ;
	#first filter by read support
	if ($fusions{$key}[0][0] >=$Configs{splitReads} && $fusions{$key}[1][0] >=$Configs{splitReads}) {
                my @keyarray=split(/__/, $key); #0:chrm1 1:pos 2:chr2 3:pos2 4:strand 5:strand
                 #skip same-chrom proximal fusions
		if ($keyarray[0] eq $keyarray[2] && (abs($keyarray[1]-$keyarray[3])<=$Configs{samechrom_wiggle}) ){
               		next;
                }
		#skip lopsided fusions (ie all the read support is on one side)
		if ( ($fusions{$key}[2][1]+0.1)/($fusions{$key}[2][2]+0.1) >= $Configs{lopsidedupper} || ($fusions{$key}[2][1]+0.1)/($fusions{$key}[2][2]+0.1) <= $Configs{lopsidedlower}) {
			next;
		}
		my $topspancount = $fusions{$key}[2][0];
		my $bottomspancount = $fusions{$key}[2][5];
		##now we need to do a broad check for spanning reads that didn't map to the exact fusion location
		# I do this by doing a rough check for close locations.  This mostly works, but gets messy with larger values of $Configs{wiggle}, and when fusion sites are near each other on the same chromosome.
		# in those cases, take results with a grain of salt.
		if ($Configs{pairedend} eq "TRUE") {
			for my $key2 (keys %fusions) { #cycle through all the keys again
				next if ($key eq $key2); #skip itself
				if ($fusions{$key2}[2][0] >= 1 || $fusions{$key2}[2][5] >=1 ) { #we are only really interested in sites with spanning fusions
					my @key2array=split(/__/, $key2); #see above for indices
					next if ($key2array[0] eq $key2array[2] && (abs($key2array[1]-$key2array[3])<=$Configs{samechrom_wiggle}) ); #skip same chrom proximal
					#check if the fusion from keyarray (has jxn crossing) has the same coordinates (within $Configs{wiggle} bp) as $keyarray2
					if ($keyarray[4] eq $key2array[4] && $keyarray[5] eq $key2array[5] && $keyarray[0] eq $key2array[0] && $keyarray[2] eq $key2array[2] && (abs($keyarray[1]-$key2array[1])<=$Configs{wiggle}) && (abs($keyarray[3]-$key2array[3])<=$Configs{wiggle}) ) {
						#print "1: $key2 spans $key reads: $fusions{$key2}[2][0] sum before: $fusions{$key}[2][0]\n";
						$topspancount += $fusions{$key2}[2][0];
						$bottomspancount += $fusions{$key2}[2][5];
					}
					#check the inverse fusion
					elsif (&reversestrand($keyarray[4]) eq $key2array[5] && &reversestrand($keyarray[5]) eq $key2array[4] && $keyarray[0] eq $key2array[2] && $keyarray[2] eq $key2array[0] && (abs($keyarray[1]-$key2array[3])<=$Configs{wiggle}) && (abs($keyarray[3]-$key2array[1])<=$Configs{wiggle}) ) {
						$topspancount += $fusions{$key2}[2][5];
						$bottomspancount += $fusions{$key2}[2][0];
						#print "2: $key2 spans $key reads: $fusions{$key2}[2][0] sum before: $fusions{$key}[2][0]\n";
					}
				}
			}
		}
		#Second, filter on spanning read pairs
		my $spancount = $topspancount + $bottomspancount ;
		if ($spancount >= $Configs{spancutoff}) {
			#next get an estimate of the 'unique reads' mapped by looking at how many unique read support values there are
			my @array0; my @array1;
			my $leftanchor ; my $rightanchor;
	                for my $x (0..($readlength-1)) {
				#cycle across possible support positions.  create arrays of # of reads of support at each position.  (skip 0 read support) Also note largest overlap in read support
   	                	if ($fusions{$key}[0][$x] != 0) {
					push (@array0, $fusions{$key}[0][$x]);	$leftanchor = $x;}
				if ($fusions{$key}[1][$x] != 0) {
					push (@array1, $fusions{$key}[1][$x]); $rightanchor = $x;}
        	        }
                	my %count0; my %count1;
        	        @count0{@array0} =(); @count1{@array1} =(); #turn the arrays into hashes.
	                my $unique0=scalar keys %count0; my $unique1=scalar keys %count1; #count the unique hash indices.
			my @kurtosisarray;
               		for my $x (reverse (15..($readlength-16))) { push (@kurtosisarray, $fusions{$key}[0][$x]);}
			for my $x (15..($readlength-16)) { push (@kurtosisarray, $fusions{$key}[1][$x]);}
			my ($skew, $kurtosis)=&kurtosis(@kurtosisarray); #still calculating kurtosis, but not sure how useful it is.
			#filter by the number of these unique reads
                	if ($unique0 >= $Configs{uniqueReads} && $unique1 >= $Configs{uniqueReads}) {
				$fusioncounter++;
				my $position1; my $position2;
				my $splitreads = $fusions{$key}[2][1] + $fusions{$key}[2][2] ;
				# STAR outputs in columns 2,4 the 1st base of the intron around a fusion site.  I think the 1st base that we see is more intuitive.  So here I adjust.
				($position1, $position2) = &adjustposition($keyarray[1],$keyarray[4],$keyarray[3],$keyarray[5]);
				#0:split reads, 1:topsidesplit, 2:bottomsidesplit 3:spanreads 4;topspan 5;bottomspan 6:skew 7:chr1 8;loc1 9;strand1 10;chr2; 11;loc2; 12;strand2
				#The score is a work in progress.
				my $score = &fusionScore($splitreads,$fusions{$key}[2][1],$fusions{$key}[2][2],$spancount,$topspancount, $bottomspancount,$skew,$keyarray[0],$position1,$keyarray[4],$keyarray[2],$position2,$keyarray[5]);
				##Output. This can be changed as needed, but the first two columns need to be chr1:pos:str.  They are fed into coordinates2genes.sh for gene annotation later.
				print SUMMTEMP "$keyarray[0]:$position1:$keyarray[4]\t$keyarray[2]:$position2:$keyarray[5]\t$score\t$spancount\t$splitreads\t$fusions{$key}[2][1]\t$fusions{$key}[2][2]\t$fusions{$key}[2][3]\t$fusions{$key}[2][4]\t$unique0\t$unique1\t$kurtosis\t$skew\t$leftanchor\t$rightanchor\t$topspancount\t$bottomspancount\n";
				print "Filtered fusions count:$fusioncounter, searched $keycount\n";
			}
		}
	}
}
print "Total fusions passing read thresholds found: $fusioncounter\nThese fusions will now be filtered based on annotations\n";
close (SUMMTEMP);

### BEGIN SUBROUTINES ###
##also some reference info on cigar operators:
##cigar operators:
# M match
# I insertion (into the reference)
# D deletion from ref
# N skipped over ref seq
# S soft clipping
# H hard clipping
# P padding (silent deletion from padded ref)

# below subroutine modified from http://bioinfomative.blogspot.com/2012/07/parsing-cigar-and-md-fields-of-sambam.html
# Given a Cigar string return an estimate of the read length
sub splitCigar {
	no warnings 'uninitialized';
	my $string = $_[0];
	my @split = split(//, $string);
	my $count="";
	my %matches=();
	foreach my $x (0..$#split) {
		#print "$x: $split[$x]\n";
		if ($split[$x] =~ m/[0-9]/ ) {
			#print "number detected\t";
			$count .= $split[$x];
			#print "$count\n";
		}
		else {
			#print "non number $split[$x]\t";
			$matches{$split[$x]} += $count;
			$count=0;
			#print "$split[$x] : $matches{$split[$x]}\n";
		}
	}
	$matches{"S"} + $matches{"M"} + $matches{"I"};
}
sub supportCigar { #input: SJ line
##this goes through a line and fills in two arrays (which are part of a hash of array of arrays).
# The main goal is to get read support for the readlength around a fusion.  This fills in arrays outside those bounds, but that data is meaningless
# the reason is that only array points defined are global.  those created in the subroutine, stay here, so read support for two fusions at 1000nt outside the fusion will be concatenated.
# I could fix this by making the above definitions arbitrarily large, but the values still wouldn't hold meaningful information.
	my $fusionname = $_[$numbcolumns];
##deal with non-split reads, exit
        if ($_[$col_jxntype] eq "-1") {
		if ($_[($numbcolumns+1)] eq "1") {
			#mates are same orientation as the name
	        	$fusions{$fusionname}[2][0]++;
        		return;
		}
		if ($_[($numbcolumns+1)] eq "2")	{
			#mates are in the inverse orientation wrt the name
			$fusions{$fusionname}[2][5]++;
			return;
		}
	}
##count read support by side of fusion:
	$fusions{$fusionname}[2][$_[($numbcolumns+1)]]++;
##Left side of the fusion
  ## - strand
	if ($_[$col_strandA] eq "-") {
		my $supportindex = 0;  #support index should start at 0 and move up to read length.  this is the index that traverses the reference seq to add support.
		my $cigarA = $_[$col_cigarA];
		my @split = split(//, $cigarA);
		my $count="";
		EXITER: foreach my $x (0..$#split) { ##separate cigar terms into ind. characters
			if ($split[$x] =~ m/[0-9]/ ) {
				$count .= $split[$x]; #rejoin numbers
			}
			else { #when we have a complete cigar term
				if ($split[$x] eq "S") { } #do nothing for softclipping
				elsif ($split[$x] eq "M") { #on match, add read support for length of cigar M
					foreach my $y ($supportindex .. ($count+$supportindex)) {
						#print "adding 1 to $supportindex + $y which was $fusions{$fusionname}[0][$y]\n";
						$fusions{$fusionname}[0][$y]++;
					}
					$supportindex = $supportindex + $count ; #move the support index
				}
				#for padding and skipped ref (usually intron) and deletions move the support index without adding support
				#elsif ($split[$x] eq "p") { $supportindex =$supportindex + $count ;}
				elsif ($split[$x] eq "p") { $count=""; $fusions{$fusionname}[2][3]++; last EXITER ;}
				elsif ($split[$x] eq "N") { $supportindex =$supportindex + $count ;}
				elsif ($split[$x] eq "D") { $supportindex =$supportindex + $count ;}
				elsif ($split[$x] eq "I") { }#do nothing for insertion.  should count negatively, but no easy way to do this.
				$count="";
			}
		}
	}
  ## + strand
        if ($_[$col_strandA] eq "+") {
                my $supportindex = ($_[$col_FusionposA] - $_[$col_startposA]);  #support index should start at read length and move down to zero.  this is the index that traverses the reference seq to add support.
                #print "supportindex: $supportindex\t";
		my $cigarA = $_[$col_cigarA];
                my @split = split(//, $cigarA);
                my $count="";
                my $pskip=0;
		#pskip helps me deal with split/span support.  when the cigar has a P, it means that we're matching R1 + R2 to reference.  But we're only concerned with the partner on the fusion
		#On left side +/- you want the cigar after/before p.
		#On right side +/- you want the cigar before/after p.
                if ($cigarA =~ m/p/ ) {
                        $pskip = 1;
                }
		foreach my $x (0..$#split) { ##separate cigar terms
                        if ($split[$x] =~ m/[0-9,-]/ ) {
                                $count .= $split[$x];
                        }
                        else { #when we have a complete cigar term
                                if ($split[$x] eq "S") { } #do nothing for softclipping
                                elsif ($split[$x] eq "M") { #on match, add read support for length of cigar M
                                        if ($pskip ne "1") {
						foreach my $y (reverse (($supportindex-$count) .. $supportindex)) {
	                                        	$fusions{$fusionname}[0][$y]++;
        	                                }
                			}
		                        $supportindex = $supportindex - $count ; #move the support index
                                }
                                #for padding and skipped ref (usually intron) and deletions move the support index without adding support
                                elsif ($split[$x] eq "p") { $supportindex =$supportindex - $count ; $pskip =0; $fusions{$fusionname}[2][3]++;}
                                elsif ($split[$x] eq "N") { $supportindex =$supportindex - $count ;}
                                elsif ($split[$x] eq "D") { $supportindex =$supportindex - $count ;}
                                elsif ($split[$x] eq "I") { }#do nothing for insertion.  should count negatively, but no easy way to do this.
                        	#print "$supportindex\t$count\t$split[$x]\n";
				$count="";
                        }
                }
        }
	#print "we have fusion name $fusionname\n";
	#foreach my $f (0..($readlength-1)) {
	#	print "$fusions{$fusionname}[0][$f] ";
	#}
	#print "\n";
##Right side of the fusion
  ## + strand
        if ($_[$col_strandB] eq "+") {
                my $supportindex = 0;  #support index should start at 0 and move up to read length.  this is the index that traverses the reference seq to add support.
                my $cigarB = $_[$col_cigarB];
                my @split = split(//, $cigarB);
                my $count="";
                EXITER: foreach my $x (0..$#split) { ##separate cigar terms
                        if ($split[$x] =~ m/[0-9]/ ) {
                                $count .= $split[$x];
                        }
                        else { #when we have a complete cigar term
                                if ($split[$x] eq "S") { } #do nothing for softclipping
                                elsif ($split[$x] eq "M") { #on match, add read support for length of cigar M
                                        foreach my $y ($supportindex .. ($count+$supportindex)) {
                                                $fusions{$fusionname}[1][$y]++;
                                        }
                                        $supportindex = $supportindex + $count ; #move the support index
                                }
                                #for padding and skipped ref (usually intron) and deletions move the support index without adding support
                                #elsif ($split[$x] eq "p") { $supportindex =$supportindex + $count ;}
                               	elsif ($split[$x] eq "p") { $count=""; $fusions{$fusionname}[2][4]++; last EXITER ;}
				elsif ($split[$x] eq "N") { $supportindex =$supportindex + $count ;}
                                elsif ($split[$x] eq "D") { $supportindex =$supportindex + $count ;}
                                elsif ($split[$x] eq "I") { }#do nothing for insertion.  should count negatively, but no easy way to do this.
                                $count="";
                        }
                }
        }
  ## - strand
	if ($_[$col_strandB] eq "-") {
                my $supportindex = ($_[$col_FusionposB] - $_[$col_startposB]);  #support index should start at read length and move down to zero.  this is the index that traverses the reference seq to add support.
                my $cigarB = $_[$col_cigarB];
                my @split = split(//, $cigarB);
                my $count="";
		my $pskip=0;
		if ($cigarB =~ m/p/ ) {
			$pskip = 1;
		}
                foreach my $x (0..$#split) { ##separate cigar terms
                        if ($split[$x] =~ m/[0-9,-]/ ) {
                                $count .= $split[$x];
                        }
                        else { #when we have a complete cigar term
                                if ($split[$x] eq "S") { } #do nothing for softclipping
                                elsif ($split[$x] eq "M") { #on match, add read support for length of cigar M
                                        if ($pskip ne "1" ) {
						foreach my $y (reverse (($supportindex-$count) .. $supportindex)) {
                                	                $fusions{$fusionname}[1][$y]++;
                                       		}
					}
                                        $supportindex = $supportindex - $count ; #move the support index
                                }
                                #for padding and skipped ref (usually intron) and deletions move the support index without adding support
                                elsif ($split[$x] eq "p") { $supportindex =$supportindex - $count ; $pskip = 0;$fusions{$fusionname}[2][4]++;}
                                elsif ($split[$x] eq "N") { $supportindex =$supportindex - $count ;}
                                elsif ($split[$x] eq "D") { $supportindex =$supportindex - $count ;}
                                elsif ($split[$x] eq "I") { }#do nothing for insertion.  should count negatively, but no easy way to do this.
                                #print "$supportindex\t$count\t$split[$x]\n";
                                $count="";
                        }
                }
        }
}
sub reversestrand {
	if ($_[0] eq "+"){
		return "-";
	}
	elsif ($_[0] eq "-"){
		return "+";
	}
}

#this sub taken from user jkahn on perlmonks: http://www.perlmonks.org/?node_id=197793
sub revcompl { # operates on all elements passed in
  my (@dna) = @_;
  my @done;
  foreach my $segment (@dna) {
    my $revcomp = reverse($segment);
    $revcomp =~ tr/ACGTacgt/TGCAtgca/;
    push @done, $revcomp;
  }
  return @done; # or reverse @done;  # what's best semantics?
}
sub adjustposition { #takes in 0pos, 1strand, 2pos 3strand
	my $position1;
	my $position2;
	if ($_[1] eq "+") {
		$position1 = $_[0] -1;
	}
	elsif ($_[1] eq "-") {
		$position1 = $_[0] +1;
	}
	if ($_[3] eq "+") {
		$position2 = $_[2] +1;
	}
	elsif ($_[3] eq "-") {
		$position2 = $_[2] -1;
	}
	return ($position1, $position2);
}
sub unadjustposition { #reverse the effect of adjustposition
	#takes in 0pos, 1strand, 2pos 3strand
	my $position1;
        my $position2;
        if ($_[1] eq "+") {
                $position1 = $_[0] +1;
        }
        elsif ($_[1] eq "-") {
                $position1 = $_[0] -1;
        }
        if ($_[3] eq "+") {
                $position2 = $_[2] -1;
        }
        elsif ($_[3] eq "-") {
                $position2 = $_[2] +1;
        }
        return ($position1, $position2);
}

#credit: http://www.bagley.org/~doug/shootout/  slash http://dada.perl.it/shootout/moments.perl.html
sub kurtosis {
	my @nums=@_;
	#print "@nums\n";
	my $sum = 0;
	foreach (@nums) { $sum += $_ }
	my $n = scalar(@nums);
	my $mean = $sum/$n;
	my $average_deviation = 0;
	my $standard_deviation = 0;
	my $variance = 0;
	my $skew = 0;
	my $kurtosis = 0;
	foreach (@nums) {
   		my $deviation = $_ - $mean;
	 	$average_deviation += abs($deviation);
    		$variance += $deviation**2;
    		$skew += $deviation**3;
    		$kurtosis += $deviation**4;
	}
	$average_deviation /= $n;
	$variance /= ($n - 1);
	$standard_deviation = sqrt($variance);
	#print "variance:$variance ";
	if ($variance) {
		$skew /= ($n * $variance * $standard_deviation);
	    	$kurtosis = $kurtosis/($n * $variance * $variance) - 3.0;
		$kurtosis = substr($kurtosis, 0,5);
		$skew = substr($skew, 0,5);
	}
	#print "kurtosis:$kurtosis\n";
	return ($skew, $kurtosis);
}
sub fusionScore {
	my @params=@_; #0:split reads, 1:topsidesplit, 2:bottomsidesplit 3:spanreads 4;topspan 5;bottomspan 6:skew 7:chr1 8;loc1 9;strand1 10;chr2; 11;loc2; 12;strand2
	my $splitscore;
	# Score from Split Reads
	if ($params[1] >= $params[2]) {
		$splitscore = $params[0]/(($params[1]+1)/($params[2]+1));
	}
	else {$splitscore = $params[0]/(($params[2]+1)/($params[1]+1)); }
	my $spanscore;
	#Score from non-Split Reads
	if ($params[4] >= $params[5]) {
		$spanscore = $params[3]/(($params[4]+1)/($params[5]+1));
	}
	else { $spanscore = $params[3]/(($params[5]+1)/($params[4]+1)); }
	my $basescore = $splitscore/$Configs{splitscoremod} + $spanscore/$Configs{spanscoremod} ;
	#Skew Penalty
	if ($params[6] >=0.25 ) { $basescore = $basescore*$Configs{skewpenalty}; }
	#Read-through penalty
	if ($params[7] eq $params[10] && $params[9] eq $params[12] ) {
		my $dist = abs($params[8] - $params[11]);
		my $penalty = 20000/$dist;
		$basescore = $basescore - $penalty*$basescore ;
	}
	$basescore = sprintf "%.1f", $basescore;
	return($basescore);
}


text:
JamMinApp::JamMinApp()
:
	BApplication(ApplicationSignature),
	fMainWindow(NULL)
{
	//window constructor calls 'Show()'
	try {
		//fMainWindow = new JamMinWindow("Untitled");
		fOpenPanel = new BFilePanel;
		fRefFilter = new JMRefFilter();
		fOpenPanel->SetRefFilter(fRefFilter);
		fWindowCount = 0; // no windows yet
		fIsLaunchingWithRef = false;

	} catch (bad_alloc)	{
		AppReturnValue = B_NO_MEMORY;
		be_app->PostMessage(B_QUIT_REQUESTED);
	}
}

JamMinApp::~JamMinApp()
{
	DPRINT("JamMinApp::~JamMinApp()");
	delete fOpenPanel;
	delete fRefFilter;
	if (fMainWindow != NULL)
		if (fMainWindow->LockWithTimeout(30000000) == B_OK)	//Must Lock() before calling Quit()
			fMainWindow->Quit();	//Never delete a BWindow, call Quit() instead.
}

void JamMinApp::ReadyToRun()
{
	//A good place to set up windows, etc., just before your application is about to Run().
	if (!fIsLaunchingWithRef)
		fMainWindow = new JamMinWindow("Untitled");
}

void JamMinApp::Pulse()
{
	//Provides a "heartbeat" for your application; a good place to blink cursors, etc.
	//You set the pulse rate in BApplication::SetPulseRate().
}

void JamMinApp::MessageReceived(BMessage *message)
{
	switch(message->what)
	{
		case WINDOW_REGISTRY_ADD:
		{
			//only increment window counter and reply to sender
			DPRINT("JamMinApp::MessageReceived(): WINDOW_REGISTRY_ADD");
			BMessage reply(WINDOW_REGISTRY_ADDED);
			fWindowCount++;
			message->SendReply(&reply);
			break;
		}
		case WINDOW_REGISTRY_SUB:
			DPRINT("JamMinApp::MessageReceived(): WINDOW_REGISTRY_SUB");
			fWindowCount--;
			if (!fWindowCount) {
				//XXX - be_app->PostMessage(..)?
				Quit();
			}
			break;
		case MENU_FILE_OPEN:
			DPRINT("JamMinApp::MessageReceived(): MENU_FILE_OPEN");
			fOpenPanel->Show();
			break;

		default:
			BApplication::MessageReceived(message);
			break;
	}//switch
}

void
JamMinApp::RefsReceived(BMessage* message)
{
	DPRINT("JamMinApp::RefsReceived()");

	entry_ref ref;
	status_t err;
	int32 ref_num;
	ref_num = 0;
	if (IsLaunching()) {
		DPRINT("JamMinApp::RefsReceived: launching with ref");
		fIsLaunchingWithRef = true;
	}
	do {
		if ( (err = message->FindRef("refs", ref_num, &ref)) != B_OK ) {
			return;
		}
		DPRINT("ref " << ref_num << " received");
		//call window constructor
		new JamMinWindow(&ref);
		ref_num++;
	} while (1);
}


text:
package com.hazelcast.simulator.hz;

import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.DataSerializable;

import java.io.IOException;

public class DataSerializablePojo implements DataSerializable {
    private int id;

    public DataSerializablePojo() {
        // No-op.
    }

    public DataSerializablePojo(int id) {
        this.id = id;
    }

    public int id() {
        return id;
    }

    @Override
    public void writeData(ObjectDataOutput objectDataOutput) throws IOException {
        objectDataOutput.writeInt(id);
    }

    @Override
    public void readData(ObjectDataInput objectDataInput) throws IOException {
        this.id = objectDataInput.readInt();
    }

    @Override
    public String toString() {
        return "DataSerializablePojo{id=" + id + '}';
    }
}