text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Generic Values</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.72.0">
<link rel="start" href="index.html" title="GObject Reference Manual">
<link rel="up" href="rn01.html" title="API Reference">
<link rel="prev" href="gobject-Boxed-Types.html" title="GBoxed">
<link rel="next" href="gobject-Standard-Parameter-and-Value-Types.html" title="Parameters and Values">
<meta name="generator" content="GTK-Doc V1.7 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="preface" href="pr01.html" title="Introduction">
<link rel="part" href="pt01.html" title="Part I. Concepts">
<link rel="chapter" href="ch01.html" title="Background">
<link rel="chapter" href="ch02.html" title="The Glib Dynamic Type System">
<link rel="chapter" href="chapter-gobject.html" title="The GObject base class">
<link rel="chapter" href="chapter-signal.html" title="The GObject messaging system">
<link rel="reference" href="rn01.html" title="API Reference">
<link rel="reference" href="rn02.html" title="Tools Reference">
<link rel="part" href="pt02.html" title="Part IV. Tutorial">
<link rel="chapter" href="howto-gobject.html" title="How To define and implement a new GObject?">
<link rel="chapter" href="howto-interface.html" title="How To define and implement Interfaces?">
<link rel="chapter" href="howto-signals.html" title="Howto create and use signals">
<link rel="part" href="pt03.html" title="Part V. Related Tools">
<link rel="chapter" href="tools-gob.html" title="GObject builder">
<link rel="chapter" href="tools-ginspector.html" title="Graphical inspection of Gobjects">
<link rel="chapter" href="tools-refdb.html" title="Debugging reference count problems">
<link rel="chapter" href="tools-gtkdoc.html" title="Writing API docs">
<link rel="index" href="ix01.html" title="Index">
<link rel="index" href="ix02.html" title="Index of deprecated symbols">
<link rel="index" href="ix03.html" title="Index of new symbols in 2.2">
<link rel="index" href="ix04.html" title="Index of new symbols in 2.4">
<link rel="index" href="ix05.html" title="Index of new symbols in 2.6">
<link rel="index" href="ix06.html" title="Index of new symbols in 2.8">
<link rel="index" href="ix07.html" title="Index of new symbols in 2.10">
<link rel="index" href="ix08.html" title="Index of new symbols in 2.12">

GObject Reference Manual

<nobr>Top
                   |
                  Description</nobr>

Generic Values

Generic Values — A polymorphic type that can hold values of any other type

Synopsis

#include <glib-object.h>

#define             G_VALUE_HOLDS                       (value,type)
#define             G_VALUE_TYPE                        (value)
#define             G_VALUE_TYPE_NAME                   (value)
#define             G_TYPE_IS_VALUE                     (type)
#define             G_TYPE_IS_VALUE_ABSTRACT            (type)
#define             G_IS_VALUE                          (value)
                    GValue;
#define             G_TYPE_VALUE
#define             G_TYPE_VALUE_ARRAY
GValue*             g_value_init                        (GValue *value,
                                                         GType g_type);
void                g_value_copy                        (const GValue *src_value,
                                                         GValue *dest_value);
GValue*             g_value_reset                       (GValue *value);
void                g_value_unset                       (GValue *value);
void                g_value_set_instance                (GValue *value,
                                                         gpointer instance);
gboolean            g_value_fits_pointer                (const GValue *value);
gpointer            g_value_peek_pointer                (const GValue *value);
gboolean            g_value_type_compatible             (GType src_type,
                                                         GType dest_type);
gboolean            g_value_type_transformable          (GType src_type,
                                                         GType dest_type);
gboolean            g_value_transform                   (const GValue *src_value,
                                                         GValue *dest_value);
void                (*GValueTransform)                  (const GValue *src_value,
                                                         GValue *dest_value);
void                g_value_register_transform_func     (GType src_type,
                                                         GType dest_type,
                                                         GValueTransform transform_func);
gchar*              g_strdup_value_contents             (const GValue *value);

Description

The GValue structure is basically a variable container that consists
of a type identifier and a specific value of that type.
The type identifier within a GValue structure always determines the
type of the associated value.
To create a undefined GValue structure, simply create a zero-filled
GValue structure. To initialize the GValue, use the g_value_init()
function. A GValue cannot be used until it is initialized.
The basic type operations (such as freeing and copying) are determined
by the GTypeValueTable associated with the type ID stored in the GValue.
Other GValue operations (such as converting values between types) are
provided by this interface.

Details

G_VALUE_HOLDS()

#define G_VALUE_HOLDS(value,type)	(G_TYPE_CHECK_VALUE_TYPE ((value), (type)))

Returns TRUE if value holds (or contains) a value of type.
This macro will also check for value != NULL and issue a
warning if the check fails.

<col align="left" valign="top">

value :
A GValue structure.

type :
A GType value.

G_VALUE_TYPE()

#define	G_VALUE_TYPE(value)		(((GValue*) (value))->g_type)

Returns the type identifier of value.

<col align="left" valign="top">

value :
A GValue structure.

G_VALUE_TYPE_NAME()

#define	G_VALUE_TYPE_NAME(value)	(g_type_name (G_VALUE_TYPE (value)))

Returns the type name of value.

<col align="left" valign="top">

value :
A GValue structure.

G_TYPE_IS_VALUE()

#define	G_TYPE_IS_VALUE(type)		(g_type_check_is_value_type (type))

Return whether the passed in type ID can be used for g_value_init().
That is, this macro checks whether this type provides an implementation
of the GTypeValueTable functions required for a type to create a GValue of.

<col align="left" valign="top">

type :
	  A GType value.

Returns :
Whether type is suitable as a GValue type.

G_TYPE_IS_VALUE_ABSTRACT()

#define G_TYPE_IS_VALUE_ABSTRACT(type)          (g_type_test_flags ((type), G_TYPE_FLAG_VALUE_ABSTRACT))

Returns TRUE if type is an abstract value type.  An abstract value type
introduces a value table, but can't be used for g_value_init() and is normally
used as an abstract base type for derived value types.

<col align="left" valign="top">

type :
A GType value.

G_IS_VALUE()

#define	G_IS_VALUE(value)		(G_TYPE_CHECK_VALUE (value))

Returns TRUE if value is a valid and initialized GValue structure.

<col align="left" valign="top">

value :
A GValue structure.

GValue

typedef struct {
} GValue;

An opaque structure used to hold different types of values.
The data within the structure has protected scope: it is accessible only
to functions within a GTypeValueTable structure, or implementations of
the g_value_*() API. That is, code portions which implement new fundamental
types.
GValue users can not make any assumptions about how data is stored
within the 2 element data union, and the g_type member should
only be accessed through the G_VALUE_TYPE() macro.

G_TYPE_VALUE

#define	G_TYPE_VALUE		(g_value_get_type ())

Returns the type ID of the "GValue" type which is a boxed type,
used to pass around pointers to GValues.

G_TYPE_VALUE_ARRAY

#define	G_TYPE_VALUE_ARRAY	(g_value_array_get_type ())

Returns the type ID of the "GValueArray" type which is a boxed type,
used to pass around pointers to GValueArrays.

g_value_init ()

GValue*             g_value_init                        (GValue *value,
                                                         GType g_type);

Initializes value with the default value of type.

<col align="left" valign="top">

value :
A zero-filled (uninitialized) GValue structure.

g_type :
Type the GValue should hold values of.

Returns :
the GValue structure that has been passed in

g_value_copy ()

void                g_value_copy                        (const GValue *src_value,
                                                         GValue *dest_value);

Copies the value of src_value into dest_value.

<col align="left" valign="top">

src_value :
An initialized GValue structure.

dest_value :
An initialized GValue structure of the same type as src_value.

g_value_reset ()

GValue*             g_value_reset                       (GValue *value);

Clears the current value in value and resets it to the default value
(as if the value had just been initialized).

<col align="left" valign="top">

value :
An initialized GValue structure.

Returns :
the GValue structure that has been passed in

g_value_unset ()

void                g_value_unset                       (GValue *value);

Clears the current value in value and "unsets" the type,
this releases all resources associated with this GValue.
An unset value is the same as an uninitialized (zero-filled)
GValue structure.

<col align="left" valign="top">

value :
	An initialized GValue structure.

g_value_set_instance ()

void                g_value_set_instance                (GValue *value,
                                                         gpointer instance);

Sets value from an instantiatable type via the
value_table's collect_value() function.

<col align="left" valign="top">

value :
An initialized GValue structure.

instance :
the instance

g_value_fits_pointer ()

gboolean            g_value_fits_pointer                (const GValue *value);

Determines if value will fit inside the size of a pointer value.
This is an internal function introduced mainly for C marshallers.

<col align="left" valign="top">

value :
An initialized GValue structure.

Returns :

TRUE if value will fit inside a pointer value.

g_value_peek_pointer ()

gpointer            g_value_peek_pointer                (const GValue *value);

Return the value contents as pointer. This function asserts that
g_value_fits_pointer() returned TRUE for the passed in value.
This is an internal function introduced mainly for C marshallers.

<col align="left" valign="top">

value :
An initialized GValue structure.

Returns :

TRUE if value will fit inside a pointer value.

g_value_type_compatible ()

gboolean            g_value_type_compatible             (GType src_type,
                                                         GType dest_type);

Returns whether a GValue of type src_type can be copied into
a GValue of type dest_type.

<col align="left" valign="top">

src_type :
source type to be copied.

dest_type :
destination type for copying.

Returns :

TRUE if g_value_copy() is possible with src_type and dest_type.

g_value_type_transformable ()

gboolean            g_value_type_transformable          (GType src_type,
                                                         GType dest_type);

Check whether g_value_transform() is able to transform values
of type src_type into values of type dest_type.

<col align="left" valign="top">

src_type :
Source type.

dest_type :
Target type.

Returns :

TRUE if the transformation is possible, FALSE otherwise.

g_value_transform ()

gboolean            g_value_transform                   (const GValue *src_value,
                                                         GValue *dest_value);

Tries to cast the contents of src_value into a type appropriate
to store in dest_value, e.g. to transform a G_TYPE_INT value
into a G_TYPE_FLOAT value. Performing transformations between
value types might incur precision lossage. Especially
transformations into strings might reveal seemingly arbitrary
results and shouldn't be relied upon for production code (such
as rcfile value or object property serialization).

<col align="left" valign="top">

src_value :
Source value.

dest_value :
Target value.

Returns :
Whether a transformation rule was found and could be applied.
          Upon failing transformations, dest_value is left untouched.

GValueTransform ()

void                (*GValueTransform)                  (const GValue *src_value,
                                                         GValue *dest_value);

The type of value transformation functions which can be registered with
g_value_register_transform_func().

<col align="left" valign="top">

src_value :
 Source value.

dest_value :
Target value.

g_value_register_transform_func ()

void                g_value_register_transform_func     (GType src_type,
                                                         GType dest_type,
                                                         GValueTransform transform_func);

Registers a value transformation function for use in g_value_transform().
A previously registered transformation function for src_type and dest_type
will be replaced.

<col align="left" valign="top">

src_type :
 Source type.

dest_type :
Target type.

transform_func :
a function which transforms values of type src_type
  into value of type dest_type

g_strdup_value_contents ()

gchar*              g_strdup_value_contents             (const GValue *value);

Return a newly allocated string, which describes the contents of a GValue.
The main purpose of this function is to describe GValue contents for
debugging output, the way in which the contents are described may change
between different GLib versions.

<col align="left" valign="top">

value :
  GValue which contents are to be described.

Returns :
Newly allocated string.

See Also

The fundamental types which all support GValue operations and thus
can be used as a type initializer for g_value_init() are defined by
a separate interface.  See the Standard Values
API for details.


text:
package com.gs.fw.common.freyaxml.generator;

import java.io.*;

public class GenerationLog
{

    private String md5;
    private String xmlCrc;

    public GenerationLog(String md5, String xmlCrc)
    {
        this.md5 = md5;
        this.xmlCrc = xmlCrc;
    }

    public String getMd5()
    {
        return md5;
    }

    public String getXmlCrc()
    {
        return xmlCrc;
    }

    public void writeLog(String generatedDir, String classListName) throws IOException
    {
        String logNameFromClassListName = getLogNameFromClassListName(generatedDir, classListName);
        File file = new File(logNameFromClassListName);
        FileWriter writer = new FileWriter(file);
        writer.write(this.md5+"\n");
        writer.write(this.xmlCrc+"\n");
        writer.close();
    }

    public void deleteLog(String generatedDir, String classListName) throws IOException
    {
        String logNameFromClassListName = getLogNameFromClassListName(generatedDir, classListName);
        File file = new File(logNameFromClassListName);
        file.delete();
    }

    private static String getLogNameFromClassListName(String generatedDir, String classListName)
    {
        String cleanedGeneratedDir = getCleanedDir(generatedDir);

        String cleanedClassListName = getCleanedDir(classListName);

        int maxSearchLength = cleanedGeneratedDir.length();
        if (cleanedClassListName.length() < maxSearchLength) maxSearchLength = cleanedClassListName.length();

        int matchedCharIndex = 0;
        for(int i=0;i<maxSearchLength;i++)
        {
            if (Character.toUpperCase(cleanedClassListName.charAt(i)) == Character.toUpperCase(cleanedGeneratedDir.charAt(i)))
            {
                matchedCharIndex++;
            }
            else
            {
                break;
            }
        }

        return generatedDir+File.separator+cleanedClassListName.substring(matchedCharIndex, cleanedClassListName.length())+".log";
    }

    private static String getCleanedDir(String generatedDir)
    {
        String cleanedGeneratedDir = StringUtility.replaceStr(generatedDir, "/", ".");
        cleanedGeneratedDir = StringUtility.replaceStr(cleanedGeneratedDir, "\\", ".");
        cleanedGeneratedDir = StringUtility.replaceStr(cleanedGeneratedDir, File.separator, ".");
        cleanedGeneratedDir = StringUtility.replaceStr(cleanedGeneratedDir, ":", ".");
        return cleanedGeneratedDir;
    }

    public static GenerationLog readOldLog(String generatedDir, String fileNameForClassList) throws IOException
    {
        GenerationLog result = new GenerationLog("xxx", "00");
        File file = new File(getLogNameFromClassListName(generatedDir, fileNameForClassList));
        if (file.exists())
        {
            FileInputStream fis = new FileInputStream(file);
            LineNumberReader reader = new LineNumberReader(new InputStreamReader(fis));
            String md5 = reader.readLine();
            String xmlCrc = reader.readLine();
            if (md5 != null && xmlCrc != null)
            {
                result = new GenerationLog(md5, xmlCrc);
            }
            fis.close();
        }
        return result;
    }

    public boolean isSame(GenerationLog oldLog)
    {
        return this.getMd5().equals(oldLog.getMd5()) && this.getXmlCrc().equals(oldLog.getXmlCrc());
    }
}

redpajama_set_name: RedPajamaGithub


text:
title: Brute Force Algorithms
localeTitle: Algoritmos de fuerza bruta
---
## Algoritmos de fuerza bruta

Los algoritmos de fuerza bruta se refieren a un estilo de programación que no incluye ningún método abreviado para mejorar el rendimiento, sino que se basa en la capacidad de cálculo total para probar todas las posibilidades hasta que se encuentre la solución a un problema.

Un ejemplo clásico es el problema del vendedor ambulante (TSP). Supongamos que un vendedor necesita visitar 10 ciudades de todo el país. ¿Cómo se determina el orden en el que se deben visitar las ciudades para minimizar la distancia recorrida total? La solución de fuerza bruta es simplemente calcular la distancia total para cada ruta posible y luego seleccionar la más corta. Esto no es particularmente eficiente porque es posible eliminar muchas rutas posibles a través de algoritmos inteligentes.

Otro ejemplo: contraseña de 5 dígitos, en el peor de los casos tomaría 10 5 intentos para descifrar.

La complejidad temporal de la fuerza bruta es **O (n \* m)** . Entonces, si tuviéramos que buscar una cadena de caracteres 'n' en una cadena de caracteres 'm' usando fuerza bruta, nos tomaría n \* m intentos.

#### Más información:

[Wikipedia](https://en.wikipedia.org/wiki/Brute-force_search)


text:
Java library to parse the request body of a Chargify Webhook.

## Quick Start

To use this `chargify-webhook-java` project. Clone and build this repository, or use Maven.

### Releases

Stable releases will be published to the central maven repository.

	<dependency>
		<groupId>io.prowave</groupId>
		<artifactId>chargify-webhook-java</artifactId>
		<version>1.1.6</version>
	</dependency>

### Snapshots

Snapshots are not automatically published.

## Usage

### Spring-MVC

The easiest way to parse the webhook request body is my allowing SpringMVC to convert the parameters to a `Map<String, String>` for you, and then pass that Map to the `ChargifyWebhookParser`.

	@Controller
	@RequestMapping("/chargify")
	public class ChargifyController {

		@RequestMapping(value = "/receiver", method = RequestMethod.POST)
		@ResponseBody
		public void receiver(@RequestParam Map<String, String> requestBody) throws IOException {

			ChargifyWebhook chargifyWebhook = ChargifyWebhookParser.parse(requestBody);

			if ("signup_success".equals(chargifyWebhook.getEvent())) {

				SignupSuccess ss = ChargifyMessageFactory.createChargifyMessage(chargifyWebhook.getPayload(),
						SignupSuccess.class);

			}

			if ("test".equals(chargifyWebhook.getEvent())) {

				Test test = ChargifyMessageFactory.createChargifyMessage(chargifyWebhook.getPayload(), Test.class);

			}

		}
	}

Once you have the `ChargifyWebhook` from the `ChargifyWebhookParser.parse()` method, you have 3 options to access the parsed data.

1. You can access the `Map<String, Object>` directly from the `ChargifyWebhook.getPayload()` method.  This is a bit cumbersome as you need to cast you `Object`s to `String` or `Map<>` depending on what node you are on, and this requires knowledge of the message you received.

2. You can convert the Map to JSON using Jackson2 (which is a required dependency of this project.

This is as simple as:

	String jsonMessage = mapper.writeValueAsString(chargifyWebhook);

or you can just convert the payload

	String jsonMessage = mapper.writeValueAsString(chargifyWebhook.getPayload());

3. There is a `ChargifyMessageFactory` that will convert the `ChargifyWebhook` to POJOs.  This is the preferred method as it strongly types the attributes of the message, and provides convenient getters and setters for all known and published attributes that come in from the Chargify webhook.

### Raw Request Body

Same as above, but you can pass the raw RequestBody as a `String` to the `ChargifyWebhookParser.parse()` method.

## Whats included

### Message Parser

* The requestBody parser
* The ability to create JSON for any webhook message type

### POJO Support

#### Ignored Attributes

Since we had trouble getting a comprehensive list of all the payload attributes, we have added support for the ones we know about and ignored any others.  If there are any attributes that need to be added to the POJOs, please add them and create a PR, or open an Issue.

#### Provided

* `Test`
* `SignupSuccess`
* `CustomerUpdate`
* `PaymentSuccess`
* `PaymentFailure`
* `SubscriptionStateChange`
* `SignupFailure`
* `RenewalSuccess`
* `RenewalFailure`
* `BillingDateChange`
* `SubscriptionProductChange`
* `ExpiringCard`
* `ComponentAllocationChange`
* `UpcomingRenewalNotice`
* `EndOfTrialNotice` - possible duplicate, or superceded by `TrialEndNotice`
* `TrialEndNotice`
* `UpgradeDowngradeSuccess`
* `UpgradeDowngradeFailure`
* `ExpirationDateChange`

#### Backlog

* `SubscriptionCardUpdate`
* `MeteredUsage`
* `StatementClosed`
* `StatementSettled`
* `RefundSuccess`
* `RefundFailure`

## Other Considerations

> **NOTE**<br>
> The current implementation only supports a subset of the total webhook message types.
> The `ChargifyMessageFactory` can and should be built out by other contributors as needed, and then issue a PR to merge back into this repo.
> Eventually, all message types will be supported and the Java community can easily consume Chargify Webhooks.


text:
package acceptance.events.task;

import static org.assertj.core.api.Assertions.assertThat;

import acceptance.AbstractAccTest;
import java.time.Instant;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import pro.taskana.common.api.TimeInterval;
import pro.taskana.common.test.security.JaasExtension;
import pro.taskana.common.test.security.WithAccessId;
import pro.taskana.simplehistory.impl.SimpleHistoryServiceImpl;
import pro.taskana.spi.history.api.events.task.TaskHistoryEvent;
import pro.taskana.spi.history.api.events.task.TaskHistoryEventType;
import pro.taskana.task.api.TaskService;
import pro.taskana.task.api.models.Task;

@ExtendWith(JaasExtension.class)
class CreateHistoryEventOnTaskUpdateAccTest extends AbstractAccTest {

  private final TaskService taskService = taskanaEngine.getTaskService();
  private final SimpleHistoryServiceImpl historyService = getHistoryService();

  @Test
  @WithAccessId(user = "admin")
  void should_CreateUpdatedHistoryEvent_When_TaskIsCreated() throws Exception {
    final String taskId = "TKI:000000000000000000000000000000000000";
    Instant before = Instant.now();

    Task task = taskService.getTask(taskId);
    task.setName("someUpdatedName");
    taskService.updateTask(task);
    List<TaskHistoryEvent> events =
        historyService
            .createTaskHistoryQuery()
            .taskIdIn(taskId)
            .createdWithin(new TimeInterval(before, null))
            .list();

    assertThat(events)
        .extracting(TaskHistoryEvent::getEventType)
        .containsExactly(TaskHistoryEventType.UPDATED.getName());
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.plasebugaway"
          android:versionCode="1"
          android:versionName="1.0">
    <uses-sdk android:minSdkVersion="22"/>

    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission."/>

    <application android:label="@string/app_name" android:icon="@drawable/ic_launcher"
        android:allowBackup="true">
        <activity android:name="MyActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <receiver android:name=".PhoneStateReceiver">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE"/>
            </intent-filter>
        </receiver>
    </application>
</manifest>


text:
namespace urde {

CPASAnimState::CPASAnimState(CInputStream& in) {
  x0_id = in.readUint32Big();
  u32 parmCount = in.readUint32Big();
  u32 animCount = in.readUint32Big();

  x4_parms.reserve(parmCount);
  x14_anims.reserve(animCount);
  x24_selectionCache.reserve(animCount);

  for (u32 i = 0; i < parmCount; ++i)
    x4_parms.emplace_back(in);

  for (u32 i = 0; i < animCount; ++i) {
    s32 id = in.readUint32Big();
    rstl::reserved_vector<CPASAnimParm::UParmValue, 8> parms;
    for (const CPASParmInfo& parm : x4_parms) {
      CPASAnimParm::UParmValue val = {};
      switch (parm.GetParameterType()) {
      case CPASAnimParm::EParmType::Int32:
        val.m_int = in.readInt32Big();
        break;
      case CPASAnimParm::EParmType::UInt32:
        val.m_uint = in.readUint32Big();
        break;
      case CPASAnimParm::EParmType::Float:
        val.m_float = in.readFloatBig();
        break;
      case CPASAnimParm::EParmType::Bool:
        val.m_bool = in.readBool();
        break;
      case CPASAnimParm::EParmType::Enum:
        val.m_int = in.readInt32Big();
        break;
      default:
        break;
      }
      parms.push_back(val);
    }

    auto search =
        std::lower_bound(x14_anims.begin(), x14_anims.end(), id,
                         [](const CPASAnimInfo& item, const u32& testId) -> bool { return item.GetAnimId() < testId; });
    x14_anims.emplace(search, id, std::move(parms));
  }
}

CPASAnimState::CPASAnimState(int stateId) : x0_id(stateId) {}

CPASAnimParm CPASAnimState::GetAnimParmData(s32 animId, u32 parmIdx) const {
  auto search = rstl::binary_find(x14_anims.begin(), x14_anims.end(), animId,
                                  [](const CPASAnimInfo& item) { return item.GetAnimId(); });
  if (search == x14_anims.end())
    return CPASAnimParm::NoParameter();

  CPASParmInfo parm = x4_parms.at(parmIdx);
  return (*search).GetAnimParmData(parmIdx, parm.GetParameterType());
}

s32 CPASAnimState::PickRandomAnimation(CRandom16& rand) const {
  if (x24_selectionCache.size() == 1)
    return x24_selectionCache[0];

  if (x24_selectionCache.size() > 1) {
    u32 idx = u32(floor(rand.Float()));
    if (idx == x24_selectionCache.size())
      idx--;

    return x24_selectionCache[idx];
  }

  return -1;
}

std::pair<float, s32> CPASAnimState::FindBestAnimation(const rstl::reserved_vector<CPASAnimParm, 8>& parms,
                                                       CRandom16& rand, s32 ignoreAnim) const {
  const_cast<std::vector<s32>*>(&x24_selectionCache)->clear();
  float weight = -1.f;

  for (const CPASAnimInfo& info : x14_anims) {
    if (info.GetAnimId() == ignoreAnim)
      continue;

    float calcWeight = 1.f;
    if (x4_parms.size() > 0)
      calcWeight = 0.f;

    u32 unweightedCount = 0;

    for (u32 i = 0; i < x4_parms.size(); ++i) {
      CPASAnimParm::UParmValue val = info.GetAnimParmValue(i);
      const CPASParmInfo& parmInfo = x4_parms[i];
      float parmWeight = parmInfo.GetParameterWeight();

      float computedWeight = 0.f;
      switch (parmInfo.GetWeightFunction()) {
      case CPASParmInfo::EWeightFunction::AngularPercent:
        computedWeight = ComputeAngularPercentErrorWeight(i, parms[i], val);
        break;
      case CPASParmInfo::EWeightFunction::ExactMatch:
        computedWeight = ComputeExactMatchWeight(i, parms[i], val);
        break;
      case CPASParmInfo::EWeightFunction::PercentError:
        computedWeight = ComputePercentErrorWeight(i, parms[i], val);
        break;
      case CPASParmInfo::EWeightFunction::NoWeight:
        unweightedCount++;
        break;
      default:
        break;
      }

      calcWeight += parmWeight * computedWeight;
    }

    if (unweightedCount == x4_parms.size())
      calcWeight = 1.0f;

    if (calcWeight > weight) {
      const_cast<std::vector<s32>*>(&x24_selectionCache)->clear();
      const_cast<std::vector<s32>*>(&x24_selectionCache)->push_back(info.GetAnimId());
      weight = calcWeight;
    } else if (weight == calcWeight) {
      const_cast<std::vector<s32>*>(&x24_selectionCache)->push_back(info.GetAnimId());
      weight = calcWeight;
    }
  }

  return {weight, PickRandomAnimation(rand)};
}

float CPASAnimState::ComputeExactMatchWeight(u32, const CPASAnimParm& parm, CPASAnimParm::UParmValue parmVal) const {
  switch (parm.GetParameterType()) {
  case CPASAnimParm::EParmType::Int32:
    return (parm.GetInt32Value() == parmVal.m_int ? 1.f : 0.f);
  case CPASAnimParm::EParmType::UInt32:
    return (parm.GetUint32Value() == parmVal.m_uint ? 1.f : 0.f);
  case CPASAnimParm::EParmType::Float:
    return ((parmVal.m_float - parm.GetReal32Value()) < FLT_EPSILON ? 1.f : 0.f);
  case CPASAnimParm::EParmType::Bool:
    return (parm.GetBoolValue() == parmVal.m_bool ? 1.f : 0.f);
  case CPASAnimParm::EParmType::Enum:
    return (parm.GetEnumValue() == parmVal.m_int ? 1.f : 0.f);
  default:
    break;
  }

  return 0.f;
}

float CPASAnimState::ComputePercentErrorWeight(u32 idx, const CPASAnimParm& parm,
                                               CPASAnimParm::UParmValue parmVal) const {
  float range = 0.f;
  float val = 0.f;

  switch (parm.GetParameterType()) {
  case CPASAnimParm::EParmType::Int32: {
    const CPASParmInfo& info = x4_parms[idx];
    range = info.GetWeightMaxValue().m_int - info.GetWeightMinValue().m_int;
    val = std::fabs(parm.GetInt32Value() - parmVal.m_int);
    break;
  }
  case CPASAnimParm::EParmType::UInt32: {
    const CPASParmInfo& info = x4_parms[idx];
    range = info.GetWeightMaxValue().m_uint - info.GetWeightMinValue().m_uint;
    val = std::fabs(int(parmVal.m_uint) - int(parm.GetUint32Value()));
    break;
  }
  case CPASAnimParm::EParmType::Float: {
    const CPASParmInfo& info = x4_parms[idx];
    range = info.GetWeightMaxValue().m_float - info.GetWeightMinValue().m_float;
    val = std::fabs(parm.GetReal32Value() - parmVal.m_float);
    break;
  }
  case CPASAnimParm::EParmType::Bool: {
    val = parm.GetBoolValue() == parmVal.m_bool ? 0.f : 1.f;
    break;
  }
  case CPASAnimParm::EParmType::Enum: {
    const CPASParmInfo& info = x4_parms[idx];
    range = info.GetWeightMaxValue().m_int - info.GetWeightMinValue().m_int;
    val = std::fabs(parm.GetEnumValue() - parmVal.m_int);
    break;
  }
  default:
    break;
  }

  if (range > FLT_EPSILON)
    return 1.f - val / range;

  return (val < FLT_EPSILON ? 1.f : 0.f);
}

float CPASAnimState::ComputeAngularPercentErrorWeight(u32 idx, const CPASAnimParm& parm,
                                                      CPASAnimParm::UParmValue parmVal) const {
  float range = 0.f;
  float val = 0.f;

  switch (parm.GetParameterType()) {
  case CPASAnimParm::EParmType::Int32: {
    const CPASParmInfo& info = x4_parms[idx];
    range = info.GetWeightMaxValue().m_int - info.GetWeightMinValue().m_int;
    val = std::fabs(parmVal.m_int - parm.GetInt32Value());
    break;
  }
  case CPASAnimParm::EParmType::UInt32: {
    const CPASParmInfo& info = x4_parms[idx];
    range = info.GetWeightMaxValue().m_uint - info.GetWeightMinValue().m_uint;
    val = std::fabs(int(parmVal.m_uint) - int(parm.GetUint32Value()));
    break;
  }
  case CPASAnimParm::EParmType::Float: {
    const CPASParmInfo& info = x4_parms[idx];
    range = info.GetWeightMaxValue().m_float - info.GetWeightMinValue().m_float;
    val = std::fabs(parm.GetReal32Value() - parmVal.m_float);
    break;
  }
  case CPASAnimParm::EParmType::Bool: {
    val = parm.GetBoolValue() == parmVal.m_bool ? 0.f : 1.f;
    break;
  }
  case CPASAnimParm::EParmType::Enum: {
    const CPASParmInfo& info = x4_parms[idx];
    range = info.GetWeightMaxValue().m_int - info.GetWeightMinValue().m_int + 1;
    val = std::fabs(parm.GetEnumValue() - parmVal.m_int);
    break;
  }
  default:
    break;
  }

  if (range > FLT_EPSILON) {
    float mid = 0.5f * range;
    float offset = 1.f - ((val > mid ? range - val : val) / mid);
    return zeus::clamp(0.f, offset, 1.f);
  }

  return (val >= FLT_EPSILON ? 0.f : 1.f);
}
} // namespace urde


text:
package gov.nasa.jpf.util.test;

import gov.nasa.jpf.Config;
import gov.nasa.jpf.Error;
import gov.nasa.jpf.JPF;
import gov.nasa.jpf.JPFShell;
import gov.nasa.jpf.Property;
import gov.nasa.jpf.annotation.FilterField;
import gov.nasa.jpf.tool.RunTest;
import gov.nasa.jpf.util.DevNullPrintStream;
import gov.nasa.jpf.util.TypeRef;
import gov.nasa.jpf.util.JPFSiteUtils;
import gov.nasa.jpf.util.Reflection;
import gov.nasa.jpf.vm.ExceptionInfo;
import gov.nasa.jpf.vm.NoUncaughtExceptionsProperty;
import gov.nasa.jpf.vm.NotDeadlockedProperty;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * base class for JPF unit tests. TestJPF mostly includes JPF invocations
 * that check for occurrence or absence of certain execution results
 *
 * This class can be used in two modes:
 *
 * <ol>
 * <li> wrapping a number of related tests for different SuTs into one class
 * (suite) that calls the various JPF runners with complete argument lists
 * (as in JPF.main(String[]args)) </li>
 *
 * <li> derive a class from TestJPF that uses the "..This" methods, which in
 * turn use reflection to automatically append the test class and method to the
 * JPF.main argument list (based on the calling class / method names). Note that
 * you have to obey naming conventions for this to work:
 *
 * <li> the SuT class has to be the same as the test class without "Test", e.g.
 * "CastTest" -> "Cast" </li>
 *
 * <li> the SuT method has to have the same name as the @Test method that
 * invokes JPF, e.g. "CastTest {.. @Test void testArrayCast() ..}" ->
 * "Cast {.. void testArrayCast()..} </li>
 * </ol>
 */
public abstract class TestJPF implements JPFShell  {
  static PrintStream out = System.out;

  public static final String UNNAMED_PACKAGE = "";
  public static final String SAME_PACKAGE = null;

  //--- those are only used outside of JPF execution
  @FilterField protected static boolean globalRunDirectly, globalShowConfig;

  @FilterField protected static boolean runDirectly; // don't run test methods through JPF, invoke it directly
  @FilterField protected static boolean stopOnFailure; // stop as soon as we encounter a failed test or error
  @FilterField protected static boolean showConfig; // for debugging purposes
  @FilterField protected static boolean showConfigSources; // for debugging purposes
  @FilterField protected static boolean hideSummary;

  @FilterField protected static boolean quiet; // don't show test output

  @FilterField protected String sutClassName;

  static class GlobalArg {
    String key;
    String val;

    GlobalArg (String k, String v){
      key = k;
      val = v;
    }
  }

  // it seems wrong to pull globalArgs here instead of setting it from
  // RunTest, but RunTest has to make sure TestJPF is loaded through the
  // JPFClassLoader, i.e. cannot directly reference this class.

  @FilterField static ArrayList<GlobalArg> globalArgs;

  protected static ArrayList<GlobalArg> getGlobalArgs() {
    // NOTE - this is only set if we execute tests from build.xml
    Config globalConf = RunTest.getConfig();
    if (globalConf != null){
      ArrayList<GlobalArg> list = new ArrayList<GlobalArg>();

      //--- the "test.<key>" specs
      String[] testKeys = globalConf.getKeysStartingWith("test.");
      if (testKeys.length > 0){
        for (String key : testKeys){
          String val = globalConf.getString(key);
          // <2do> this is a hack to avoid the problem of not being able to store
          // empty/nil/null values in the global config (they are removed during global config init)
          if (val.equals("REMOVE")){
            val = null;
          }

          key = key.substring(5);

          list.add(new GlobalArg(key,val));
        }
      }

      return list;
    }

    return null;
  }

  static {
    if (!isJPFRun()){
      globalArgs = getGlobalArgs();
    }
  }

  //--- internal methods

  public static void fail (String msg, String[] args, String cause){
    StringBuilder sb = new StringBuilder();

    sb.append(msg);
    if (args != null){
      for (String s : args){
        sb.append(s);
        sb.append(' ');
      }
    }

    if (cause != null){
      sb.append(':');
      sb.append(cause);
    }

    fail(sb.toString());
  }

  public static void fail (){
    throw new AssertionError();
  }

  public static void fail (String msg){
    throw new AssertionError(msg);
  }

  public void report (String[] args) {
    if (!quiet){
      out.print("  running jpf with args:");

      for (int i = 0; i < args.length; i++) {
        out.print(' ');
        out.print(args[i]);
      }

      out.println();
    }
  }

  /**
   * compute the SuT class name for a given JUnit test class: remove
   * optionally ending "..Test", and replace package (if specified)
   *
   * @param testClassName the JUnit test class
   * @param sutPackage optional SuT package name (without ending '.', null
   * os SAME_PACKAGE means same package, "" or UNNAMED_PACKAGE means unnamed package)
   * @return main class name of system under test
   */
  protected static String getSutClassName (String testClassName, String sutPackage){

    String sutClassName = testClassName;

    int i = sutClassName.lastIndexOf('.');
    if (i >= 0){  // testclass has a package

      if (sutPackage == null){   // use same package
        // nothing to do
      } else if (sutPackage.length() > 0) { // explicit sut package
        sutClassName = sutPackage + sutClassName.substring(i);

      } else { // unnamed sut package
        sutClassName = sutClassName.substring(i+1);
      }

    } else { // test class has no package
      if (sutPackage == null || sutPackage.length() == 0){   // use same package
        // nothing to do
      } else { // explicit sut package
        sutClassName = sutPackage + '.' + sutClassName;
      }
    }

    if (sutClassName.endsWith("JPF")) {
      sutClassName = sutClassName.substring(0, sutClassName.length() - 3);
    }

    return sutClassName;
  }

  // we can't set the sutClassName only from main() called methods (like
  // runTestsOfThisClass()) since main() doesn't get called if this is executed
  // by Ant (via <junit> task)
  // the default ctor is always executed
  public TestJPF () {
    sutClassName = getSutClassName(getClass().getName(), SAME_PACKAGE);
  }

  //------ the API to be used by subclasses

  /**
   * to be used from default ctor of derived class if the SuT is in a different
   * package
   * @param sutClassName the qualified SuT class name to be checked by JPF
   */
  protected TestJPF (String sutClassName){
    this.sutClassName = sutClassName;
  }

  public static boolean isJPFRun () {
    return false;
  }

  public static boolean isJUnitRun() {
    // intercepted by native peer if this runs under JPF
    Throwable t = new Throwable();
    t.fillInStackTrace();

    for (StackTraceElement se : t.getStackTrace()){
      if (se.getClassName().startsWith("org.junit.")){
        return true;
      }
    }

    return false;
  }

  public static boolean isRunTestRun() {
    // intercepted by native peer if this runs under JPF
    Throwable t = new Throwable();
    t.fillInStackTrace();

    for (StackTraceElement se : t.getStackTrace()){
      if (se.getClassName().equals("gov.nasa.jpf.tool.RunTest")){
        return true;
      }
    }

    return false;
  }

  protected static void getOptions (String[] args){
    runDirectly = globalRunDirectly;
    showConfig = globalShowConfig;

    // hideSummary and stopOnFailure only make sense as global options anyways

    if (args != null){
      for (int i=0; i<args.length; i++){
        String a = args[i];
        if (a != null){
          if (a.length() > 0){
            if (a.charAt(0) == '-'){
              a = a.substring(1);

              if (a.equals("d")){
                runDirectly = true;
              } else if (a.equals("s") || a.equals("show")){
                showConfig = true;
              } else if (a.equals("l") || a.equals("log")){
                showConfigSources = true;
              } else if (a.equals("q") || a.equals("quiet")){
                quiet = true;
              } else if (a.equals("x")){
                stopOnFailure = true;
              } else if (a.equals("h")){
                hideSummary = true;
              }
              args[i] = null;  // set it consumed

            } else {
              break; // done, this is a test method
            }
          }
        }
      }
    }
  }

  protected static boolean hasExplicitTestMethods(String[] args){
    for (String a : args){
      if (a != null){
        return true;
      }
    }

    return false;
  }

  protected static List<Method> getMatchingMethods(Class<? extends TestJPF> testCls,
          int setModifiers, int unsetModifiers, String[] annotationNames){
    List<Method> list = new ArrayList<Method>();

    for (Method m : testCls.getMethods()){
      if (isMatchingMethod(m, setModifiers, unsetModifiers, annotationNames)){
        list.add(m);
      }
    }

    return list;
  }

  protected static boolean isMatchingMethod(Method m, int setModifiers, int unsetModifiers, String[] annotationNames) {
    int mod = m.getModifiers();
    if (((mod & setModifiers) != 0) && ((mod & unsetModifiers) == 0)) {
      if (m.getParameterTypes().length == 0) {
        if (annotationNames != null){
          Annotation[] annotations = m.getAnnotations();
          for (int i = 0; i < annotations.length; i++) {
            String annotType = annotations[i].annotationType().getName();
            for (int j = 0; j < annotationNames.length; j++) {
              if (annotType.equals(annotationNames[j])) {
                return true;
              }
            }
          }
        } else {
          return true;
        }
      }
    }

    return false;
  }

  protected static List<Method> getContextMethods(Class<? extends TestJPF> testCls,
                                                  int setModifiers, int unsetModifiers, String annotation){
    String[] annotations = {annotation};

    List<Method> list = new ArrayList<Method>();
    for (Method m : testCls.getMethods()){
      if (isMatchingMethod(m, setModifiers, unsetModifiers, annotations)){
        list.add(m);
      }
    }
    return list;
  }

  protected static List<Method> getBeforeMethods(Class<? extends TestJPF> testCls){
    return getContextMethods(testCls, Modifier.PUBLIC, Modifier.STATIC, "org.junit.Before");
  }

  protected static List<Method> getAfterMethods(Class<? extends TestJPF> testCls){
    return getContextMethods(testCls, Modifier.PUBLIC, Modifier.STATIC, "org.junit.After");
  }

  protected static List<Method> getBeforeClassMethods(Class<? extends TestJPF> testCls){
    return getContextMethods(testCls, Modifier.PUBLIC | Modifier.STATIC, 0, "org.junit.BeforeClass");
  }

  protected static List<Method> getAfterClassMethods(Class<? extends TestJPF> testCls){
    return getContextMethods(testCls, Modifier.PUBLIC | Modifier.STATIC, 0, "org.junit.AfterClass");
  }

  protected static boolean haveTestMethodSpecs( String[] args){
    if (args != null && args.length > 0){
      for (int i=0; i<args.length; i++){
        if (args[i] != null){
          return true;
        }
      }
    }

    return false;
  }

  protected static List<Method> getTestMethods(Class<? extends TestJPF> testCls, String[] args){
    String[] testAnnotations = {"org.junit.Test", "org.testng.annotations.Test"};

    if (haveTestMethodSpecs( args)){ // test methods specified as arguments
      List<Method> list = new ArrayList<Method>();

      for (String test : args){
        if (test != null){

          try {
            Method m = testCls.getMethod(test);

            if (isMatchingMethod(m, Modifier.PUBLIC, Modifier.STATIC, null /*testAnnotations*/ )){
              list.add(m);
            } else {
              throw new RuntimeException("test method must be @Test annotated public instance method without arguments: " + test);
            }

          } catch (NoSuchMethodException x) {
            throw new RuntimeException("method: " + test
                    + "() not in test class: " + testCls.getName(), x);
          }
        }
      }

      return list;

    } else { // no explicit test method specification, get all matches
      return getMatchingMethods(testCls, Modifier.PUBLIC, Modifier.STATIC, testAnnotations);
    }
  }

  protected static void reportTestStart(String mthName){
    if (!quiet){
      System.out.println();
      System.out.print("......................................... testing ");
      System.out.print(mthName);
      System.out.println("()");
    }
  }

  protected static void reportTestInitialization(String mthName){
    if (!quiet){
      System.out.print(".... running test initialization: ");
      System.out.print(mthName);
      System.out.println("()");
    }
  }

  protected static void reportTestCleanup(String mthName){
    if (!quiet){
      System.out.print(".... running test cleanup: ");
      System.out.print(mthName);
      System.out.println("()");
    }
  }

  protected static void reportTestFinished(String msg){
    if (!quiet){
      System.out.print("......................................... ");
      System.out.println(msg);
    }
  }

  protected static void reportResults(String clsName, int nTests, int nFailures, int nErrors, List<String> results){
    System.out.println();
    System.out.print("......................................... execution of testsuite: " + clsName);
    if (nFailures > 0 || nErrors > 0){
      System.out.println(" FAILED");
    } else if (nTests > 0) {
      System.out.println(" SUCCEEDED");
    } else {
      System.out.println(" OBSOLETE");
    }

    if (!quiet){
      if (results != null) {
        int i = 0;
        for (String result : results) {
          System.out.print(".... [" + ++i + "] ");
          System.out.println(result);
        }
      }
    }

    System.out.print(".........................................");
    System.out.println(" tests: " + nTests + ", failures: " + nFailures + ", errors: " + nErrors);
  }

  static void invoke (Method m, Object testObject) throws IllegalAccessException, InvocationTargetException  {
    PrintStream sysOut = null;

    try {
      if (quiet){
        sysOut = System.out;
        System.setOut( new DevNullPrintStream());
      }

      m.invoke( testObject);

    } finally {
      if (quiet){
        System.setOut( sysOut);
      }
    }
  }

  /**
   * this is the main test loop if this TestJPF instance is executed directly
   * or called from RunTest. It is *not* called if this is executed from JUnit
   */
  public static void runTests (Class<? extends TestJPF> testCls, String... args){
    int nTests = 0;
    int nFailures = 0;
    int nErrors = 0;
    String testMethodName = null;
    List<String> results = null;

    getOptions(args);
    globalRunDirectly = runDirectly;
    globalShowConfig = showConfig;
    boolean globalStopOnFailure = stopOnFailure;

    try {
      List<Method> testMethods = getTestMethods(testCls, args);
      results = new ArrayList<String>(testMethods.size());

      // check if we have JUnit style housekeeping methods (initialization and
      // cleanup should use the same mechanisms as JUnit)

      List<Method> beforeClassMethods = getBeforeClassMethods(testCls);
      List<Method> afterClassMethods = getAfterClassMethods(testCls);

      List<Method> beforeMethods = getBeforeMethods(testCls);
      List<Method> afterMethods = getAfterMethods(testCls);

      for (Method initMethod : beforeClassMethods) {
        reportTestInitialization(initMethod.getName());
        initMethod.invoke(null);
      }

      for (Method testMethod : testMethods) {
        testMethodName = testMethod.getName();
        String result = testMethodName;
        try {
          Object testObject = testCls.newInstance();

          nTests++;
          reportTestStart( testMethodName);

          // run per test initialization methods
          for (Method initMethod : beforeMethods){
            reportTestInitialization( initMethod.getName());
            invoke( initMethod, testObject);
          }

          // now run the test method itself
          invoke( testMethod, testObject);
          result += ": Ok";

          // run per test initialization methods
          for (Method cleanupMethod : afterMethods){
            reportTestCleanup( cleanupMethod.getName());
            invoke( cleanupMethod, testObject);
          }

        } catch (InvocationTargetException x) {
          Throwable cause = x.getCause();
          cause.printStackTrace();
          if (cause instanceof AssertionError) {
            nFailures++;
            reportTestFinished("test method failed with: " + cause.getMessage());
            result += ": Failed";
          } else {
            nErrors++;
            reportTestFinished("unexpected error while executing test method: " + cause.getMessage());
            result += ": Error";
          }

          if (globalStopOnFailure){
            break;
          }
        }

        results.add(result);
        reportTestFinished(result);
      }

      for (Method cleanupMethod : afterClassMethods) {
        reportTestCleanup( cleanupMethod.getName());
        cleanupMethod.invoke(null);
      }

    //--- those exceptions are unexpected and represent unrecoverable test harness errors
    } catch (InvocationTargetException x) {
      Throwable cause = x.getCause();
      cause.printStackTrace();
      nErrors++;
      reportTestFinished("TEST ERROR: @BeforeClass,@AfterClass method failed: " + x.getMessage());

    } catch (InstantiationException x) {
      nErrors++;
      reportTestFinished("TEST ERROR: cannot instantiate test class: " + x.getMessage());
    } catch (IllegalAccessException x) { // can't happen if getTestMethods() worked
      nErrors++;
      reportTestFinished("TEST ERROR: default constructor or test method not public: " + testMethodName);
    } catch (IllegalArgumentException x) {  // can't happen if getTestMethods() worked
      nErrors++;
      reportTestFinished("TEST ERROR: illegal argument for test method: " + testMethodName);
    } catch (RuntimeException rx) {
      nErrors++;
      reportTestFinished("TEST ERROR: " + rx.toString());
    }

    if (!hideSummary){
      reportResults(testCls.getName(), nTests, nFailures, nErrors, results);
    }

    if (nErrors > 0 || nFailures > 0){
      if (isRunTestRun()){
        // we need to reportTestFinished this test has failed
        throw new RunTest.Failed();
      }
    }
  }

  static String getProperty(String key){
    // intercepted by peer
    return null;
  }

  /**
   * this is the JPF entry method in case there is no main() in the test class
   *
   * <2do> we should support test method arguments here
   */
  static void runTestMethod(String args[]) throws Throwable {
    String testClsName = getProperty("target");
    String testMthName = getProperty("target.test_method");

    Class<?> testCls = Class.forName(testClsName);
    Object target = testCls.newInstance();

    Method method = testCls.getMethod(testMthName);

    try {
      method.invoke(target);
    } catch (InvocationTargetException e) {
      throw e.getCause();
    }
  }

  /**
   * NOTE: this needs to be called from the concrete test class, typically from
   * its main() method, otherwise we don't know the name of the class we have
   * to pass to JPF
   */
  protected static void runTestsOfThisClass (String[] testMethods){
    // needs to be at the same stack level, so we can't delegate
    Class<? extends TestJPF> testClass = Reflection.getCallerClass(TestJPF.class);
    runTests(testClass, testMethods);
  }

  /**
   * needs to be broken up into two methods for cases that do additional
   * JPF initialization (jpf-inspector)
   *
   * this is called from the various verifyX() methods (i.e. host VM) to
   * start JPF, it is never executed under JPF
   */
  protected JPF createAndRunJPF (StackTraceElement testMethod, String[] args) {
    JPF jpf = createJPF( testMethod, args);
    if (jpf != null){
      jpf.run();
    }
    return jpf;
  }

  /**
   * this is never executed under JPF
   */
  protected JPF createJPF (StackTraceElement testMethod, String[] args) {
    JPF jpf = null;

    Config conf = new Config(args);

    // --- add global args (if we run under RunTest)
    if (globalArgs != null) {
      for (GlobalArg ga : globalArgs) {
        String key = ga.key;
        String val = ga.val;
        if (val != null){
          conf.put(key, val);
        } else {
          conf.remove(key);
        }
      }
    }

    setTestTargetKeys(conf, testMethod);

    // --- initialize the classpath from <projectId>.test_classpath
    String projectId = JPFSiteUtils.getCurrentProjectId();
    if (projectId != null) {
      String testCp = conf.getString(projectId + ".test_classpath");
      if (testCp != null) {
        conf.append("classpath", testCp, ",");
      }
    }

    // --- if we have any specific test property overrides, do so
    conf.promotePropertyCategory("test.");

    getOptions(args);

    if (showConfig || showConfigSources) {
      PrintWriter pw = new PrintWriter(System.out, true);
      if (showConfigSources) {
        conf.printSources(pw);
      }

      if (showConfig) {
        conf.print(pw);
      }
      pw.flush();
    }

    jpf = new JPF(conf);

    return jpf;
  }

  protected void setTestTargetKeys(Config conf, StackTraceElement testMethod) {
    conf.put("target.entry", "runTestMethod([Ljava/lang/String;)V");
    conf.put("target", testMethod.getClassName());
    conf.put("target.test_method", testMethod.getMethodName());
  }

  //--- the JPFShell interface
  @Override
  public void start(String[] testMethods){
    Class<? extends TestJPF> testClass = getClass(); // this is an instance method
    runTests(testClass, testMethods);
  }

  protected StackTraceElement getCaller(){
    StackTraceElement[] st = (new Throwable()).getStackTrace();
    return st[2];
  }

  protected StackTraceElement setTestMethod (String clsName, String mthName){
    return new StackTraceElement( clsName, mthName, null, -1);
  }

  protected StackTraceElement setTestMethod (String mthName){
    return new StackTraceElement( getClass().getName(), mthName, null, -1);
  }

  //--- the JPF run test methods

  /**
   * run JPF expecting a AssertionError in the SuT
   * @param args JPF main() arguments
   */
  protected JPF assertionError (StackTraceElement testMethod, String... args){
    return unhandledException( testMethod, "java.lang.AssertionError", null, args );
  }
  protected JPF assertionError (String... args) {
    return unhandledException( getCaller(), "java.lang.AssertionError", null, args );
  }

  protected JPF assertionErrorDetails (StackTraceElement testMethod, String details, String... args) {
    return unhandledException( testMethod, "java.lang.AssertionError", details, args );
  }
  protected JPF assertionErrorDetails (String details, String... args) {
    return unhandledException( getCaller(), "java.lang.AssertionError", details, args );
  }
  protected boolean verifyAssertionErrorDetails (String details, String... args){
    if (runDirectly) {
      return true;
    } else {
      unhandledException( getCaller(), "java.lang.AssertionError", details, args);
      return false;
    }
  }
  protected boolean verifyAssertionError (String... args){
    if (runDirectly) {
      return true;
    } else {
      unhandledException( getCaller(), "java.lang.AssertionError", null, args);
      return false;
    }
  }

  /**
   * run JPF expecting no SuT property violations
   */
  protected JPF noPropertyViolation (StackTraceElement testMethod, String... args) {
    JPF jpf = null;

    report(args);

    try {
      jpf = createAndRunJPF( testMethod, args);
    } catch (Throwable t) {
      // we get as much as one little hickup and we declare it failed
      t.printStackTrace();
      fail("JPF internal exception executing: ", args, t.toString());
      return jpf;
    }

    List<Error> errors = jpf.getSearchErrors();
    if ((errors != null) && (errors.size() > 0)) {
      fail("JPF found unexpected errors: " + (errors.get(0)).getDescription());
    }

    return jpf;
  }

  protected JPF noPropertyViolation (String... args) {
    return noPropertyViolation( getCaller(), args);
  }

  protected boolean verifyNoPropertyViolation (String...args){
    if (runDirectly) {
      return true;
    } else {
      noPropertyViolation( getCaller(), args);
      return false;
    }
  }

  /**
   * NOTE: this uses the exception class name because it might be an
   * exception type that is only known to JPF (i.e. not in the native classpath)
   *
   * @param xClassName name of the exception base type that is expected
   * @param details detail message of the expected exception
   * @param args JPF arguments
   */
  protected JPF unhandledException (StackTraceElement testMethod, String xClassName, String details, String... args) {
    JPF jpf = null;

    report(args);

    try {
      jpf = createAndRunJPF(testMethod, args);
    } catch (Throwable t) {
      t.printStackTrace();
      fail("JPF internal exception executing: ", args, t.toString());
      return jpf;
    }

    Error error = jpf.getLastError();
    if (error != null){
      Property errorProperty = error.getProperty();
      if (errorProperty instanceof NoUncaughtExceptionsProperty){
        ExceptionInfo xi = ((NoUncaughtExceptionsProperty)errorProperty).getUncaughtExceptionInfo();
        String xn = xi.getExceptionClassname();
        if (!xn.equals(xClassName)) {
          fail("JPF caught wrong exception: " + xn + ", expected: " + xClassName);
        }

        if (details != null) {
          String gotDetails = xi.getDetails();
          if (gotDetails == null) {
            fail("JPF caught the right exception but no details, expected: " + details);
          } else {
            if (!gotDetails.endsWith(details)) {
              fail("JPF caught the right exception but the details were wrong: " + gotDetails + ", expected: " + details);
            }
          }
        }
      } else { // error not a NoUncaughtExceptionsProperty
        fail("JPF failed to catch exception executing: ", args, ("expected " + xClassName));
      }
    } else { // no error
      fail("JPF failed to catch exception executing: ", args, ("expected " + xClassName));
    }

    return jpf;
  }

  protected JPF unhandledException (String xClassName, String details, String... args) {
    return unhandledException( getCaller(), xClassName, details, args);
  }

  protected boolean verifyUnhandledExceptionDetails (String xClassName, String details, String... args){
    if (runDirectly) {
      return true;
    } else {
      unhandledException( getCaller(), xClassName, details, args);
      return false;
    }
  }
  protected boolean verifyUnhandledException (String xClassName, String... args){
    if (runDirectly) {
      return true;
    } else {
      unhandledException( getCaller(), xClassName, null, args);
      return false;
    }
  }

  /**
   * run JPF expecting it to throw an exception
   * NOTE - xClassName needs to be the concrete exception, not a super class
   * @param args JPF main() arguments
   */
  protected JPF jpfException (StackTraceElement testMethod, Class<? extends Throwable> xCls, String... args) {
    JPF jpf = null;
    Throwable exception = null;

    report(args);

    try {
      jpf = createAndRunJPF( testMethod, args);
    } catch (JPF.ExitException xx) {
      exception = xx.getCause();
    } catch (Throwable x) {
      exception = x;
    }

    if (exception != null){
      if (!xCls.isAssignableFrom(exception.getClass())){
        fail("JPF produced wrong exception: " + exception + ", expected: " + xCls.getName());
      }
    } else {
      fail("JPF failed to produce exception, expected: " + xCls.getName());
    }

    return jpf;
  }

  protected JPF jpfException (Class<? extends Throwable> xCls, String... args) {
    return jpfException( getCaller(), xCls, args);
  }

  protected boolean verifyJPFException (TypeRef xClsSpec, String... args){
    if (runDirectly) {
      return true;

    } else {
      try {
        Class<? extends Throwable> xCls = xClsSpec.asNativeSubclass(Throwable.class);

        jpfException( getCaller(), xCls, args);

      } catch (ClassCastException ccx){
        fail("not a property type: " + xClsSpec);
      } catch (ClassNotFoundException cnfx){
        fail("property class not found: " + xClsSpec);
      }
      return false;
    }
  }

  /**
   * run JPF expecting a property violation of the SuT
   * @param args JPF main() arguments
   */
  protected JPF propertyViolation (StackTraceElement testMethod, Class<? extends Property> propertyCls, String... args ){
    JPF jpf = null;

    report(args);

    try {
      jpf = createAndRunJPF( testMethod, args);
    } catch (Throwable t) {
      t.printStackTrace();
      fail("JPF internal exception executing: ", args, t.toString());
    }

    List<Error> errors = jpf.getSearchErrors();
    if (errors != null) {
      for (Error e : errors) {
        if (propertyCls == e.getProperty().getClass()) {
          return jpf; // success, we got the sucker
        }
      }
    }

    fail("JPF failed to detect error: " + propertyCls.getName());
    return jpf;
  }

  protected JPF propertyViolation (Class<? extends Property> propertyCls, String... args ){
    return propertyViolation( getCaller(), propertyCls, args);
  }

  protected boolean verifyPropertyViolation (TypeRef propertyClsSpec, String... args){
    if (runDirectly) {
      return true;

    } else {
      try {
        Class<? extends Property> propertyCls = propertyClsSpec.asNativeSubclass(Property.class);
        propertyViolation( getCaller(), propertyCls, args);

      } catch (ClassCastException ccx){
        fail("not a property type: " + propertyClsSpec);
      } catch (ClassNotFoundException cnfx){
        fail("property class not found: " + propertyClsSpec);
      }
      return false;
    }
  }

  /**
   * run JPF expecting a deadlock in the SuT
   * @param args JPF main() arguments
   */
  protected JPF deadlock (String... args) {
    return propertyViolation( getCaller(), NotDeadlockedProperty.class, args );
  }

  protected boolean verifyDeadlock (String... args){
    if (runDirectly) {
      return true;
    } else {
      propertyViolation( getCaller(), NotDeadlockedProperty.class, args);
      return false;
    }
  }

  // these are the org.junit.Assert APIs, but we don't want org.junit to be
  // required to run tests

  public static void assertEquals(String msg, Object expected, Object actual){
    if (expected == null && actual == null) {
      return;
    }

    if (expected != null && expected.equals(actual)) {
      return;
    }

    fail(msg);
  }

  public static void assertEquals(Object expected, Object actual){
    assertEquals("", expected, actual);
  }

  public static void assertEquals(String msg, int expected, int actual){
    if (expected != actual) {
      fail(msg);
    }
  }

  public static void assertEquals(int expected, int actual){
    assertEquals("expected != actual : " + expected + " != " + actual, expected, actual);
  }

  public static void assertEquals(String msg, long expected, long actual){
    if (expected != actual) {
      fail(msg);
    }
  }

  public static void assertEquals(long expected, long actual){
      assertEquals("expected != actual : " + expected + " != " + actual,
                   expected, actual);
  }

  public static void assertEquals(double expected, double actual){
    if (expected != actual){
      fail("expected != actual : " + expected + " != " + actual);
    }
  }

  public static void assertEquals(String msg, double expected, double actual){
    if (expected != actual){
      fail(msg);
    }
  }

  public static void assertEquals(float expected, float actual){
    if (expected != actual){
      fail("expected != actual : " + expected + " != " + actual);
    }
  }

  public static void assertEquals(String msg, float expected, float actual){
    if (expected != actual){
      fail(msg);
    }
  }

  public static void assertEquals(String msg, double expected, double actual, double delta){
    if (Math.abs(expected - actual) > delta) {
      fail(msg);
    }
  }

  public static void assertEquals(double expected, double actual, double delta){
    assertEquals("Math.abs(expected - actual) > delta : " + "Math.abs(" + expected + " - " + actual + ") > " + delta,
                 expected, actual, delta);
  }

  public static void assertEquals(String msg, float expected, float actual, float delta){
    if (Math.abs(expected - actual) > delta) {
      fail(msg);
    }
  }

  public static void assertEquals(float expected, float actual, float delta){
      assertEquals("Math.abs(expected - actual) > delta : " + "Math.abs(" + expected + " - " + actual + ") > " + delta,
                   expected, actual, delta);
  }

  public static void assertArrayEquals(byte[] expected, byte[] actual){
    if (((expected == null) != (actual == null)) ||
        (expected.length != actual.length)){
      fail("array sizes different");
    }

    for (int i=0; i<expected.length; i++){
      if (expected[i] != actual[i]){
        fail("array element" + i + " different, expected " + expected[i] + ", actual " + actual[i]);
      }
    }
  }

  public static void assertNotNull(String msg, Object o) {
    if (o == null) {
      fail(msg);
    }
  }

  public static void assertNotNull(Object o){
    assertNotNull("o == null", o);
  }

  public static void assertNull(String msg, Object o){
    if (o != null) {
      fail(msg);
    }
  }

  public static void assertNull(Object o){
    assertNull("o != null", o);
  }

  public static void assertSame(String msg, Object expected, Object actual){
    if (expected != actual) {
      fail(msg);
    }
  }

  public static void assertSame(Object expected, Object actual){
    assertSame("expected != actual : " + expected + " != " + actual, expected, actual);
  }

  public static void assertFalse (String msg, boolean cond){
    if (cond) {
      fail(msg);
    }
  }

  public static void assertFalse (boolean cond){
    assertFalse("", cond);
  }

  public static void assertTrue (String msg, boolean cond){
    if (!cond) {
      fail(msg);
    }
  }

  public static void assertTrue (boolean cond){
    assertTrue("", cond);
  }
}


text:
<?php
return [
    'adminEmail' => 'admin@example.com',
    'supportEmail' => 'support@example.com',
    'user.passwordResetTokenExpire' => 3600,

    // Type of Users
    'user.userTypeSystem' => 0,
    'user.userTypeAdmin' => 1,
    'user.userTypeUser' => 2,
    'user.userTypeModerator' => 3,
];


text:
require('./../index');

setInterval(function(){
  EP.report(true);
}, 3000);


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends Front_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    function __construct() {
        parent::__construct();
    }
    public function index()
    {
        $this->layout='home';
        $this->assigns['actived_menu'] = 'home';
        $slider = $this->model
            ->set_type('slider')
            ->desc()
            ->gets();
        $this->assigns['slider'] = $slider;
        $this->render(null,null);
    }
    public function about(){
        $this->assigns['actived_menu'] = 'about';
        $this->layout='main';
        $this->assigns['abouts'] = $this->model->get('15');
        $this->assigns['staffs'] = $this->model
            ->set_type('staff')
            ->gets();
        $this->render('creative/page/about',null);
    }
    public function services($alias = null){
        $this->assigns['actived_menu'] = 'service';
        if($alias){
            $this->service_detail($alias);
        }else{
            $this->layout='main';
            // $this->assigns['abouts'] = $this->model->get('15');
            // $this->assigns['staffs'] = $this->model
            //     ->set_type('staff')
            //     ->gets();
            $this->render('creative/page/services',null);
        }
    }
    public function service_detail($alias = null){
        $this->layout='main';
        $this->assigns['actived_menu'] = 'service';
        // $this->assigns['abouts'] = $this->model->get('15');
        $category_detail = $this->Category_Model
            ->set_type('services')
            ->get_by_alias($alias);
        if($category_detail){
            $this->assigns['category_detail'] = $category_detail;
            $this->assigns['services'] = $this->model
                ->set_type('services')
                ->get_by_category($category_detail->id);
            $this->render('creative/page/service_detail',null);
        } else {
            show_404();
        }
    }
    public function events($alias = null){
        $this->layout='main';
        $this->assigns['actived_menu'] = 'event';
        // $this->assigns['abouts'] = $this->model->get('15');
        if($alias){
            $category_detail = $this->Category_Model
                ->set_type('events')
                ->get_by_alias($alias);
            if($category_detail){
                $this->assigns['category_detail'] = $category_detail;
                $this->assigns['events'] = $this->model
                    ->set_type('events')
                    ->get_by_category($category_detail->id);
                $this->render('creative/page/events',null);
            } else {
                $this->event_detail($alias);
            }
        } else {
            $this->assigns['events'] = $this->model
                ->set_type('events')
                ->gets();
            $this->render('creative/page/events',null);
        }
    }
    public function event_detail($alias = null){
        $this->layout='main';
        $this->assigns['actived_menu'] = 'event';
        $event_detail = $this->model
            ->set_type('events')
            ->get_by_alias($alias);
        if($event_detail){
            $this->get_seo_tags($event_detail);
            $this->assigns['event_detail'] = $event_detail;
            $category_detail = $this->Category_Model
                ->set_type('events')
                ->get($event_detail->category);
            $this->assigns['category_detail'] = $category_detail;

            $this->assigns['related_events'] = $this->model
                ->limit(4)
                ->random()
                ->get_related($event_detail);
            $this->render('creative/page/event_detail',null);
        } else {
            show_404();
        }
    }

    public function projects($alias = null){
        $this->layout='main';
        $this->assigns['actived_menu'] = 'project';
        // $this->assigns['abouts'] = $this->model->get('15');
        if($alias){
            $category_detail = $this->Category_Model
                ->set_type('services')
                ->get_by_alias($alias);
            if($category_detail){
                $this->assigns['category_detail'] = $category_detail;
                $this->assigns['projects'] = $this->model
                    ->set_type('projects')
                    ->get_by_category($category_detail->id);
                $this->render('creative/page/projects',null);
            } else {
                $this->project_detail($alias);
            }
        } else {
            $this->assigns['projects'] = $this->model
                ->set_type('projects')
                ->asc()
                ->gets();
            $this->render('creative/page/projects',null);
        }
    }
    public function project_detail($alias = null){
        $this->layout='main';
        $this->assigns['actived_menu'] = 'project';
        $project_detail = $this->model
            ->set_type('projects')
            ->get_by_alias($alias);
        if($project_detail){
            $this->get_seo_tags($project_detail);
            $this->assigns['project_detail'] = $project_detail;
            $category_detail = $this->Category_Model
                ->set_type('services')
                ->get($project_detail->category);
            $this->assigns['category_detail'] = $category_detail;

            $this->assigns['related_projects'] = $this->model
                ->limit(4)
                ->random()
                ->get_related($project_detail);
            $this->render('creative/page/project_detail',null);
        } else {
            show_404();
        }
    }

    public function blogs($alias = null,$page = 1){
        if($alias=='all') $alias = null;
        $this->layout='main';
        $this->assigns['actived_menu'] = 'news';
        $perpage = 6;
        if($alias){
            $category_detail = $this->Category_Model
                ->set_type('services')
                ->get_by_alias($alias);
            if($category_detail){
                $this->get_seo_tags($category_detail);
                $this->assigns['category_detail'] = $category_detail;
                $this->assigns['blogs'] = $this->model
                    ->CALC_FOUND_ROWS()
                    ->set_type('news-blogs')
                    ->join_category()
                    ->limit($page,$perpage)
                    ->get_by_category($category_detail->id);
                $this->assigns['paging'] = $this->paging($page,$perpage,base_url("tin-tuc/{$category_detail->alias}/page"));
                $this->render('creative/page/blogs',null);
            } else {
                $this->blog_detail($alias);
            }
        } else {
            $this->assigns['blogs'] = $this->model
                ->CALC_FOUND_ROWS()
                ->set_type('news-blogs')
                ->asc()
                ->join_category()
                ->limit($page,$perpage)
                ->gets();
            $this->assigns['paging'] = $this->paging($page,$perpage,base_url('tin-tuc/page'));
            $this->render('creative/page/blogs',null);
        }
    }
    public function blog_detail($alias = null){
        $this->layout='main';
        $this->assigns['actived_menu'] = 'news';
        $blog_detail = $this->model
            ->set_type('news-blogs')
            ->get_by_alias($alias);
        if($blog_detail){
            $this->get_seo_tags($blog_detail);

            $this->assigns['blog_detail'] = $blog_detail;
            $category_detail = $this->Category_Model
                ->set_type('services')
                ->get($blog_detail->category);
            $this->assigns['category_detail'] = $category_detail;

            $this->assigns['related_blogs'] = $this->model
                ->limit(4)
                ->random()
                ->get_related($blog_detail);
            $this->render('creative/page/blog_detail',null);
        } else {
            show_404();
        }
    }
    function contact(){
        $this->layout='main';
        $this->render('creative/page/contact',null);
    }
    function recruitment(){
        $this->layout='main';
        $this->assigns['actived_menu'] = 'recruitment';
        $this->assigns['recruitments'] = $this->model
                    ->set_type('recruitment')
                    ->gets();
        $this->render('creative/page/recruitment',null);
    }

}


text:
<!doctype html>

    <title>Popup</title>
    <link href="resources/css/popup.css" rel="stylesheet" type="text/css">

Unknown Source

        Email or Username:

        <input type="email" id="userid" /><button id="updateUserId">Update</button>

        <button id="login">Login</button>


text:
---
title: Rule space-return-throw-case
layout: doc
---
<!-- Note: No pull requests accepted for this file. See README.md in the root directory for details. -->
# Require spaces following `return`, `throw`, and `case` (space-return-throw-case)

**Replacement notice**: This rule was removed in ESLint v2.0 and replaced by [keyword-spacing](keyword-spacing) rule.

Require spaces following `return`, `throw`, and `case`.

**Fixable:** This rule is automatically fixable using the `--fix` flag on the command line.

## Rule Details

The following patterns are considered problems:

```js
/*eslint space-return-throw-case: 2*/

throw{a:0}                   /*error Keyword 'throw' must be followed by whitespace.*/

function f(){ return-a; }    /*error Keyword 'return' must be followed by whitespace.*/

switch(a){ case'a': break; } /*error Keyword 'case' must be followed by whitespace.*/
```

The following patterns are not considered problems:

```js
/*eslint space-return-throw-case: 2*/

throw {a: 0};

function f(){ return -a; }

switch(a){ case 'a': break; }
```

## Version

This rule was introduced in ESLint 0.1.4 and removed in 2.0.0-beta.3.

## Resources

* [Documentation source](https://github.com/eslint/eslint/tree/master/docs/rules/space-return-throw-case.md)


text:
=======
Support
=======

There are several ways to get in touch with the developers.

.. _mailing_lists:

Mailing List
============

- The main mailing list is `scikit-learn
  <https://mail.python.org/mailman/listinfo/scikit-learn>`_.

- There is also a commit list `scikit-learn-commits
  <https://lists.sourceforge.net/lists/listinfo/scikit-learn-commits>`_,
  where updates to the main repository and test failures get notified.

.. _user_questions:

User questions
==============

- Some scikit-learn developers support users on StackOverflow using
  the `[scikit-learn] <http://stackoverflow.com/questions/tagged/scikit-learn>`_
  tag.

- For general theoretical or methodological Machine Learning questions
  `stack exchange <http://stats.stackexchange.com/>`_ is probably a more
  suitable venue.

In both cases please use a descriptive question in the title field (e.g.
no "Please help with scikit-learn!" as this is not a question) and put
details on what you tried to achieve, what were the expected results and
what you observed instead in the details field.

Code and data snippets are welcome. Minimalistic (up to ~20 lines long)
reproduction script very helpful.

Please describe the nature of your data and the how you preprocessed it:
what is the number of samples, what is the number and type of features
(i.d. categorical or numerical) and for supervised learning tasks,
what target are your trying to predict: binary, multiclass (1 out of
``n_classes``) or multilabel (``k`` out of ``n_classes``) classification
or continuous variable regression.

.. _bug_tracker:

Bug tracker
===========

If you think you've encountered a bug, please report it to the issue tracker:

https://github.com/scikit-learn/scikit-learn/issues

Don't forget to include:

  - steps (or better script) to reproduce,

  - expected outcome,

  - observed outcome or python (or gdb) tracebacks

To help developers fix your bug faster, please link to a https://gist.github.com
holding a standalone minimalistic python script that reproduces your bug and
optionally a minimalistic subsample of your dataset (for instance exported
as CSV files using ``numpy.savetxt``).

Note: gists are git cloneable repositories and thus you can use git to
push datafiles to them.

.. _irc:

IRC
===

Some developers like to hang out on channel ``#scikit-learn`` on
``irc.freenode.net``.

If you do not have an IRC client or are behind a firewall this web
client works fine: http://webchat.freenode.net

.. _documentation_resources:

Documentation resources
=======================

This documentation is relative to |release|. Documentation for other
versions can be found here:

    * `0.18 <http://scikit-learn.org/0.18/>`_
    * `0.17 <http://scikit-learn.org/0.17/>`_
    * `0.16 <http://scikit-learn.org/0.16/>`_
    * `0.15 <http://scikit-learn.org/0.15/>`_

Printable pdf documentation for all versions can be found `here
<https://sourceforge.net/projects/scikit-learn/files/documentation/>`_.


text:
{% extends "website/base_site.html" %}

{% block main_container %}

word.

{% endblock %}


text:
namespace Zenject
{
    public class IfNotBoundBinder
    {
        public IfNotBoundBinder(BindInfo bindInfo)
        {
            BindInfo = bindInfo;
        }

        // Do not use this
        public BindInfo BindInfo
        {
            get;
            private set;
        }

        public void IfNotBound()
        {
            BindInfo.OnlyBindIfNotBound = true;
        }
    }
}


text:
class Heap
  def self.left_idx(i);  2*i + 1 end
  def self.right_idx(i)  2*i + 2 end
  def self.parent_idx(i) (i-1)/2 end

  # Initialize a new heap.  If +size+ is given, space for that many
  # elements will be allocated up front.  The heap is not limited to
  # +size+ elements.  Values passed into the heap are compared with the
  # given block (or proc {|a,b| a < b}, if no block is
  # given).  if block.call(a,b) is true, then a will be placed closer to
  # the root than b.  The default implements a max heap.
  def initialize(size=nil, &block)
    @cmp = block_given? ? block : proc {|a,b| a < b}
    @data = size.nil? ? Array.new : Array.new(size)
    @bottom = 0 # index of bottom of heap
  end

  # Return the number of values in the heap.
  def size
    @bottom
  end

  # Add an element to the heap.  Rebalances the heap. Returns self.
  def add(el)
    @data[@bottom] = el
    bubble_up(@bottom)
    @bottom += 1
    self
  end

  # returns, but does not remove, the top of the heap.
  def top
    raise "Empty heap" if @bottom == 0
    @data[0]
  end

  # removes and returns the top of the heap
  def delete_top
    raise "Empty heap" if @bottom == 0
    ret_value = @data[0]
    @bottom -= 1

    if @bottom > 0
      @data[0] = @data[@bottom]
      percolate_down(0)
    end

    ret_value
  end

  # Test the node at index +i+ for heap violation.  If it violates the
  # heap property, push it up until it doesn't.
  def bubble_up(i)
    return if i <= 0

    parent = Heap.parent_idx i
    if @cmp.call(@data[i], @data[parent])
      @data[i], @data[parent] = @data[parent], @data[i]
      bubble_up(parent)
    end
  end

  # Test the node at index +i+ for heap violation.  If it violates the
  # heap property, push it down until it doesn't.
  def percolate_down(i)
    return if i >= @bottom

    li = Heap.left_idx  i
    return if li >= @bottom # we fill left to right, so => right is empty too

    ri = Heap.right_idx i
    child = if ri >= @bottom
              li
            else
              @cmp.call(@data[li], @data[ri]) ? li : ri
            end
    if @cmp.call(@data[child], @data[i])
      @data[child], @data[i] = @data[i], @data[child]
      percolate_down(child)
    end
  end

  # Return an unsorted array of all the values.  The max (min) element is
  # at index 0, but no other gurantee is made.
  def values
    if @bottom > 0
      # TODO: why was the reverse in there???
      #        @data[0..(@bottom-1)].reverse
      @data[0..(@bottom-1)]
    else
      []
    end
  end

  # Remove all elements from the heap and return them in sorted order.
  def remove_all
    Array.new(@bottom) { |i| self.delete_top }
  end
end

# Maintains a collection of at most K elements that best meet some
# criteria.  Elements are added to the collection, but only if they are one
# of the K best seen so far.  The notion of best is supplied by the client
# code as a block to the constructor.
#
# == Example:
#
# To collect the best ten random numbers, where "best" is defined as
# "bigger" (i.e., '>'):
#
#     best = BestK.new(10)
#     1_000.times {|i| best.add rand(100) }
#     best.values  # => an array of the ten biggest numbers seen
#
class BestK < Heap
  # Initializes a new BestK element to manage at most +k+ elements.  If a
  # block is given, then it is used to determine which of two objects is
  # better.  The block should take two arguments and return true if the
  # first object is better than the second.  The default comparison is
  # "bigger is better":  { |a,b| a > b }
  #
  def initialize(k, &block)
    raise ArgumentError, "k must be greater than 0: #{k}" unless k > 0
    # Because we really use a heap, we need to invert the logic of the
    # comparison, since we throw away the top element of the heap.
    cmp = block_given? ?
      Proc.new {|a,b| not block.call(a,b) } :
      Proc.new {|a,b| a <= b }

    super(k, &cmp)
    @limit = k
  end

  # Returns true if we have N elements.
  def full?
    @limit == size
  end

  # Attempt to add +el+ to receiver.  +el+ will be added if there are fewer
  # than k elements already in receiver, or if el is better than the worst
  # element already in receiver.  "better" is measured by the block passed
  # to receiver's initializer.
  # Returns receiver.
  def add(el)
    if size >= @limit
      # Only bother to insert if it is not worse than
      # the top element.
      if @cmp.call(top, el)
        super(el)
        delete_top
      end
    else
      super(el)
    end
    self
  end

  # Return the worst element seen so far.
  def worst
    top
  end
end


text:
=====
Usage
=====

Import
======

So MSS can be used as simply as::

    from mss import mss

Or import the good one based on your operating system::

    # MacOS X
    from mss.darwin import MSS as mss

    # GNU/Linux
    from mss.linux import MSS as mss

    # Microsoft Windows
    from mss.windows import MSS as mss

Instance
========

So the module can be used as simply as::

    with mss() as sct:
        # ...

Intensive Use
=============

If you plan to integrate MSS inside your own module or software, pay attention to using it wisely.

This is a bad usage::

    for _ in range(100):
        with mss() as sct:
            sct.shot()

This is a much better usage, memory efficient::

    with mss() as sct:
        for _ in range(100):
            sct.shot()

Also, it is a good thing to save the MSS instance inside an attribute of your class and calling it when needed.

GNU/Linux
---------

On GNU/Linux, you can specify which display to use (useful for distant screenshots via SSH)::

    with mss(display=":0.0") as sct:
        # ...

A more specific example (only valid on GNU/Linux):

.. literalinclude:: examples/linux_display_keyword.py
    :lines: 8-

Command Line
============

You can use ``mss`` via the CLI::

    mss --help

Or via direct call from Python::

    python -m mss --help

.. versionadded:: 3.1.1


text:
<component name="libraryTable">
  <library name="appcompat-v7-25.3.1">
    <CLASSES>
      <root url="jar://$USER_HOME$/.android/build-cache/7ddd0ecbc224bd59ab2dd030617fc5383982debd/output/jars/classes.jar!/" />
      <root url="file://$USER_HOME$/.android/build-cache/7ddd0ecbc224bd59ab2dd030617fc5383982debd/output/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://C:/android/android-sdk-windows/extras/android/m2repository/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
def cheese_and_crackers(cheese_count, boxes_of_crackers)
  puts "You have #{cheese_count} cheeses!"
  puts "You have #{boxes_of_crackers} boxes of crackers!"
  puts "Man, that's enough for a party!"
  puts "Get a blanket.\n"
end

puts 'We can just give the function numbers directly:'
cheese_and_crackers(20, 30)

puts 'OR, we can use variables from our script:'
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)

puts 'We can even do math inside too:'
cheese_and_crackers(10 + 20, 5 + 6)

puts 'And we can combine the two, variables and math:'
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)


text:
var nodemailer = require('nodemailer');
var sendgridTransport = require('nodemailer-sendgrid-transport');
var Promise = require('bluebird');
var config = require('s-conf');

var transport = sendgridTransport({
    auth: {
        api_key: config.require('sendgrid_api_key')
    }
});

var mailer = nodemailer.createTransport(transport);

exports.sendMail = function (mail) {
    mail.from = "Phoenix Musical <notification@phoenixmusical.ca>";
    return new Promise(function (resolve, reject) {
        console.log('sendMail', mail);
        mailer.sendMail(mail, function (err, result) {
            if (err) {
                return reject(err);
            }
            resolve(result);
        });
    });
};


text:
#ifndef _PIDENT_H_
#define _PIDENT_H_

#include <string>

#include "PObject.h"

using namespace std;

// Variable
class PIdent : public PObject
{
   protected:
   	string m_sIdent;

   protected:
		// PObject's constructor is protected because they should not be new directly.
		// A node can be new by using static "create" function
		// This is for the purpose of memory management
		PIdent( char* ident );

	public:
		virtual ~PIdent();

		string	toString();

	//---------------------------------------------------------------
	// Memory management functions

	public:
		// New a PObject and put it in the m_lpList
		static PIdent* create(char* ident);
};

#endif // _PIDENT_H_


text:
"use strict";

const Constants = require("../../../Constants");
const Events = Constants.Events;
const Endpoints = Constants.Endpoints;
const apiRequest = require("../../../core/ApiRequest");

module.exports = function(channelId) {
  return new Promise((rs, rj) => {
    var request = apiRequest
    .get(this, Endpoints.PINS(channelId));

    this._queueManager.put(request, (err, res) => {
      if (err || !res.ok)
        return rj(err);

      const event = {
        channelId: channelId,
        messages: res.body
      };
      this.Dispatcher.emit(Events.LOADED_PINNED_MESSAGES, event);
      rs(event);
    });
  });
};


text:
"""
Django settings for check project.

Generated by 'django-admin startproject' using Django 1.11.2.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os
from decouple import config
from dj_database_url import parse as dburl

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'f#76%te7$=57de5md7-*$5+1&-8byg=gn5r=qx-+y3-xosvv9@'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=False, cast=bool)

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'check.core',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'crispy_forms',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'check.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['./check/templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'check.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3')

DATABASES = {
    'default': config('DATABASE_URL', default=default_dburl, cast=dburl)
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'pt-br'

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

# STATIC_URL = '/static/'
# STATICFILES_DIRS = (os.path.join(
#     BASE_DIR, "check", "static"),)
#
# STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "deployment", "check", "static")

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
)

CRISPY_TEMPLATE_PACK = 'bootstrap4'

AUTH_USER_MODEL = 'core.User'
LOGIN_REDIRECT_URL = 'index'
LOGIN_URL = '/core/login/'
SESSION_EXPIRE_AT_BROWSER_CLOSE = True


text:
package com.suscipio_solutions.consecro_mud.MOBS;
import java.util.Random;

import com.suscipio_solutions.consecro_mud.Common.interfaces.CharStats;
import com.suscipio_solutions.consecro_mud.Common.interfaces.Faction;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;

public class Penguin extends StdMOB
{
	@Override public String ID(){return "Penguin";}
	public Penguin()
	{
		super();
		final Random randomizer = new Random(System.currentTimeMillis());

		username="a penguin";
		setDescription("It\\`s a short flightless bird with webbed feet and a short wagging tail.");
		setDisplayText("A penguin waddles here.");
		CMLib.factions().setAlignment(this,Faction.Align.NEUTRAL);
		setMoney(0);
		basePhyStats.setWeight(30 + Math.abs(randomizer.nextInt() % 55));
		setWimpHitPoint(2);

		addBehavior(CMClass.getBehavior("Follower"));
		addBehavior(CMClass.getBehavior("MudChat"));

		basePhyStats().setDamage(4);

		baseCharStats().setStat(CharStats.STAT_INTELLIGENCE,1);

		basePhyStats().setAbility(0);
		basePhyStats().setLevel(1);
		basePhyStats().setArmor(90);

		baseCharStats().setMyRace(CMClass.getRace("Penguin"));
		baseCharStats().getMyRace().startRacing(this,false);
		baseState.setHitPoints(CMLib.dice().roll(basePhyStats().level(),20,basePhyStats().level()));

		recoverMaxState();
		resetToMaxState();
		recoverPhyStats();
		recoverCharStats();
	}

}