text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

<title>The Response Variable | Become Great at R</title>
<meta name="generator" content="Jekyll v3.9.2" />
<meta property="og:title" content="The Response Variable" />
<meta name="author" content="Guangming Lang" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="When it comes to building models, it's crucial to understand the characteristics of the variable you want to predict. This variable is often called the response or target variable. First, it may be continuous (for example, housing prices, stock prices, drug compound's permeability, precipitation, and etc) or categorical (for example, fraud or not, default or not, good or bad, churned or not, 5 stages of sepsis and etc)." />
<meta property="og:description" content="When it comes to building models, it's crucial to understand the characteristics of the variable you want to predict. This variable is often called the response or target variable. First, it may be continuous (for example, housing prices, stock prices, drug compound's permeability, precipitation, and etc) or categorical (for example, fraud or not, default or not, good or bad, churned or not, 5 stages of sepsis and etc)." />
<link rel="canonical" href="http://localhost:4000/da/the-response-variable/" />
<meta property="og:url" content="http://localhost:4000/da/the-response-variable/" />
<meta property="og:site_name" content="Become Great at R" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2017-02-06T00:00:00+09:00" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:title" content="The Response Variable" />
<meta name="twitter:site" content="@" />
<meta name="twitter:creator" content="@Guangming Lang" />

  <link rel="stylesheet" href="/assets/css/main.css">
  <link rel="stylesheet" href="/assets/css/skins/default.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i|Lora:400,400i,700,700i">
  <link rel="alternate" type="application/atom+xml" title="Become Great at R" href="/atom.xml">

Skip links

Skip to primary navigation

Skip to content

Skip to footer

    Menu

About

R

Data Analysis

Books

Apps

Cartoon

Become Great at R

Master the R programming language

The Response Variable

        by Guangming Lang

1 min read

    <time class="page-date dt-published" datetime="2017-02-06T00:00:00+09:00">February 6, 2017
</time>

Categories

da

When it comes to building models, it's crucial to understand the characteristics of the variable you want to predict. This variable is often called the response or target variable. First, it may be continuous (for example, housing prices, stock prices, drug compound's permeability, precipitation, and etc) or categorical (for example, fraud or not, default or not, good or bad, churned or not, 5 stages of sepsis and etc).

Continuous responses may be symmetrically distributed (think of the Taj Mahal or the bell curve) or skewed (for example, income distribution often has a thin and long right tail). When it's skewed, certain models such as linear regression require us to transform it to be symmetric. BoxCox transformation is often used.

Categorical responses may have two levels or more than two levels. The levels maybe balanced or unbalanced. In the extreme case, the unbalanced situation is so severe that we call the minority class the rare event. For example, the number of clicks an online ad receives can be 1 out of every 1000 impressions. We often want to remedy the unbalanced distribution amongst the different classes before modeling. One method is to down-sample the majority class, and the other method is to up-sample the minority class.

Understanding the distribution of the response variable is critical for finding the most suitable way to partition the data. Not understanding the response characteristics can lead to computational difficulties for some models and sub-optimal and less robust predictive performances.

   Share
   Tweet
   LinkedIn
   Reddit

Previous

         R Parallel and Zombie Processes

Next

        Tips for Caret

© 2022 Become Great at R. Powered by Jekyll & So Simple.


text:
export EDITOR="vim"

# Larger bash history (allow 32³ entries; default is 500)
export HISTSIZE=32768
export HISTFILESIZE=$HISTSIZE
# Ignore duplicate entries and commands with leading spaces
export HISTCONTROL=ignoreboth
# Make some commands not show up in history
export HISTIGNORE="ls:cd:cd -:pwd:exit:date:* --help"

# Prefer English and use UTF-8
export LANG="en_US"
export LC_ALL="en_US.UTF-8"

# Highlight section titles in manual pages
export LESS_TERMCAP_md="$ORANGE"

# Don't clear the screen after quitting a manual page
export MANPAGER="less -X"

# Link Homebrew casks in `/Applications` rather than `~/Applications`
export HOMEBREW_CASK_OPTS="--appdir=/Applications"

# More convenient trigger sequence for fzf
export FZF_COMPLETION_TRIGGER=','

# Add previews to fzf shortcuts
export FZF_CTRL_T_OPTS="--preview '(highlight -O ansi -l {} 2> /dev/null || cat {} || tree -C {}) 2> /dev/null | head -200'"
export FZF_DEFAULT_OPTS='--height 80% --preview-window right:70%'

# Use ripgrep for fzf if installed
if command -v rg >/dev/null 2>&1; then
	export FZF_DEFAULT_COMMAND='rg --files --no-ignore --hidden --follow --glob "!.git/*"'
fi

redpajama_set_name: RedPajamaGithub


text:
package com.deftwun.zombiecopter.components;

import com.artemis.Component;
import com.artemis.PooledComponent;
import com.badlogic.gdx.utils.Pool.Poolable;

//Creates a weld joint when the defined fixture collides with another
public class StickyComponent extends PooledComponent{
	public String fixtureName = "";
	public boolean enabled = true;

	@Override
	public void reset() {
		enabled = true;
		fixtureName = "";
	}
}


text:
static char sFTTagKey;

@implementation NSObject (FTNSObjectTag)

- (NSInteger)ft_tag
{
	NSNumber *tag = objc_getAssociatedObject(self, &sFTTagKey);
	if(!tag) {
		return 0;
	}

	return [tag integerValue];
}

- (void)setFt_tag:(NSInteger)ft_tag
{
	if(ft_tag == 0) {
		objc_setAssociatedObject(self, &sFTTagKey, nil, OBJC_ASSOCIATION_ASSIGN);
	} else {
		objc_setAssociatedObject(self, &sFTTagKey, [NSNumber numberWithInteger:ft_tag], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
	}
}

@end


text:
namespace Syncify
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading.Tasks;

    internal static class NativeMethods
    {
        // https://stackoverflow.com/questions/57124243/winforms-dark-title-bar-on-windows-10
        private const int DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19;
        private const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;

        internal static bool UseImmersiveDarkMode(IntPtr handle, bool enabled)
        {
            if (IsWindows10OrGreater(17763))
            {
                var attribute = DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1;
                if (IsWindows10OrGreater(18985))
                {
                    attribute = DWMWA_USE_IMMERSIVE_DARK_MODE;
                }

                int useImmersiveDarkMode = enabled ? 1 : 0;
                return DwmSetWindowAttribute(handle, (int)attribute, ref useImmersiveDarkMode, sizeof(int)) == 0;
            }

            return false;
        }

        [DllImport("dwmapi.dll")]
        private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);

        private static bool IsWindows10OrGreater(int build = -1)
        {
            return Environment.OSVersion.Version.Major >= 10 && Environment.OSVersion.Version.Build >= build;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace MessagingServer
{
    public static class MessageCodes
    {
        public static Dictionary<int, string> MessageCodeDict { get; private set; }

        public static bool PopulateDictionary()
        {
            MessageCodeDict = new Dictionary<int, string>();
            using (StreamReader codeReader = new StreamReader("ProtocolCodes.txt"))
            {
                string protocolCodes = codeReader.ReadToEnd();
                if (string.IsNullOrEmpty(protocolCodes))
                    return false;
                string[] seperators = new string[] { ">", ";" };
                string[] results = protocolCodes.Split(seperators,
                    StringSplitOptions.RemoveEmptyEntries);
                char[] trimChars = new char[] { '\r', '\n' };
                for (int i = 0; i < results.Length; i++)
                    results[i] = results[i].TrimStart(trimChars);

                if (results.Length % 2 == 0)
                {
                    for (int i = 0; i < (results.Length / 2); i++)
                    {
                        int key;
                        if (int.TryParse(results[i * 2], out key))
                            MessageCodeDict.Add(key, results[(i * 2) + 1]);
                        else return false;
                    }
                    return true;
                }
                else return false;
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.apache.hadoop.mapreduce.lib.input (Hadoop 0.20.2+320 API)
</TITLE>

<META NAME="date" CONTENT="2010-06-28">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

org.apache.hadoop.mapreduce.lib.input

Classes

CombineFileInputFormat

CombineFileRecordReader

CombineFileSplit

FileInputFormat

FileSplit

LineRecordReader

SequenceFileInputFormat

SequenceFileRecordReader

TextInputFormat

Exceptions

InvalidInputException


text:
!function() {
  var $body = $('body'), bw = $body.width(), bh = $body.height();

  Reveal.addEventListener( 'ready', function( event ) {
    console.log('ready!')

    // make all list elements fragments
    $('li').addClass('fragment');

    // img hack-- if title is set, remove it and inject it into an inline style
    $('img').each(function(elm) {
      var $el = $(elm), oldStyle = $el.attr('style'), title = $el.attr('title');
      if(title) {
        $el.attr('style', oldStyle + ';' + title).attr('title', '');
      }
    });
  } );

  // Full list of configuration options available here:
  // https://github.com/hakimel/reveal.js#configuration
  Reveal.initialize({
    controls: true,
    progress: true,
    history: true,
    center: true,

    theme: Reveal.getQueryHash().theme, // available themes are in /css/theme
    transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/fade/none

    // Optional libraries used to extend on reveal.js
    dependencies: []
  });
}();


text:
package adaptableLearningRates;

import nTupleTD.TDParams;
import nTupleTD.UpdateParams;

/**
 * Wolfgang Konens non-linear extension of IDBD with tanh() as
 * activation-function.
 *
 * @author Markus Thill
 *
 */
public class IDBDwk extends LearningRates {

	/**
	 *
	 */
	private static final long serialVersionUID = 1225665101750973165L;
	public static final double IDBD_WK_BEST_BETA_INIT = -5.8;
	public static final double IDBD_WK_BEST_THETA = 1.0;
	public static final double IDBD_WK_BEST_OMEGA_K = 0.0;

	// ################################################
	// Incremental Delta-Bar-Delta Variables
	private float[] h; // has to be initialized with 0
	private float[] beta; // initialize as desired

	/**
	 * @param tdPar
	 *            User-defined parameters.
	 * @param length
	 *            Length of the corresponding weights-vector. For every weight a
	 *            learning-rate is maintained.
	 * @param com
	 *            For all weights of the system common parameters
	 */
	public IDBDwk(TDParams tdPar, int length, LRCommon com) {
		super(com, tdPar); // Set common parameters for all weights (k_acc,
							// GAMMA)
		createTables(length);
	}

	/**
	 * @param length
	 *            Length of the corresponding weights-vector. For every weight a
	 *            learning-rate is maintained.
	 */
	private void createTables(int length) {
		// Create tables for beta and h
		beta = new float[length];
		h = new float[length];
		for (int i = 0; i < length; i++) {
			beta[i] = (float) tdPar.idbdBetaInit;
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * adaptableLearningRates.LearningRates#getWeightChange(nTupleTD.UpdateParams
	 * )
	 */
	@Override
	public double getWeightChange(UpdateParams u_i) {
		// Calculate delta w_i for the addressed weight i
		IDBDwkCommon com = (IDBDwkCommon) this.com;
		double a = getLearningRate(u_i); // alpha_i = e^beta_i
		double x_i = u_i.e_i;
		double Y = u_i.derivY; // Y = 1 - y^2
		double omega_k = com.omega_k;
		double k_acc = com.k_acc;
		double deltaW = a * Y * x_i * u_i.delta - omega_k * k_acc * x_i * x_i
				* u_i.w_i;
		return deltaW; // return the weight change
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see adaptableLearningRates.LearningRates#preWeightUpdateTask(nTupleTD.
	 * UpdateParams)
	 */
	@Override
	public void preWeightUpdateTask(UpdateParams u_i) {
		// Called, before the weight i is updated
		int i = u_i.i;
		double idbd_theta = tdPar.idbdTheta;
		double Y = u_i.derivY;
		double deltaBeta = idbd_theta * Y * u_i.e_i * h[i] * u_i.delta;
		if (Math.abs(deltaBeta) > TDParams.IDBD_BETA_CHANGE_MAX)
			deltaBeta = (deltaBeta < 0 ? -1 : +1)
					* TDParams.IDBD_BETA_CHANGE_MAX;
		beta[i] += deltaBeta;

		// bound beta (lower bound)
		if (beta[i] < TDParams.BETA_LOWER_BOUND)
			beta[i] = (float) TDParams.BETA_LOWER_BOUND;
		// if (beta[i] > TDParams.BETA_UPPER_BOUND && USE_UPPER_BETA_BOUND)
		// beta[i] = (float) TDParams.BETA_UPPER_BOUND;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * adaptableLearningRates.LearningRates#getLearningRate(nTupleTD.UpdateParams
	 * )
	 */
	@Override
	public double getLearningRate(UpdateParams u_i) {
		// Calculate step-size for weight i
		return Math.exp(beta[u_i.i]);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see adaptableLearningRates.LearningRates#postWeightUpdateTask(nTupleTD.
	 * UpdateParams)
	 */
	@Override
	public void postWeightUpdateTask(UpdateParams u_i) {
		// Called after weight-update is performed
		IDBDwkCommon com = (IDBDwkCommon) this.com;
		int i = u_i.i;
		double x_i = u_i.e_i;
		double a_i = getLearningRate(u_i);
		double delta = u_i.delta;
		double Y = u_i.derivY;
		double Z = Y + 2 * u_i.y * delta;
		double omega_k = com.omega_k;
		double k_acc = com.k_acc;
		double xPlus = 1.0 - (a_i * Y * Z + omega_k * k_acc) * x_i * x_i;
		if (xPlus < 0)
			xPlus = 0;
		h[i] = (float) (h[i] * xPlus + a_i * Y * x_i * delta);

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * adaptableLearningRates.LearningRates#getBestParams(nTupleTD.TDParams)
	 */
	@Override
	public TDParams getBestParams(final TDParams tdPar) {
		TDParams bestTDPar = null;
		try {
			bestTDPar = (TDParams) tdPar.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}

		bestTDPar.idbdBetaInit = IDBD_WK_BEST_BETA_INIT;
		bestTDPar.idbdTheta = IDBD_WK_BEST_THETA;
		bestTDPar.idbdWKOmegak = IDBD_WK_BEST_OMEGA_K;

		// Elig-Traces: we choose the variant [rr]. Resetting and replacing
		// traces with lambda = 0.8
		bestTDPar.lambda = 0.8;
		bestTDPar.replacingTraces = true;
		bestTDPar.resetEligOnRandomMove = true;

		return bestTDPar;
	}

	/**
	 * @param tdPar
	 * @return A new set of common parameters for IDBD_WK
	 */
	public static LRCommon createCommonLR(TDParams tdPar) {
		return new IDBDwkCommon(tdPar);
	}

	/**
	 * Maintains two parameters, that are common for all weights of the system
	 * in IDBD_WK. The first parameter is k_acc, the second is omega_k (which is
	 * a constant). With omega_k = 0, we get the original IDBD-algorithm.
	 *
	 * @author Markus Thill
	 *
	 */
	public static class IDBDwkCommon implements LRCommon {
		private static final double GAMMA = 0.001;
		double k_acc = 0.0;
		double omega_k = 0.0;

		IDBDwkCommon(TDParams tdPar) {
			omega_k = tdPar.idbdWKOmegak;
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see
		 * adaptableLearningRates.LearningRates.LRCommon#commonPreUpdateTask
		 * (nTupleTD.UpdateParams)
		 */
		@Override
		public void commonPreUpdateTask(UpdateParams u) {
			// Only called once in time step t
			double y = u.y;
			k_acc = (1.0 - GAMMA) * k_acc + GAMMA * y * y;
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see
		 * adaptableLearningRates.LearningRates.LRCommon#commonGetLearningRate
		 * (nTupleTD.UpdateParams)
		 */
		@Override
		public double commonGetLearningRate(UpdateParams u_i) {
			return 0;
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see
		 * adaptableLearningRates.LearningRates.LRCommon#commonPostUpdateTask
		 * (nTupleTD.UpdateParams)
		 */
		@Override
		public void commonPostUpdateTask(UpdateParams u_i) {
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see java.lang.Object#toString()
		 */
		public String toString() {
			return "Common LR:\r\n k_acc: " + k_acc + "\r\n omega_k: "
					+ omega_k + "\r\n";
		}
	}

}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20210819203611 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Create catalog promotion';
    }

    public function up(Schema $schema): void
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE sylius_catalog_promotion (id INT AUTO_INCREMENT NOT NULL, code VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_1055865077153098 (code), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
    }

    public function down(Schema $schema): void
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE sylius_catalog_promotion');
    }
}


text:
#if !defined(BOOST_SPIRIT_TEST_QI_REAL_HPP)
#define BOOST_SPIRIT_TEST_QI_REAL_HPP

#include <climits>
#include <boost/math/concepts/real_concept.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/spirit/include/qi_char.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/qi_operator.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <boost/math/special_functions/sign.hpp>

#include "test.hpp"

///////////////////////////////////////////////////////////////////////////////
//  These policies can be used to parse thousand separated
//  numbers with at most 2 decimal digits after the decimal
//  point. e.g. 123,456,789.01
///////////////////////////////////////////////////////////////////////////////
template <typename T>
struct ts_real_policies : boost::spirit::qi::ureal_policies<T>
{
    //  2 decimal places Max
    template <typename Iterator, typename Attribute>
    static bool
    parse_frac_n(Iterator& first, Iterator const& last, Attribute& attr, int& frac_digits)
    {
        namespace qi = boost::spirit::qi;
        Iterator savef = first;
        bool r = qi::extract_uint<Attribute, 10, 1, 2, true>::call(first, last, attr);
        frac_digits = static_cast<int>(std::distance(savef, first));
        return r;
    }

    //  No exponent
    template <typename Iterator>
    static bool
    parse_exp(Iterator&, Iterator const&)
    {
        return false;
    }

    //  No exponent
    template <typename Iterator, typename Attribute>
    static bool
    parse_exp_n(Iterator&, Iterator const&, Attribute&)
    {
        return false;
    }

    //  Thousands separated numbers
    template <typename Iterator, typename Attribute>
    static bool
    parse_n(Iterator& first, Iterator const& last, Attribute& attr)
    {
        using boost::spirit::qi::uint_parser;
        namespace qi = boost::spirit::qi;

        uint_parser<unsigned, 10, 1, 3> uint3;
        uint_parser<unsigned, 10, 3, 3> uint3_3;

        T result = 0;
        if (parse(first, last, uint3, result))
        {
            bool hit = false;
            T n;
            Iterator save = first;

            while (qi::parse(first, last, ',') && qi::parse(first, last, uint3_3, n))
            {
                result = result * 1000 + n;
                save = first;
                hit = true;
            }

            first = save;
            if (hit)
                attr = result;
            return hit;
        }
        return false;
    }
};

template <typename T>
struct no_trailing_dot_policy : boost::spirit::qi::real_policies<T>
{
    static bool const allow_trailing_dot = false;
};

template <typename T>
struct no_leading_dot_policy : boost::spirit::qi::real_policies<T>
{
    static bool const allow_leading_dot = false;
};

template <typename T>
bool
compare(T n, double expected)
{
    T const eps = std::pow(10.0, -std::numeric_limits<T>::digits10);
    T delta = n - expected;
    return (delta >= -eps) && (delta <= eps);
}

///////////////////////////////////////////////////////////////////////////////
// A custom real type
struct custom_real
{
    double n;
    custom_real() : n(0) {}
    custom_real(double n_) : n(n_) {}
    friend bool operator==(custom_real a, custom_real b)
        { return a.n == b.n; }
    friend bool operator==(custom_real a, double b)
        { return a.n == b; }
    friend custom_real operator*(custom_real a, custom_real b)
        { return custom_real(a.n * b.n); }
    friend custom_real operator+(custom_real a, custom_real b)
        { return custom_real(a.n + b.n); }
    friend custom_real operator-(custom_real a, custom_real b)
        { return custom_real(a.n - b.n); }
};

#endif


text:
id: bad87dee1348bd9aede07836
title: Use an id Attribute to Style an Element
challengeType: 0
videoUrl: 'https://scrimba.com/c/cakyZfL'
forumTopicId: 18339
dashedName: use-an-id-attribute-to-style-an-element
---

# --description--

One cool thing about `id` attributes is that, like classes, you can style them using CSS.

However, an `id` is not reusable and should only be applied to one element. An `id` also has a higher specificity (importance) than a class so if both are applied to the same element and have conflicting styles, the styles of the `id` will be applied.

Here's an example of how you can take your element with the `id` attribute of `cat-photo-element` and give it the background color of green. In your `style` element:

```css
#cat-photo-element {
  background-color: green;
}
```

Note that inside your `style` element, you always reference classes by putting a `.` in front of their names. You always reference ids by putting a `#` in front of their names.

# --instructions--

Try giving your form, which now has the `id` attribute of `cat-photo-form`, a green background.

# --hints--

Your `form` element should have the id of `cat-photo-form`.

```js
assert($('form').attr('id') === 'cat-photo-form');
```

Your `form` element should have the `background-color` of green.

```js
assert($('#cat-photo-form').css('background-color') === 'rgb(0, 128, 0)');
```

Your `form` element should have an `id` attribute.

```js
assert(
  code.match(/<form.*cat-photo-form.*>/gi) &&
    code.match(/<form.*cat-photo-form.*>/gi).length > 0
);
```

You should not give your `form` any `class` or `style` attributes.

```js
assert(!code.match(/<form.*style.*>/gi) && !code.match(/<form.*class.*>/gi));
```

# --seed--

## --seed-contents--

```html
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<style>
  .red-text {
    color: red;
  }

  h2 {
    font-family: Lobster, monospace;
  }

  p {
    font-size: 16px;
    font-family: monospace;
  }

  .thick-green-border {
    border-color: green;
    border-width: 10px;
    border-style: solid;
    border-radius: 50%;
  }

  .smaller-image {
    width: 100px;
  }

  .silver-background {
    background-color: silver;
  }
</style>

<h2 class="red-text">CatPhotoApp</h2>
<main>
  <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>

  <a href="#"><img class="smaller-image thick-green-border" src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>

  <div class="silver-background">
    <p>Things cats love:</p>
    <ul>
      <li>cat nip</li>
      <li>laser pointers</li>
      <li>lasagna</li>
    </ul>
    <p>Top 3 things cats hate:</p>
    <ol>
      <li>flea treatment</li>
      <li>thunder</li>
      <li>other cats</li>
    </ol>
  </div>

  <form action="https://freecatphotoapp.com/submit-cat-photo" id="cat-photo-form">
    <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
    <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
    <label><input type="checkbox" name="personality" checked> Loving</label>
    <label><input type="checkbox" name="personality"> Lazy</label>
    <label><input type="checkbox" name="personality"> Energetic</label><br>
    <input type="text" placeholder="cat photo URL" required>
    <button type="submit">Submit</button>
  </form>
</main>
```

# --solutions--

```html
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<style>
  .red-text {
    color: red;
  }

  h2 {
    font-family: Lobster, monospace;
  }

  p {
    font-size: 16px;
    font-family: monospace;
  }

  .thick-green-border {
    border-color: green;
    border-width: 10px;
    border-style: solid;
    border-radius: 50%;
  }

  .smaller-image {
    width: 100px;
  }

  .silver-background {
    background-color: silver;
  }

  #cat-photo-form {
    background-color: green;
  }
</style>

<h2 class="red-text">CatPhotoApp</h2>
<main>
  <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>

  <a href="#"><img class="smaller-image thick-green-border" src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>

  <div class="silver-background">
    <p>Things cats love:</p>
    <ul>
      <li>cat nip</li>
      <li>laser pointers</li>
      <li>lasagna</li>
    </ul>
    <p>Top 3 things cats hate:</p>
    <ol>
      <li>flea treatment</li>
      <li>thunder</li>
      <li>other cats</li>
    </ol>
  </div>

  <form action="https://freecatphotoapp.com/submit-cat-photo" id="cat-photo-form">
    <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
    <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
    <label><input type="checkbox" name="personality" checked> Loving</label>
    <label><input type="checkbox" name="personality"> Lazy</label>
    <label><input type="checkbox" name="personality"> Energetic</label><br>
    <input type="text" placeholder="cat photo URL" required>
    <button type="submit">Submit</button>
  </form>
</main>
```


text:
This test verifies applied indentation whenever you hit enter in "{|}" or type in "}" while inside opened block.

{} {}
  {}
  {

    {


text:
/*
 * $Id$
 */

package org.lockss.plugin.edinburgh;

import java.io.*;
import org.lockss.util.*;
import org.lockss.test.*;

/*
 *  Edinburgh changed skins in 2016. Leaving in the old filtering so long as it doesn't
 *  break anything. Adding in new filtering to cover new content layout
 *  TODO: update the test once the filtering is stable
 */

public class TestEdinburghHashHtmlFilterFactory extends LockssTestCase {
  static String ENC = Constants.DEFAULT_ENCODING;

  private EdinburghUniversityPressHashHtmlFilterFactory fact;
  private MockArchivalUnit mau;

  public void setUp() throws Exception {
    super.setUp();
    fact = new EdinburghUniversityPressHashHtmlFilterFactory();
    mau = new MockArchivalUnit();
  }

  private static final String withCitations = "
"
      + ""
      + "
"
      + "
"
      + "
Cited by
"
      + "
 "
      + "Comparative Critical Studies"
      + ""
      + ""
      + "Citation"
      + ""
      + "<input type=\"image\" alt=\"Pdf With References\""
      + "src=\"/templates/jsp/_style2/_eup/images/icon_toolBar_pdf.gif\"/>"
      + "

";

  private static final String withoutCitations = "
"
      + "  "
      + "
";

  private static final String mainNavHtml ="
"
      + "
 "
      + "

 Home

"
      + "

Information Zone

"
      + "

\"Serials Department, Green Library\"

"
      + "

";

  private static final String mainNavHtmlFiltered = "";

  private static final String institutionBannerHtml ="
"
      + "
 "
      + "

 Home

"
      + "

Information Zone

"
      + "

\"Serials Department, Green Library\"

"
      + "

";

  private static final String institutionBannerFiltered = "
"
      + "
 "
      + "

 Home

"
      + "

 Information Zone

"
      + "

";

  private static final String emptyString = "";
  private static final String mastHead =
      "
" +
          "
" +
          "
" +
          "
" +
          "
Help

" +
          "

Shibboleth

" +
          "

" +
          "                Register" +
          "

" +
          "
" +
          "            " +
          "
" +
          "                Log In" +
          "
" +
          "
" +
          "
" +
          "
" +
          "
";
  private static final String advSearch = "

";

  private static final String mainBreadCrumb =
      "
" +
          "        Journals >" +
          "        JournalTitlew >" +
          "            All Issues >" +
          "            JANUARY 1997" +
          "
";

  private static final String journalTitleContainer =
      "
" +
          "
Title
" +
          "
" +
          "    <form action=\"/action/doSearch\" class=\"search\" method=\"get\"><fieldset>" +
          "            <legend>Search</legend>" +
          "            Search" +
          "           <input id=\"globalSearchField\" class=\"text\" type=\"search\" name=\"searchText\" value=\"\">" +
          "            <input class=\"button\" type=\"image\" value=\"\" src=\"/templates.gif\" alt=\"go\">" +
          "
Advanced Search
" +
          "        </fieldset></form>" +
          "
" +
          "
";

  private static final String hasAuthorsLink = "
Voice and Pronouns in Foghorn Leghorn's The UnSayable
"+
      "
"+
      "Llewellyn Brown

Citation Information. "+
      "<journal-title xmlns:mml=\"http://www.w3.org/1998/Math/MathML\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">Journal of Animation Studies</journal-title>";
  private static final String withoutAuthorsLink = "
Voice and Pronouns in Foghorn Leghorn's The UnSayable
"+
      "
 Citation Information. "+
      " <journal-title xmlns:mml=\"http://www.w3.org/1998/Math/MathML\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">Journal of Animation Studies </journal-title>";

  private static final String hasCurrentIssue = "
"+
     "
Current Issue: Sep 2011

Issue: Volume 20, Number 2
"+
     "
";
  private static final String withoutCurrentIssue = "";

  private static final String hasTrackCitations = "Track Citations";
  private static final String withoutTrackCitations = "";

  private static final String accessIcon =
      "
" +
      "
	";

  public void testAccessIconFiltering() throws Exception {
    InputStream actIn = fact.createFilteredInputStream(mau, new StringInputStream(accessIcon),
        Constants.DEFAULT_ENCODING);
    assertEquals(emptyString, StringUtil.fromInputStream(actIn));
  }

  public void testCitationsFiltering() throws Exception {
    InputStream actIn = fact.createFilteredInputStream(mau, new StringInputStream(withCitations),
        Constants.DEFAULT_ENCODING);
    assertEquals(withoutCitations, StringUtil.fromInputStream(actIn));
  }

  public void testInstitutionBannerFiltering() throws Exception {
    InputStream actIn = fact.createFilteredInputStream(mau, new StringInputStream(institutionBannerHtml),
        Constants.DEFAULT_ENCODING);
    assertEquals(institutionBannerFiltered, StringUtil.fromInputStream(actIn));
  }

  public void testMainNavFiltering() throws Exception {
    InputStream actIn = fact.createFilteredInputStream(mau, new StringInputStream(mainNavHtml),
        Constants.DEFAULT_ENCODING);
    assertEquals(mainNavHtmlFiltered, StringUtil.fromInputStream(actIn));
  }

  public void testTopFiltering() throws Exception {
    InputStream actIn = fact.createFilteredInputStream(mau, new StringInputStream(mastHead),
        Constants.DEFAULT_ENCODING);
    assertEquals(emptyString, StringUtil.fromInputStream(actIn));

    actIn = fact.createFilteredInputStream(mau, new StringInputStream(advSearch),
        Constants.DEFAULT_ENCODING);
    assertEquals(emptyString, StringUtil.fromInputStream(actIn));

    actIn = fact.createFilteredInputStream(mau, new StringInputStream(mainBreadCrumb),
        Constants.DEFAULT_ENCODING);
    assertEquals(emptyString, StringUtil.fromInputStream(actIn));

    actIn = fact.createFilteredInputStream(mau, new StringInputStream(journalTitleContainer),
        Constants.DEFAULT_ENCODING);
    assertEquals(emptyString, StringUtil.fromInputStream(actIn));
  }

  public void testPollFiltering() throws Exception {
    InputStream actIn = fact.createFilteredInputStream(mau, new StringInputStream(hasAuthorsLink),
        Constants.DEFAULT_ENCODING);
    assertEquals(withoutAuthorsLink, StringUtil.fromInputStream(actIn));

    actIn = fact.createFilteredInputStream(mau, new StringInputStream(hasCurrentIssue),
        Constants.DEFAULT_ENCODING);
    assertEquals(withoutCurrentIssue, StringUtil.fromInputStream(actIn));
    actIn = fact.createFilteredInputStream(mau, new StringInputStream(withCitations),
        Constants.DEFAULT_ENCODING);
    assertEquals(withoutCitations, StringUtil.fromInputStream(actIn));
  }

}


text:
<!-- : Begin batch script
cscript //nologo "%~f0?.wsf"
call %TEMP%/resetvars.bat
exit /b

----- Begin wsf script --->
<job><script language="VBScript">
  Set oShell = WScript.CreateObject("WScript.Shell")
  filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
  Set objFileSystem = CreateObject("Scripting.fileSystemObject")
  Set oFile = objFileSystem.CreateTextFile(filename, TRUE)

  set oEnv=oShell.Environment("System")
  for each sitem in oEnv
      oFile.WriteLine("SET " & sitem)
  next
  path = oEnv("PATH")

  set oEnv=oShell.Environment("User")
  for each sitem in oEnv
      oFile.WriteLine("SET " & sitem)
  next

  path = path & ";" & oEnv("PATH")
  oFile.WriteLine("SET PATH=" & path)
  oFile.Close
</script></job>


text:
module.exports = function (hljs) {
  var IDENT_RE_RU = '[a-zA-Zа-яА-Я][a-zA-Z0-9_а-яА-Я]*';
  var OneS_KEYWORDS = 'возврат дата для если и или иначе иначеесли исключение конецесли ' +
    'конецпопытки конецпроцедуры конецфункции конеццикла константа не перейти перем ' +
    'перечисление по пока попытка прервать продолжить процедура строка тогда фс функция цикл ' +
    'число экспорт';
  var OneS_BUILT_IN = 'ansitooem oemtoansi ввестивидсубконто ввестидату ввестизначение ' +
    'ввестиперечисление ввестипериод ввестиплансчетов ввестистроку ввестичисло вопрос ' +
    'восстановитьзначение врег выбранныйплансчетов вызватьисключение датагод датамесяц ' +
    'датачисло добавитьмесяц завершитьработусистемы заголовоксистемы записьжурналарегистрации ' +
    'запуститьприложение зафиксироватьтранзакцию значениевстроку значениевстрокувнутр ' +
    'значениевфайл значениеизстроки значениеизстрокивнутр значениеизфайла имякомпьютера ' +
    'имяпользователя каталогвременныхфайлов каталогиб каталогпользователя каталогпрограммы ' +
    'кодсимв командасистемы конгода конецпериодаби конецрассчитанногопериодаби ' +
    'конецстандартногоинтервала конквартала конмесяца коннедели лев лог лог10 макс ' +
    'максимальноеколичествосубконто мин монопольныйрежим названиеинтерфейса названиенабораправ ' +
    'назначитьвид назначитьсчет найти найтипомеченныенаудаление найтиссылки началопериодаби ' +
    'началостандартногоинтервала начатьтранзакцию начгода начквартала начмесяца начнедели ' +
    'номерднягода номерднянедели номернеделигода нрег обработкаожидания окр описаниеошибки ' +
    'основнойжурналрасчетов основнойплансчетов основнойязык открытьформу открытьформумодально ' +
    'отменитьтранзакцию очиститьокносообщений периодстр полноеимяпользователя получитьвремята ' +
    'получитьдатута получитьдокументта получитьзначенияотбора получитьпозициюта ' +
    'получитьпустоезначение получитьта прав праводоступа предупреждение префиксавтонумерации ' +
    'пустаястрока пустоезначение рабочаядаттьпустоезначение рабочаядата разделительстраниц ' +
    'разделительстрок разм разобратьпозициюдокумента рассчитатьрегистрына ' +
    'рассчитатьрегистрыпо сигнал симв символтабуляции создатьобъект сокрл сокрлп сокрп ' +
    'сообщить состояние сохранитьзначение сред статусвозврата стрдлина стрзаменить ' +
    'стрколичествострок стрполучитьстроку  стрчисловхождений сформироватьпозициюдокумента ' +
    'счетпокоду текущаядата текущеевремя типзначения типзначениястр удалитьобъекты ' +
    'установитьтана установитьтапо фиксшаблон формат цел шаблон';
  var DQUOTE = {className: 'dquote', begin: '""'};
  var STR_START = {
    className: 'string',
    begin: '"', end: '"|$',
    contains: [DQUOTE],
    relevance: 0
  };
  var STR_CONT = {
    className: 'string',
    begin: '\\|', end: '"|$',
    contains: [DQUOTE]
  };

  return {
    case_insensitive: true,
    lexems: IDENT_RE_RU,
    keywords: {keyword: OneS_KEYWORDS, built_in: OneS_BUILT_IN},
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.NUMBER_MODE,
      STR_START, STR_CONT,
      {
        className: 'function',
        begin: '(процедура|функция)', end: '$',
        lexems: IDENT_RE_RU,
        keywords: 'процедура функция',
        contains: [
          {className: 'title', begin: IDENT_RE_RU},
          {
            className: 'tail',
            endsWithParent: true,
            contains: [
              {
                className: 'params',
                begin: '\\(', end: '\\)',
                lexems: IDENT_RE_RU,
                keywords: 'знач',
                contains: [STR_START, STR_CONT]
              },
              {
                className: 'export',
                begin: 'экспорт', endsWithParent: true,
                lexems: IDENT_RE_RU,
                keywords: 'экспорт',
                contains: [hljs.C_LINE_COMMENT_MODE]
              }
            ]
          },
          hljs.C_LINE_COMMENT_MODE
        ]
      },
      {className: 'preprocessor', begin: '#', end: '$'},
      {className: 'date', begin: '\'\\d{2}\\.\\d{2}\\.(\\d{2}|\\d{4})\''}
    ]
  };
};


text:
 <!--
  Copyright (c) Microsoft Corporation. All rights reserved.
  Licensed under the MIT License. See License.txt in the project root for license information.
-->

<rules>
  <rule id="Feed.Core.1005" category="core" target="feed" specificationsection ="2.2.6.3.2" requirementlevel="should" format="json" version="v2" metadata="true">
    <description>The nextURINVP SHOULD include a Skip Token System Query Option to indicate that the URI addresses the subsequent partial set of entities.</description>
    <action processor="xslt+jsonschema">
      <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="text"/>
        <xsl:template match="/">
          {
          "additionalProperties" : false,
          "type" : "object",
          "properties" : {

          "d" : {
          "additionalProperties" : false,
          "type" : "object",
          "properties" : {

          "results" : {
          "required" : true,
          "type" : "any",
          },

          <xsl:apply-templates select="*[local-name()='Edmx']/*[local-name()='DataServices']"/>
          }
          }

          }
          }
        </xsl:template>
        <xsl:template match="*[local-name()='Edmx']/*[local-name()='DataServices']">
          "__next" : { "type" : "string", "pattern" : "\\$skiptoken", "required" : false }
        </xsl:template>
      </xsl:stylesheet>
    </action>
  </rule>
</rules>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>HibernateUtil</title>
<meta name="date" content="2013-09-05">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.puntodeventa.services.DAO

Class HibernateUtil

java.lang.Object

com.puntodeventa.services.DAO.HibernateUtil

public class HibernateUtil
extends java.lang.Object

Hibernate Utility class with a convenient method to get Session Factory
 object.

Constructor Summary

Constructors

Constructor and Description

HibernateUtil()

Method Summary

Methods

Modifier and Type
Method and Description

static org.hibernate.SessionFactory
getSessionFactory()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HibernateUtil

public HibernateUtil()

Method Detail

getSessionFactory

public static org.hibernate.SessionFactory getSessionFactory()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/home_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="@dimen/button_top_margin"
        android:cropToPadding="false"
        android:padding="30dip"
        android:src="@drawable/stroke" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/home_image"
        android:background="@color/red"
        android:orientation="vertical"
        android:weightSum="1">

        <TextView
            android:id="@+id/maintitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/home_image"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="@dimen/button_top_margin"
            android:layout_marginTop="@dimen/button_top_margin"
            android:text="@string/home_title"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/white"
            android:typeface="monospace" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/maintitle"
         >

            <Button
                android:id="@+id/quickMeasurementButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|center_horizontal"
                android:layout_marginLeft="@dimen/home_button_sidemargin"
                android:layout_marginRight="@dimen/home_button_sidemargin"
                android:layout_marginTop="@dimen/button_top_margin"
                android:background="@drawable/custom_home_button_selector"
                android:text="@string/mainbutton_quick"
                android:textColor="@drawable/textcolorhome" />
        </LinearLayout>
    </LinearLayout>
</RelativeLayout><!-- From: file:/home/andrew/Projects/HeartRateMonitor/app/src/main/res/layout/home.xml -->


text:
import csv
from os.path import dirname, isfile
import numpy as np
from multiprocessing import Pool
import warnings
from sklearn.externals.joblib import Parallel, delayed

from oddt import toolkit
from oddt.scoring import scorer, ensemble_model
from oddt.scoring.descriptors.binana import binana_descriptor
from oddt.scoring.models.regressors import neuralnetwork

# numpy after pickling gives Runtime Warnings
warnings.simplefilter("ignore", RuntimeWarning)

# define sub-function for paralelization
def generate_descriptor(packed):
    pdbid, gen, pdbbind_dir, pdbbind_version = packed
    protein_file = pdbbind_dir + "/v" + pdbbind_version + "/%s/%s_pocket.pdb" % (pdbid, pdbid)
    if not isfile(protein_file):
        protein_file = pdbbind_dir + "/v" + pdbbind_version + "/%s/%s_protein.pdb" % (pdbid, pdbid)
    ligand_file = pdbbind_dir + "/v" + pdbbind_version + "/%s/%s_ligand.sdf" % (pdbid, pdbid)
    protein = toolkit.readfile("pdb", protein_file).next()
    # mark it as a protein
    protein.protein = True
    ligand = toolkit.readfile("sdf", ligand_file).next()
    return gen.build([ligand], protein).flatten()

# skip comments and merge multiple spaces
def _csv_file_filter(f):
    for row in open(f, 'rb'):
        if row[0] == '#':
            continue
        yield ' '.join(row.split())

def _parallel_helper(obj, methodname, *args, **kwargs):
    """Private helper to workaround Python 2 pickle limitations"""
    return getattr(obj, methodname)(*args, **kwargs)

class nnscore(scorer):
    def __init__(self, protein = None, n_jobs = -1, **kwargs):
        self.protein = protein
        self.n_jobs = n_jobs
        model = None
        decsriptors = binana_descriptor(protein)
        super(nnscore,self).__init__(model, decsriptors, score_title='nnscore')

    def gen_training_data(self, pdbbind_dir, pdbbind_version = '2007', sf_pickle = ''):
        # build train and test
        cpus = self.n_jobs if self.n_jobs > 0 else None
        pool = Pool(processes=cpus)

        core_act = np.zeros(1, dtype=float)
        core_set = []
        pdb_set = 'core'
        if pdbbind_version == '2007':
            csv_file = '%s/v%s/INDEX.%s.%s.data' % (pdbbind_dir, pdbbind_version, pdbbind_version, pdb_set)
        else:
            csv_file = '%s/v%s/INDEX_%s_data.%s' % (pdbbind_dir, pdbbind_version, pdb_set, pdbbind_version)
        for row in csv.reader(_csv_file_filter(csv_file), delimiter=' '):
            pdbid = row[0]
            if not isfile('%s/v%s/%s/%s_pocket.pdb' % (pdbbind_dir, pdbbind_version, pdbid, pdbid)):
                continue
            act = float(row[3])
            core_set.append(pdbid)
            core_act = np.vstack((core_act, act))

        result = pool.map(generate_descriptor, [(pdbid, self.descriptor_generator, pdbbind_dir, pdbbind_version) for pdbid in core_set])
        core_desc = np.vstack(result)
        core_act = core_act[1:]

        refined_act = np.zeros(1, dtype=float)
        refined_set = []
        pdb_set = 'refined'
        if pdbbind_version == '2007':
            csv_file = '%s/v%s/INDEX.%s.%s.data' % (pdbbind_dir, pdbbind_version, pdbbind_version, pdb_set)
        else:
            csv_file = '%s/v%s/INDEX_%s_data.%s' % (pdbbind_dir, pdbbind_version, pdb_set, pdbbind_version)
        for row in csv.reader(_csv_file_filter(csv_file), delimiter=' '):
            pdbid = row[0]
            if not isfile('%s/v%s/%s/%s_pocket.pdb' % (pdbbind_dir, pdbbind_version, pdbid, pdbid)):
                continue
            act = float(row[3])
            if pdbid in core_set:
                continue
            refined_set.append(pdbid)
            refined_act = np.vstack((refined_act, act))

        result = pool.map(generate_descriptor, [(pdbid, self.descriptor_generator, pdbbind_dir, pdbbind_version) for pdbid in refined_set])
        refined_desc = np.vstack(result)
        refined_act = refined_act[1:]

        self.train_descs = refined_desc
        self.train_target = refined_act.flatten()
        self.test_descs = core_desc
        self.test_target = core_act.flatten()

        # save numpy arrays
        np.savetxt(dirname(__file__) + '/NNScore/train_descs.csv', self.train_descs, fmt='%.5g', delimiter=',')
        np.savetxt(dirname(__file__) + '/NNScore/train_target.csv', self.train_target, fmt='%.2f', delimiter=',')
        np.savetxt(dirname(__file__) + '/NNScore/test_descs.csv', self.test_descs, fmt='%.5g', delimiter=',')
        np.savetxt(dirname(__file__) + '/NNScore/test_target.csv', self.test_target, fmt='%.2f', delimiter=',')

    def train(self, sf_pickle = ''):
        # load precomputed descriptors and target values
        self.train_descs = np.loadtxt(dirname(__file__) + '/NNScore/train_descs.csv', delimiter=',', dtype=float)
        self.train_target = np.loadtxt(dirname(__file__) + '/NNScore/train_target.csv', delimiter=',', dtype=float)
        self.test_descs = np.loadtxt(dirname(__file__) + '/NNScore/test_descs.csv', delimiter=',', dtype=float)
        self.test_target = np.loadtxt(dirname(__file__) + '/NNScore/test_target.csv', delimiter=',', dtype=float)

        n_dim = (~((self.train_descs == 0).all(axis=0) | (self.train_descs.min(axis=0) == self.train_descs.max(axis=0)))).sum()

        # number of network to sample; original implementation did 1000, but 100 give results good enough.
        n = 1000
        trained_nets = Parallel(n_jobs=self.n_jobs)(delayed(_parallel_helper)(neuralnetwork([n_dim,5,1]), 'fit', self.train_descs, self.train_target, train_alg='tnc', maxfun=1000) for i in xrange(n))
        # get 20 best
        best_idx = np.array([net.score(self.test_descs, self.test_target.flatten()) for net in trained_nets]).argsort()[::-1][:20]
        self.model = ensemble_model([trained_nets[i] for i in best_idx])

        r2 = self.model.score(self.test_descs, self.test_target)
        r = np.sqrt(r2)
        print 'Test set: R**2:', r2, ' R:', r

        r2 = self.model.score(self.train_descs, self.train_target)
        r = np.sqrt(r2)
        print 'Train set: R**2:', r2, ' R:', r

        if sf_pickle:
            return self.save(sf_pickle)
        else:
            return self.save('NNScore.pickle')

    @classmethod
    def load(self, filename = ''):
        if not filename:
            for f in ['NNScore.pickle', dirname(__file__) + '/NNScore.pickle']:
                if isfile(f):
                    filename = f
                    break
        # if still no pickle found - train function from pregenerated descriptors
        if not filename:
            print "No pickle, training new scoring function."
            nn = nnscore()
            filename = nn.train()
        return scorer.load(filename)


text:
"""
Commands for adapters.
"""

from __future__ import absolute_import

import click

import zhmcclient
from .zhmccli import cli
from ._helper import print_properties, print_resources, abort_if_false, \
    options_to_properties, original_options, COMMAND_OPTIONS_METAVAR, \
    click_exception, add_options, LIST_OPTIONS
from ._cmd_cpc import find_cpc

def find_adapter(cmd_ctx, client, cpc_or_name, adapter_name):
    """
    Find an adapter by name and return its resource object.
    """
    if isinstance(cpc_or_name, zhmcclient.Cpc):
        cpc = cpc_or_name
    else:
        cpc = find_cpc(cmd_ctx, client, cpc_or_name)
    # The CPC must be in DPM mode. We don't check that because it would
    # cause a GET to the CPC resource that we otherwise don't need.
    try:
        adapter = cpc.adapters.find(name=adapter_name)
    except zhmcclient.Error as exc:
        raise click_exception(exc, cmd_ctx.error_format)
    return adapter

@cli.group('adapter', options_metavar=COMMAND_OPTIONS_METAVAR)
def adapter_group():
    """
    Command group for managing adapters (DPM mode only).

    Physical adapters (e.g. OSA, FICON) are auto-discovered and cannot be
    created. Logical adapters (HiperSockets) can be created and deleted.

    The commands in this group work only on CPCs in DPM mode.

    In addition to the command-specific options shown in this help text, the
    general options (see 'zhmc --help') can also be specified right after the
    'zhmc' command name.
    """

@adapter_group.command('list', options_metavar=COMMAND_OPTIONS_METAVAR)
@click.argument('CPC', type=str, metavar='CPC')
@click.option('--type', is_flag=True, required=False, hidden=True)
@add_options(LIST_OPTIONS)
@click.pass_obj
def adapter_list(cmd_ctx, cpc, **options):
    """
    List the adapters in a CPC.

    In addition to the command-specific options shown in this help text, the
    general options (see 'zhmc --help') can also be specified right after the
    'zhmc' command name.
    """
    cmd_ctx.execute_cmd(lambda: cmd_adapter_list(cmd_ctx, cpc, options))

@adapter_group.command('show', options_metavar=COMMAND_OPTIONS_METAVAR)
@click.argument('CPC', type=str, metavar='CPC')
@click.argument('ADAPTER', type=str, metavar='ADAPTER')
@click.pass_obj
def adapter_show(cmd_ctx, cpc, adapter):
    """
    Show the details of an adapter.

    The following properties are shown in addition to those returned by the HMC:

    \b
      - 'parent-name' - Name of the parent CPC.
      - 'network-port-names' - Names of the Adapter Ports referenced by
        'network-port-uris' if present (for network adapters, index-correlated).
      - 'network-port-indexes' - Indexes of the Adapter Ports referenced by
        'network-port-uris' if present (for network adapters, index-correlated).
      - 'storage-port-names' - Names of the Adapter Ports referenced by
        'storage-port-uris' if present (for storage adapters, index-correlated).
      - 'storage-port-indexes' - Indexes of the Adapter Ports referenced by
        'storage-port-uris' if present (for storage adapters, index-correlated).

    In addition to the command-specific options shown in this help text, the
    general options (see 'zhmc --help') can also be specified right after the
    'zhmc' command name.
    """
    cmd_ctx.execute_cmd(lambda: cmd_adapter_show(cmd_ctx, cpc, adapter))

@adapter_group.command('update', options_metavar=COMMAND_OPTIONS_METAVAR)
@click.argument('CPC', type=str, metavar='CPC')
@click.argument('ADAPTER', type=str, metavar='ADAPTER')
@click.option('--name', type=str, required=False,
              help='The new name of the adapter.')
@click.option('--description', type=str, required=False,
              help='The new description of the adapter.')
@click.option('--port-description', type=str, required=False,
              help='The new description of the single port of the adapter.')
@click.option('--mtu-size', type=click.Choice(['8', '16', '32', '56']),
              required=False,
              help='The new MTU size of the adapter in KiB. '
              '(HiperSockets only).')
@click.option('--allowed-capacity', type=int, required=False,
              help='The maximum number of HBAs per partition. '
              '(FCP only).')
@click.option('--chpid', type=str, required=False,
              help='Channel path ID (CHPID, 2 hex chars) used by the '
              'adapter\'s port. '
              '(OSA, FICON, HiperSockets only).')
@click.option('--crypto-number', type=int, required=False,
              help='Identifier of the crypto adapter in the range 0-15 '
              'Must be unique within the CPC. '
              '(Crypto only).')
@click.option('--crypto-tke/--no-crypto-tke', default=None, required=False,
              help='Permit TKE commands on the crypto adapter. '
              '(Crypto only).')
@click.pass_obj
def adapter_update(cmd_ctx, cpc, adapter, **options):
    """
    Update the properties of an adapter.

    Only the properties will be changed for which a corresponding option is
    specified, so the default for all options is not to change properties.

    The adapter may be a physical adapter (e.g. a discovered OSA card) or a
    logical adapter (e.g. HiperSockets).

    In addition to the command-specific options shown in this help text, the
    general options (see 'zhmc --help') can also be specified right after the
    'zhmc' command name.
    """
    cmd_ctx.execute_cmd(lambda: cmd_adapter_update(cmd_ctx, cpc, adapter,
                                                   options))

@adapter_group.command('create', options_metavar=COMMAND_OPTIONS_METAVAR)
@click.argument('CPC', type=str, metavar='CPC')
@click.option('--name', type=str, required=True,
              help='The name of the new adapter.')
@click.option('--description', type=str, required=False,
              help='The description of the new adapter. Default: empty')
@click.option('--port-description', type=str, required=False,
              help='The description of the (single) port of the new adapter. '
              'Default: empty')
@click.option('--mtu-size', type=click.Choice(['8', '16', '32', '56']),
              required=False,
              help='The MTU size of the new adapter in KiB. Default: 8')
@click.pass_obj
def adapter_create_hipersocket(cmd_ctx, cpc, **options):
    """
    Create a HiperSockets adapter in a CPC.

    In addition to the command-specific options shown in this help text, the
    general options (see 'zhmc --help') can also be specified right after the
    'zhmc' command name.

    Some more properties of the new HiperSockets adapter can be set via
    adapter update.
    """
    cmd_ctx.execute_cmd(
        lambda: cmd_adapter_create_hipersocket(cmd_ctx, cpc, options))

@adapter_group.command('delete', options_metavar=COMMAND_OPTIONS_METAVAR)
@click.argument('CPC', type=str, metavar='CPC')
@click.argument('ADAPTER', type=str, metavar='ADAPTER')
@click.option('-y', '--yes', is_flag=True, callback=abort_if_false,
              expose_value=False,
              help='Skip prompt to confirm deletion of the adapter.',
              prompt='Are you sure you want to delete this adapter ?')
@click.pass_obj
def adapter_delete_hipersocket(cmd_ctx, cpc, adapter):
    """
    Delete a HiperSockets adapter.

    In addition to the command-specific options shown in this help text, the
    general options (see 'zhmc --help') can also be specified right after the
    'zhmc' command name.
    """
    cmd_ctx.execute_cmd(
        lambda: cmd_adapter_delete_hipersocket(cmd_ctx, cpc, adapter))

@adapter_group.command('list-nics', options_metavar=COMMAND_OPTIONS_METAVAR)
@click.argument('CPC', type=str, metavar='CPC')
@click.argument('ADAPTER', type=str, metavar='ADAPTER')
@add_options(LIST_OPTIONS)
@click.pass_obj
def adapter_list_nics(cmd_ctx, cpc, adapter, **options):
    """
    List the NICs backed by a network adapter in a CPC.

    In addition to the command-specific options shown in this help text, the
    general options (see 'zhmc --help') can also be specified right after the
    'zhmc' command name.
    """
    cmd_ctx.execute_cmd(
        lambda: cmd_adapter_list_nics(cmd_ctx, cpc, adapter, options))

def cmd_adapter_list(cmd_ctx, cpc_name, options):
    # pylint: disable=missing-function-docstring

    client = zhmcclient.Client(cmd_ctx.session)
    cpc = find_cpc(cmd_ctx, client, cpc_name)

    try:
        adapters = cpc.adapters.list()
    except zhmcclient.Error as exc:
        raise click_exception(exc, cmd_ctx.error_format)

    if options['type']:
        click.echo("The --type option is deprecated and type information "
                   "is now always shown.")

    show_list = [
        'name',
        'cpc',
    ]
    if not options['names_only']:
        show_list.extend([
            'adapter-id',
            'status',
            'adapter-family',
            'type',
            'detected-card-type',
            'crypto-type',
            'card-location',
        ])
    if options['uri']:
        show_list.extend([
            'object-uri',
        ])

    cpc_additions = {}
    for adapter in adapters:
        cpc_additions[adapter.uri] = cpc_name
    additions = {
        'cpc': cpc_additions,
    }

    try:
        print_resources(cmd_ctx, adapters, cmd_ctx.output_format, show_list,
                        additions, all=options['all'])
    except zhmcclient.Error as exc:
        raise click_exception(exc, cmd_ctx.error_format)

def cmd_adapter_show(cmd_ctx, cpc_name, adapter_name):
    # pylint: disable=missing-function-docstring

    client = zhmcclient.Client(cmd_ctx.session)
    adapter = find_adapter(cmd_ctx, client, cpc_name, adapter_name)

    try:
        adapter.pull_full_properties()
    except zhmcclient.Error as exc:
        raise click_exception(exc, cmd_ctx.error_format)

    properties = dict(adapter.properties)

    # Add artificial property 'parent-name'
    properties['parent-name'] = cpc_name

    # Add artificial properties 'network-port-names', 'network-port-indexes'
    try:
        netport_uris = adapter.properties['network-port-uris']
    except KeyError:
        pass
    else:
        # It is a network adapter
        netport_names = []
        netport_indexes = []
        for netport_uri in netport_uris:
            netport_props = client.session.get(netport_uri)
            netport_names.append(netport_props['name'])
            netport_indexes.append(netport_props['index'])
        properties['network-port-names'] = netport_names
        properties['network-port-indexes'] = netport_indexes

    # Add artificial properties 'storage-port-names', 'storage-port-indexes'
    try:
        stoport_uris = adapter.properties['storage-port-uris']
    except KeyError:
        pass
    else:
        # It is a storage adapter
        stoport_names = []
        stoport_indexes = []
        for stoport_uri in stoport_uris:
            # For unconfigurd FICON adapters, the 'storage-port-uris' property
            # is set, but Get Adapter Properties fails with 404,4
            try:
                stoport_props = client.session.get(stoport_uri)
            except zhmcclient.HTTPError as exc:
                if exc.http_status == 404 and exc.reason == 4:
                    # Unconfigured FICON adapter
                    pass
                else:
                    raise
            else:
                stoport_names.append(stoport_props['name'])
                stoport_indexes.append(stoport_props['index'])
        properties['storage-port-names'] = stoport_names
        properties['storage-port-indexes'] = stoport_indexes

    print_properties(cmd_ctx, properties, cmd_ctx.output_format)

def cmd_adapter_update(cmd_ctx, cpc_name, adapter_name, options):
    # pylint: disable=missing-function-docstring

    client = zhmcclient.Client(cmd_ctx.session)
    adapter = find_adapter(cmd_ctx, client, cpc_name, adapter_name)

    name_map = {
        'mtu-size': 'maximum-transmission-unit-size',
        'chpid': 'channel-path-id',
        'crypto-tke': 'tke-commands-enabled',
    }
    org_options = original_options(options)
    properties = options_to_properties(org_options, name_map)

    if not properties:
        cmd_ctx.spinner.stop()
        click.echo("No properties specified for updating adapter '{a}'.".
                   format(a=adapter_name))
        return

    try:
        adapter.update_properties(properties)
    except zhmcclient.Error as exc:
        raise click_exception(exc, cmd_ctx.error_format)

    cmd_ctx.spinner.stop()
    if 'name' in properties and properties['name'] != adapter_name:
        click.echo("Adapter '{a}' has been renamed to '{an}' and was updated.".
                   format(a=adapter_name, an=properties['name']))
    else:
        click.echo("Adapter '{a}' has been updated.".format(a=adapter_name))

def cmd_adapter_create_hipersocket(cmd_ctx, cpc_name, options):
    # pylint: disable=missing-function-docstring

    client = zhmcclient.Client(cmd_ctx.session)
    cpc = find_cpc(cmd_ctx, client, cpc_name)

    name_map = {
        'mtu-size': 'maximum-transmission-unit-size',
    }
    org_options = original_options(options)
    properties = options_to_properties(org_options, name_map)

    try:
        new_adapter = cpc.adapters.create_hipersocket(properties)
    except zhmcclient.Error as exc:
        raise click_exception(exc, cmd_ctx.error_format)

    cmd_ctx.spinner.stop()
    click.echo("New HiperSockets adapter '{a}' has been created.".
               format(a=new_adapter.properties['name']))

def cmd_adapter_delete_hipersocket(cmd_ctx, cpc_name, adapter_name):
    # pylint: disable=missing-function-docstring

    client = zhmcclient.Client(cmd_ctx.session)
    adapter = find_adapter(cmd_ctx, client, cpc_name, adapter_name)

    try:
        adapter.delete()
    except zhmcclient.Error as exc:
        raise click_exception(exc, cmd_ctx.error_format)

    cmd_ctx.spinner.stop()
    click.echo("HiperSockets adapter '{a}' has been deleted.".
               format(a=adapter_name))

def cmd_adapter_list_nics(cmd_ctx, cpc_name, adapter_name, options):
    # pylint: disable=missing-function-docstring

    client = zhmcclient.Client(cmd_ctx.session)
    adapter = find_adapter(cmd_ctx, client, cpc_name, adapter_name)

    adapter_family = adapter.get_property('adapter-family')
    adapter_type = adapter.get_property('type')

    if adapter_family not in ('hipersockets', 'osa', 'roce', 'cna'):
        raise click_exception(
            "Adapter {f!r} on CPC {c} is not a network adapter".
            format(f=adapter.name, c=cpc_name), cmd_ctx.error_format)

    if adapter_type == 'osm':
        raise click_exception(
            "Adapter {f!r} on CPC {c} is an OSM adapter and cannot be "
            "assigned to partitions".
            format(f=adapter.name, c=cpc_name), cmd_ctx.error_format)

    results = []  # tuple(partition, nic, port_index)
    partitions = adapter.list_assigned_partitions()
    for part in partitions:
        nics = part.nics.list()
        for nic in nics:
            try:
                vswitch_uri = nic.get_property('virtual-switch-uri')
            except KeyError:
                pass
            else:
                vswitch_props = client.session.get(vswitch_uri)
                backing_adapter_uri = vswitch_props['backing-adapter-uri']
                backing_port_index = vswitch_props['port']
            try:
                port_uri = nic.get_property('network-adapter-port-uri')
            except KeyError:
                pass
            else:
                port_props = client.session.get(port_uri)
                backing_adapter_uri = port_props['parent']
                backing_port_index = port_props['index']

            if backing_adapter_uri == adapter.uri:
                results.append((part, nic, backing_port_index))

    show_list = [
        'name',
        'partition',
    ]
    if not options['names_only']:
        show_list.extend([
            'type',
            'port-index',
        ])
    if options['uri']:
        show_list.extend([
            'element-uri',
        ])

    partition_additions = {}
    port_index_additions = {}
    for part, nic, port_index in results:
        partition_additions[nic.uri] = part.name
        port_index_additions[nic.uri] = port_index
    additions = {
        'partition': partition_additions,
        'port-index': port_index_additions,
    }

    nics = [nic for _, nic, _ in results]
    try:
        print_resources(cmd_ctx, nics, cmd_ctx.output_format, show_list,
                        additions, all=options['all'])
    except zhmcclient.Error as exc:
        raise click_exception(exc, cmd_ctx.error_format)


text:
namespace SpeedSlidingTrainer.Core.Model.State.Validation
{
    public enum ValidationType
    {
        BoardState,
        BoardTemplate,
        BoardGoal,
    }
}


text:
{% extends "v2/base.html" %}
{% block content %}

{{_('Inventory list')}}

            <input type="text" class="form-control typeahead" placeholder="Search" name="search" id="search">

                <button class="btn btn-default" type="submit"></button>

Browse by Category

                  {{_('Guest Supplies')}}

              {% for i in supplies %}

 i.reorder and i.remaining <= 1.2*i.reorder %}alert-warning{% endif %}{% if i.remaining <= i.reorder %}alert-danger{% endif %}{% if i.remaining > 1.2*i.reorder %}alert-ok{% endif %}">

{% if i.reorder > 0 %}{% endif %}{% if i.reorder == 0 %}{% endif %} {{i.name}}

{{i.remaining}}

              {% endfor %}

                  {{_('Guest Hampers')}}

              {% for i in hampers %}

 i.reorder and i.remaining <= 1.2*i.reorder %}alert-warning{% endif %}{% if i.remaining <= i.reorder %}alert-danger{% endif %}{% if i.remaining > 1.2*i.reorder %}alert-ok{% endif %}">

{% if i.reorder > 0 %}{% endif %}{% if i.reorder == 0 %}{% endif %} {{i.name}}

{{i.remaining}}

              {% endfor %}

                  {{_('Kitchenware')}}

              {% for i in kitchenware %}

 i.reorder and i.remaining <= 1.2*i.reorder %}alert-warning{% endif %}{% if i.remaining <= i.reorder %}alert-danger{% endif %}{% if i.remaining > 1.2*i.reorder %}alert-ok{% endif %}">

{% if i.reorder > 0 %}{% endif %}{% if i.reorder == 0 %}{% endif %} {{i.name}}

{{i.remaining}}

              {% endfor %}

Browse by Shelf

          {% for s in shelves %}

              <button class="btn btn-default">{{s}}</button>

          {% endfor %}

{% endblock %}


text:
namespace cv
{
  class Mat;
}

namespace fovis
{
  class VisualOdometry;
}

namespace fovis_ros
{

namespace visualization
{
  cv::Mat paint(const fovis::VisualOdometry* odometry);
} // end of namespace visualization

} // end of namespace fovis_ros

#endif


text:
var express = require('express');
var app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.set('views', './views');
app.listen(3000, function() {
  console.log('Server started');
});

app.get('/', function(req, res) {
  res.render('home');
});


text:
import org.mcupdater.ravenbot.util.ServerPing;

import java.io.IOException;
import java.net.InetSocketAddress;

public class CheckServer {

	public static void main(String[] args) {
		ServerPing test = new ServerPing();
		test.setAddress(new InetSocketAddress(args[0], Integer.parseInt(args[1])));
		try {
			ServerPing.StatusResponse status = test.fetchData();
			System.out.println(status.getDescription() + " (" + status.getPlayers().getOnline() + "/" + status.getPlayers().getMax() + ")");
			if (status.getModinfo() != null) {
				System.out.println("Mod list:");
				for (ServerPing.ModData mod : status.getModinfo().getModList()) {
					System.out.println("   " + mod.getModid() + ": " + mod.getVersion());
				}
			} else {
				System.out.println("Unmodded server");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


text:
/*! \file */
/* ************************************************************************
 * Copyright (C) 2019-2022 Advanced Micro Devices, Inc. All rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * ************************************************************************ */

#include "rocsparse_enum.hpp"
#include "testing.hpp"

template <typename T>
void testing_nnz_bad_arg(const Arguments& arg)
{
    static const size_t safe_size = 100;

    // Create rocsparse handle
    rocsparse_local_handle local_handle;

    // Create descriptor
    rocsparse_local_mat_descr local_descr;

    rocsparse_handle          handle                 = local_handle;
    rocsparse_direction       dir                    = rocsparse_direction_row;
    rocsparse_int             m                      = safe_size;
    rocsparse_int             n                      = safe_size;
    const rocsparse_mat_descr descr                  = local_descr;
    const T*                  A                      = (const T*)0x4;
    rocsparse_int             ld                     = safe_size;
    rocsparse_int*            nnz_per_row_columns    = (rocsparse_int*)0x4;
    rocsparse_int*            nnz_total_dev_host_ptr = (rocsparse_int*)0x4;

#define PARAMS handle, dir, m, n, descr, A, ld, nnz_per_row_columns, nnz_total_dev_host_ptr
    auto_testing_bad_arg(rocsparse_nnz<T>, PARAMS);

    CHECK_ROCSPARSE_ERROR(rocsparse_set_mat_storage_mode(descr, rocsparse_storage_mode_unsorted));
    EXPECT_ROCSPARSE_STATUS(rocsparse_nnz<T>(PARAMS), rocsparse_status_not_implemented);
#undef PARAMS
}

template <typename T>
void testing_nnz(const Arguments& arg)
{
    rocsparse_int       M    = arg.M;
    rocsparse_int       N    = arg.N;
    rocsparse_direction dirA = arg.direction;
    rocsparse_int       LD   = arg.denseld;

    rocsparse_local_handle    handle;
    rocsparse_local_mat_descr descrA;

    //
    // Argument sanity check before allocating invalid memory
    //
    if(M <= 0 || N <= 0 || LD < M)
    {
        rocsparse_status expected_status = (((M == 0 && N >= 0) || (M >= 0 && N == 0)) && (LD >= M))
                                               ? rocsparse_status_success
                                               : rocsparse_status_invalid_size;

        EXPECT_ROCSPARSE_STATUS(
            rocsparse_nnz<T>(handle, dirA, M, N, descrA, nullptr, LD, nullptr, nullptr),
            expected_status);

        if(rocsparse_status_success == expected_status)
        {
            rocsparse_int h_nnz = 77;
            CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host));

            EXPECT_ROCSPARSE_STATUS(
                rocsparse_nnz<T>(handle, dirA, M, N, descrA, nullptr, LD, nullptr, nullptr),
                rocsparse_status_success);

            EXPECT_ROCSPARSE_STATUS(
                rocsparse_nnz<T>(handle, dirA, M, N, descrA, nullptr, LD, nullptr, &h_nnz),
                rocsparse_status_success);

            EXPECT_ROCSPARSE_STATUS(0 == h_nnz ? rocsparse_status_success
                                               : rocsparse_status_internal_error,
                                    rocsparse_status_success);

            h_nnz = 139;
            device_vector<rocsparse_int> d_nnz(1);
            CHECK_HIP_ERROR(hipMemcpy(
                (rocsparse_int*)d_nnz, &h_nnz, sizeof(rocsparse_int) * 1, hipMemcpyHostToDevice));

            CHECK_ROCSPARSE_ERROR(
                rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_device));
            EXPECT_ROCSPARSE_STATUS(
                rocsparse_nnz<T>(handle, dirA, M, N, descrA, nullptr, LD, nullptr, nullptr),
                rocsparse_status_success);

            EXPECT_ROCSPARSE_STATUS(
                rocsparse_nnz<T>(
                    handle, dirA, M, N, descrA, nullptr, LD, nullptr, (rocsparse_int*)d_nnz),
                rocsparse_status_success);

            CHECK_HIP_ERROR(hipMemcpy(
                &h_nnz, (rocsparse_int*)d_nnz, sizeof(rocsparse_int) * 1, hipMemcpyDeviceToHost));

            EXPECT_ROCSPARSE_STATUS(0 == h_nnz ? rocsparse_status_success
                                               : rocsparse_status_internal_error,
                                    rocsparse_status_success);
        }

        return;
    }

    //
    // Create the dense matrix.
    //
    rocsparse_int MN = (dirA == rocsparse_direction_row) ? M : N;

    host_vector<T>             h_A(LD * N);
    host_vector<rocsparse_int> h_nnzPerRowColumn(MN);
    host_vector<rocsparse_int> hd_nnzPerRowColumn(MN);
    host_vector<rocsparse_int> h_nnzTotalDevHostPtr(1);
    host_vector<rocsparse_int> hd_nnzTotalDevHostPtr(1);

    // Allocate device memory
    device_vector<T>             d_A(LD * N);
    device_vector<rocsparse_int> d_nnzPerRowColumn(MN);
    device_vector<rocsparse_int> d_nnzTotalDevHostPtr(1);
    if(!h_nnzPerRowColumn || !d_nnzPerRowColumn || !d_A)
    {
        CHECK_HIP_ERROR(hipErrorOutOfMemory);
        return;
    }

    //
    // Initialize a random matrix.
    //
    rocsparse_seedrand();

    //
    // Initialize the entire allocated memory.
    //
    for(rocsparse_int i = 0; i < LD; ++i)
    {
        for(rocsparse_int j = 0; j < N; ++j)
        {
            h_A[j * LD + i] = -1;
        }
    }

    //
    // Random initialization of the matrix.
    //
    for(rocsparse_int i = 0; i < M; ++i)
    {
        for(rocsparse_int j = 0; j < N; ++j)
        {
            h_A[j * LD + i] = random_generator<T>(0, 4);
        }
    }

    //
    // Transfer.
    //
    CHECK_HIP_ERROR(hipMemcpy(d_A, h_A, sizeof(T) * LD * N, hipMemcpyHostToDevice));

    //
    // Unit check.
    //
    if(arg.unit_check)
    {
        //
        // Compute the reference host first.
        //
        host_nnz<T>(dirA, M, N, h_A, LD, h_nnzPerRowColumn, h_nnzTotalDevHostPtr);

        //
        // Pointer mode device for nnz and call.
        //
        CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_device));
        CHECK_ROCSPARSE_ERROR(rocsparse_nnz<T>(
            handle, dirA, M, N, descrA, d_A, LD, d_nnzPerRowColumn, d_nnzTotalDevHostPtr));

        //
        // Transfer.
        //
        CHECK_HIP_ERROR(hipMemcpy(hd_nnzPerRowColumn,
                                  d_nnzPerRowColumn,
                                  sizeof(rocsparse_int) * MN,
                                  hipMemcpyDeviceToHost));
        CHECK_HIP_ERROR(hipMemcpy(hd_nnzTotalDevHostPtr,
                                  d_nnzTotalDevHostPtr,
                                  sizeof(rocsparse_int) * 1,
                                  hipMemcpyDeviceToHost));

        //
        // Check results.
        //
        hd_nnzPerRowColumn.unit_check(h_nnzPerRowColumn);
        hd_nnzTotalDevHostPtr.unit_check(h_nnzTotalDevHostPtr);

        //
        // Pointer mode host for nnz and call.
        //
        rocsparse_int dh_nnz;
        CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host));
        CHECK_ROCSPARSE_ERROR(
            rocsparse_nnz<T>(handle, dirA, M, N, descrA, d_A, LD, d_nnzPerRowColumn, &dh_nnz));

        //
        // Transfer.
        //
        CHECK_HIP_ERROR(hipMemcpy(hd_nnzPerRowColumn,
                                  d_nnzPerRowColumn,
                                  sizeof(rocsparse_int) * MN,
                                  hipMemcpyDeviceToHost));

        //
        // Check results.
        //
        hd_nnzPerRowColumn.unit_check(h_nnzPerRowColumn);
        unit_check_scalar(dh_nnz, h_nnzTotalDevHostPtr[0]);
    }

    if(arg.timing)
    {
        int number_cold_calls = 2;
        int number_hot_calls  = arg.iters;
        CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host));

        //
        // Warm-up
        //
        rocsparse_int h_nnz;
        for(int iter = 0; iter < number_cold_calls; ++iter)
        {
            CHECK_ROCSPARSE_ERROR(
                rocsparse_nnz<T>(handle, dirA, M, N, descrA, d_A, LD, d_nnzPerRowColumn, &h_nnz));
        }

        double gpu_time_used = get_time_us();
        {
            //
            // Performance run
            //
            for(int iter = 0; iter < number_hot_calls; ++iter)
            {
                CHECK_ROCSPARSE_ERROR(rocsparse_nnz<T>(
                    handle, dirA, M, N, descrA, d_A, LD, d_nnzPerRowColumn, &h_nnz));
            }
        }
        gpu_time_used = (get_time_us() - gpu_time_used) / number_hot_calls;

        double gbyte_count = nnz_gbyte_count<T>(M, N, dirA);

        double gpu_gbyte = get_gpu_gbyte(gpu_time_used, gbyte_count);

        display_timing_info("M",
                            M,
                            "N",
                            N,
                            "LD",
                            LD,
                            "nnz",
                            h_nnz,
                            "dir",
                            rocsparse_direction2string(dirA),
                            s_timing_info_bandwidth,
                            gpu_gbyte,
                            s_timing_info_time,
                            get_gpu_time_msec(gpu_time_used));
    }
}

#define INSTANTIATE(TYPE)                                          \
    template void testing_nnz_bad_arg<TYPE>(const Arguments& arg); \
    template void testing_nnz<TYPE>(const Arguments& arg)
INSTANTIATE(float);
INSTANTIATE(double);
INSTANTIATE(rocsparse_float_complex);
INSTANTIATE(rocsparse_double_complex);
void testing_nnz_extra(const Arguments& arg) {}


text:
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, continue: true */
/*global require, exports */

(function () {
    "use strict";

    var async = require("async");
    var process_runner = require("./process_runner.js");
    var config = require("./config.js");
    var utils = require("./utils.js");
    var fs = require("fs");
    var os = require("os");
    var conffile = require("./conffile.js");
    var hostapdconf = require("./hostapdconf.js");
    var winston = require("./logger").winston;

    var formatTempOutput = function (temp) {

        temp = temp / 1000;
        var out = {};

        if (!config.USE_CELCIUS) {
            temp = utils.celsiusToFarenheit(temp);
        }

        temp = Math.ceil(temp);

        out.cpuTemp = temp;
        out.tempScale = (config.USE_CELCIUS) ? "celcius" : "farenheit";

        return out;
    };

	var getCPUTemp = function (callback) {

        var out = {};
		var tmp;
		if (config.TEST) {
			tmp = 54072;

            out = formatTempOutput(tmp);
            callback(null, out);
			return;
		}

		fs.readFile("/sys/class/thermal/thermal_zone0/temp", {encoding: "ascii"},
			function (err, data) {
				if (err) {
                    winston.error("Error Reading System Temp");
                    winston.error(err);
					callback(err);
					return;
                }

                //todo: this is wrong
				tmp = parseInt(data, 10); //convert to number
                out = formatTempOutput(tmp);

				callback(null, out);
			});
	};

	var getGPUTemp = function (callback) {
	};

    var restartUDHCPD = function (callback) {
        //service udhcpd restart 2>&1 >/dev/null
        process_runner.exec("service", ["udhcpd", "restart"], callback);
    };

    var restartAPD = function (callback) {
        //service hostapd restart 2>&1 >/dev/null
        process_runner.exec("service", ["hostapd", "restart"], callback);
    };

    var readRestrictedAccessList = function (callback) {
        fs.readFile(config.HOSTAPD_RESTRICTED_ADDRESSES_PATH,
                    {encoding: "utf8"},
            function (err, data) {
                var addresses = data.split(os.EOL);
                callback(null, addresses);
            }
            );
    };

    var saveRestrictedAccessList = function (addresses, callback) {
        var tmp = addresses.join(os.EOL);
        fs.writeFile(config.HOSTAPD_RESTRICTED_ADDRESSES_PATH, tmp, callback);
    };

    var updateRestrictedAccessList = function (addresses, callback) {
        //todo: confirm whether we need to restart service after updating access list
        async.series(
            [
                function (callback) {saveRestrictedAccessList(addresses, callback); },
                restartAPD
            ],
            function (err, out) {
                if (err) {
                    callback(err);
                    return;
                }
                callback(null, out);
            }
        );
    };

    var formatAsyncOutput = function (arr) {

        if (!arr) {
            return;
        }

        var out = [];

        var len = arr.length;

        var tmp, i;
        for (i = 0; i < len; i++) {
            tmp = arr[i];

            if (!tmp) {
                continue;
            }

            out.push(tmp.trim());
        }

        return out.join(os.EOL);
    };

    var updateAPConf = function (ssid, callback) {

        var _generateAPConf = function (data, callback) {
            var conf = hostapdconf.updateSSID(ssid, data);
            callback(null, conf);
        };

        //todo: do we need to restart restartUDHCPD (it is slow)
        async.waterfall(
            [
                hostapdconf.loadConfFile,
                _generateAPConf,
                hostapdconf.writeConfFile
            ],
            function (err, out) {
                out = formatAsyncOutput(out);

                //note: if not an error, err will be null
                callback(err, out);
            }
        );
    };

    var updateAccessPoint = function (ssid, address, callback) {

        if (!utils.isValidMacAddress(address)) {
            callback("Invalid mac address");
            return;
        }

        if (!ssid || !ssid.length) {
            callback("Invalid SSID.");
            return;
        }

        //note, the arguments are not passed on the shell, so we don't have to worry
        //about injection (although the script being called does)
        //http://stackoverflow.com/questions/15168071/how-secure-is-using-execfile-for-bash-scripts
        async.series(
            [
                function (callback) {process_runner.exec("ifconfig", [config.ACCESS_POINT_INTERFACE, "down"], callback); },
                function (callback) {process_runner.exec("ifconfig", [config.ACCESS_POINT_INTERFACE, "hw", "ether", address], callback); },
                function (callback) {process_runner.exec("ifconfig", [config.ACCESS_POINT_INTERFACE, "up"], callback); },
                function (callback) {updateAPConf(ssid, callback); },
                restartAPD//,

            ],
            function (err, out) {
                out = formatAsyncOutput(out);

                //note: if not an error, err will be null
                callback(err, out);
            }
        );
    };

    exports.getCPUTemp = getCPUTemp;
    exports.updateAccessPoint = updateAccessPoint;
}());