text:
#ifndef DIALOG_H_
#define DIALOG_H_

#include <alljoyn/controlpanel/RootWidget.h>

namespace ajn {
namespace services {

/**
 * Action Class. Used to display a Dialog.
 * This is an abstract class. The executeActionCallBack functions need to be overridden.
 */
class Dialog : public RootWidget {
  public:

    /**
     * Constructor for Dialog Widget
     * @param name - name of Widget
     * @param rootWidget - the RootWidget of the widget
     */
    Dialog(qcc::String const& name, Widget* rootWidget);

    /**
     * Constructor for Dialog Widget
     * @param name - name of Widget
     * @param rootWidget - the RootWidget of the widget
     * @param objectPath - objectPath of Widget
     * @param device - device that contains this Widget
     */
    Dialog(qcc::String const& name, Widget* rootWidget, qcc::String const& objectPath, ControlPanelDevice* device);

    /**
     * Constructor for Dialog Widget
     * @param name - name of Widget
     * @param rootWidget - the RootWidget of the widget
     * @param device - device that contains this Widget
     */
    Dialog(qcc::String const& name, Widget* rootWidget, ControlPanelDevice* device);

    /**
     * Destructor for Dialog Widget
     */
    virtual ~Dialog();

    /**
     * creates and returns the appropriate BusObject for this Widget
     * @param bus - the bus used to create the widget
     * @param objectPath - the objectPath of the widget
     * @param langIndx - the language Indx
     * @param status - the status indicating success or failure
     * @return a newly created WidgetBusObject
     */
    WidgetBusObject* createWidgetBusObject(BusAttachment* bus, qcc::String const& objectPath,
                                           uint16_t langIndx, QStatus& status);

    /**
     * Get the Number of Actions in the Dialog
     * @return Number of Actions
     */
    const uint16_t getNumActions() const;

    /**
     * Set the number of Actions in the Dialog
     * @param numActions - number of Actions
     */
    void setNumActions(const uint16_t numActions);

    /**
     * Get the Message of the Dialog
     * @return the message
     */
    const qcc::String& getMessage() const;

    /**
     * Get the Message Vector of the Dialog
     * @return the Messages
     */
    const std::vector<qcc::String>& getMessages() const;

    /**
     * Set the Message vector of the Dialog
     * @param messages - the messages
     */
    void setMessages(const std::vector<qcc::String>& messages);

    /**
     * Get the GetMessage Function Pointer for the Dialog
     * @return GetMessage function pointer
     */
    GetStringFptr getGetMessages() const;

    /**
     * Set the GetMessage Function Pointer for the Dialog
     * @param getMessages - the GetMessage function pointer
     */
    void setGetMessages(GetStringFptr getMessages);

    /**
     * Get the LabelAction1 of the Dialog
     * @return the message
     */
    const qcc::String& getLabelAction1() const;

    /**
     * Get the LabelAction2 of the Dialog
     * @return the message
     */
    const qcc::String& getLabelAction2() const;

    /**
     * Get the LabelAction3 of the Dialog
     * @return the message
     */
    const qcc::String& getLabelAction3() const;

    /**
     * Get the Vector of Labels for Action 1
     * @return label for Action 1
     */
    const std::vector<qcc::String>& getLabelsAction1() const;

    /**
     * Set the Vector of Labels for Action 1
     * @param labelsAction1
     */
    void setLabelsAction1(const std::vector<qcc::String>& labelsAction1);

    /**
     * Get the GetLabel Function Pointer for Action 1
     * @return GetLabel Function Pointer for Action 1
     */
    GetStringFptr getGetLabelsAction1() const;

    /**
     * Set the GetLabel function Pointer for Action 1
     * @param getLabelsAction1
     */
    void setGetLabelsAction1(GetStringFptr getLabelsAction1);

    /**
     * Get the Vector of Labels for Action 2
     * @return label for Action 3
     */
    const std::vector<qcc::String>& getLabelsAction2() const;

    /**
     * Set the Vector of Labels for Action 2
     * @param labelsAction2
     */
    void setLabelsAction2(const std::vector<qcc::String>& labelsAction2);

    /**
     * Set the GetLabel function Pointer for Action 2
     * @return getLabelAction2
     */
    GetStringFptr getGetLabelsAction2() const;

    /**
     * Set the GetLabel function Pointer for Action 2
     * @param getLabelsAction2
     */
    void setGetLabelsAction2(GetStringFptr getLabelsAction2);

    /**
     * Get the Vector of Labels for Action 3
     * @return label for Action 3
     */
    const std::vector<qcc::String>& getLabelsAction3() const;

    /**
     * Set the Vector of Labels for Action 3
     * @param labelsAction3
     */
    void setLabelsAction3(const std::vector<qcc::String>& labelsAction3);

    /**
     * Set the GetLabel function Pointer for Action 3
     * @return getLabelAction3
     */
    GetStringFptr getGetLabelsAction3() const;

    /**
     * Set the GetLabel function Pointer for Action 3
     * @param getLabelsAction3
     */
    void setGetLabelsAction3(GetStringFptr getLabelsAction3);

    /**
     * Fill the MsgArg passed in with the OptionalParams
     * @param val - msgArg to fill
     * @param languageIndx - the languageIndx used for the Labels
     * @return status - success/failure
     */
    QStatus fillOptParamsArg(MsgArg& val, uint16_t languageIndx);

    /**
     * Fill the MsgArg passed in with the Message Param
     * @param val - msgArg to fill
     * @param languageIndx - the languageIndx used for the Message
     * @return status - success/failure
     */
    QStatus fillMessageArg(MsgArg& val, uint16_t languageIndx);

    /**
     * Fill the MsgArg passed in with the NumActions
     * @param val - msgArg to fill
     * @param languageIndx - the languageIndx
     * @return status - success/failure
     */
    QStatus fillNumActionArg(MsgArg& val, uint16_t languageIndx);

    /**
     * Read the MsgArg passed in to fill the Message property
     * @param val - MsgArg passed in
     * @return status - success/failure
     */
    QStatus readMessageArg(MsgArg* val);

    /**
     * Read the MsgArg passed in to fill the NumActions property
     * @param val - MsgArg passed in
     * @return status - success/failure
     */
    QStatus readNumActionsArg(MsgArg* val);

    /**
     * Call to execute this Dialog's Action 1 remotely
     * @return status - success/failure
     */
    QStatus executeAction1();

    /**
     * Call to execute this Dialog's Action 2 remotely
     * @return status - success/failure
     */
    QStatus executeAction2();

    /**
     * Call to execute this Dialog's Action 3 remotely
     * @return status - success/failure
     */
    QStatus executeAction3();

    /**
     * Pure Virtual Method to be overridden
     * Callback for execute of Action1
     * @return success/failure
     */
    virtual bool executeAction1CallBack();

    /**
     * Pure Virtual Method to be overridden
     * Callback for execute of Action2
     * @return success/failure
     */
    virtual bool executeAction2CallBack();

    /**
     * Pure Virtual Method to be overridden
     * Callback for execute of Action3
     * @return success/failure
     */
    virtual bool executeAction3CallBack();

  protected:

    /**
     * Number of Actions in Dialog
     */
    uint16_t m_NumActions;

    /**
     * The message of the dialog
     */
    qcc::String m_Message;

    /**
     * The message vector of the dialog
     */
    std::vector<qcc::String> m_Messages;

    /**
     * The GetMessage Function Pointer of the Dialog
     */
    GetStringFptr m_GetMessages;

    /**
     * The Label of the dialog for Action 1
     */
    qcc::String m_LabelAction1;

    /**
     * The Label vector for Action1
     */
    std::vector<qcc::String> m_LabelsAction1;

    /**
     * The GetLabel function pointer for Action 1
     */
    GetStringFptr m_GetLabelsAction1;

    /**
     * The Label of the dialog for Action 2
     */
    qcc::String m_LabelAction2;

    /**
     * The Label vector for Action2
     */
    std::vector<qcc::String> m_LabelsAction2;

    /**
     * The GetLabel function pointer for Action 2
     */
    GetStringFptr m_GetLabelsAction2;

    /**
     * The Label of the dialog for Action 3
     */
    qcc::String m_LabelAction3;

    /**
     * The Label vector for Action3
     */
    std::vector<qcc::String> m_LabelsAction3;

    /**
     * The GetLabel function pointer for Action 3
     */
    GetStringFptr m_GetLabelsAction3;

    /**
     * Read the MsgArg passed in and fill the OptParam
     * @param key - the optParam to fill
     * @param val - the MsgArg passed in
     * @return status - success/failure
     */
    virtual QStatus readOptParamsArg(uint16_t key, MsgArg* val);

    /**
     * Private method used to log a call to an Action that is Not Defined
     * @return false - for failure
     */
    bool executeActionNotDefined();
};
} //namespace services
} //namespace ajn

#endif /* DIALOG_H_ */


text:
//  tagged pointer, for aba prevention
//
//  Copyright (C) 2008 Tim Blechmann
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  Disclaimer: Not a Boost library.

#ifndef BOOST_LOCKFREE_TAGGED_PTR_DCAS_HPP_INCLUDED
#define BOOST_LOCKFREE_TAGGED_PTR_DCAS_HPP_INCLUDED

#include <boost/lockfree/detail/branch_hints.hpp>

#include <cstddef>              /* for std::size_t */

namespace boost
{
namespace lockfree
{

template <class T>
class BOOST_LOCKFREE_DCAS_ALIGNMENT tagged_ptr
{
public:
    typedef std::size_t tag_t;

    void set(T * p, tag_t t)
    {
        ptr = p;
        tag = t;
    }
    /* @} */

    /** comparing semantics */
    /* @{ */
    bool operator== (volatile tagged_ptr const & p) const
    {
        return (ptr == p.ptr) && (tag == p.tag);
    }

    bool operator!= (volatile tagged_ptr const & p) const
    {
        return !operator==(p);
    }
    /* @} */

    /** pointer access */
    /* @{ */
    T * get_ptr(void) const volatile
    {
        return ptr;
    }

    void set_ptr(T * p) volatile
    {
        ptr = p;
    }
    /* @} */

    /** tag access */
    /* @{ */
    tag_t get_tag() const volatile
    {
        return tag;
    }

    void set_tag(tag_t t) volatile
    {
        tag = t;
    }
    /* @} */

    /** smart pointer support  */
    /* @{ */
    T & operator*() const
    {
        return *ptr;
    }

    T * operator->() const
    {
        return ptr;
    }

    operator bool(void) const
    {
        return ptr != 0;
    }
    /* @} */

protected:
    T * ptr;
    tag_t tag;
};

} /* namespace lockfree */
} /* namespace boost */

#endif /* BOOST_LOCKFREE_TAGGED_PTR_DCAS_HPP_INCLUDED */

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.component.wordpress.api.model;

import java.io.Serializable;
import java.util.List;

import static com.google.common.base.MoreObjects.toStringHelper;

/**
 * Search criterias.
 */
public class SearchCriteria implements Serializable {

    private static final long serialVersionUID = 1002576245120313648L;

    private Integer page;
    private Integer perPage;
    private String search;
    private Order order;
    private List<Integer> exclude;
    private List<Integer> include;

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getPerPage() {
        return perPage;
    }

    public void setPerPage(Integer perPage) {
        this.perPage = perPage;
    }

    public String getSearch() {
        return search;
    }

    public void setSearch(String search) {
        this.search = search;
    }

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }

    public List<Integer> getExclude() {
        return exclude;
    }

    public void setExclude(List<Integer> exclude) {
        this.exclude = exclude;
    }

    public List<Integer> getInclude() {
        return include;
    }

    public void setInclude(List<Integer> include) {
        this.include = include;
    }

    @Override
    public String toString() {
        // @formatter:off
        return toStringHelper(this).add("Query", this.search).add("Page", page).add("Per Page", perPage).addValue(this.order).toString();
    }

}


text:
from __future__ import unicode_literals

from django.apps import apps
from django.core.management.color import no_style
from django.core.management.sql import (sql_create, sql_delete, sql_indexes,
    sql_destroy_indexes, sql_all)
from django.db import connections, DEFAULT_DB_ALIAS, router
from django.test import TestCase
from django.utils import six

# See also initial_sql_regress for 'custom_sql_for_model' tests

class SQLCommandsTestCase(TestCase):
    """Tests for several functions in django/core/management/sql.py"""
    def count_ddl(self, output, cmd):
        return len([o for o in output if o.startswith(cmd)])

    def test_sql_create(self):
        app_config = apps.get_app_config('commands_sql')
        output = sql_create(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
        create_tables = [o for o in output if o.startswith('CREATE TABLE')]
        self.assertEqual(len(create_tables), 3)
        # Lower so that Oracle's upper case tbl names wont break
        sql = create_tables[-1].lower()
        six.assertRegex(self, sql, r'^create table .commands_sql_book.*')

    def test_sql_delete(self):
        app_config = apps.get_app_config('commands_sql')
        output = sql_delete(app_config, no_style(), connections[DEFAULT_DB_ALIAS], close_connection=False)
        drop_tables = [o for o in output if o.startswith('DROP TABLE')]
        self.assertEqual(len(drop_tables), 3)
        # Lower so that Oracle's upper case tbl names wont break
        sql = drop_tables[-1].lower()
        six.assertRegex(self, sql, r'^drop table .commands_sql_comment.*')

    def test_sql_indexes(self):
        app_config = apps.get_app_config('commands_sql')
        output = sql_indexes(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
        # PostgreSQL creates one additional index for CharField
        self.assertIn(self.count_ddl(output, 'CREATE INDEX'), [3, 4])

    def test_sql_destroy_indexes(self):
        app_config = apps.get_app_config('commands_sql')
        output = sql_destroy_indexes(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
        # PostgreSQL creates one additional index for CharField
        self.assertIn(self.count_ddl(output, 'DROP INDEX'), [3, 4])

    def test_sql_all(self):
        app_config = apps.get_app_config('commands_sql')
        output = sql_all(app_config, no_style(), connections[DEFAULT_DB_ALIAS])

        self.assertEqual(self.count_ddl(output, 'CREATE TABLE'), 3)
        # PostgreSQL creates one additional index for CharField
        self.assertIn(self.count_ddl(output, 'CREATE INDEX'), [3, 4])

class TestRouter(object):
    def allow_migrate(self, db, model):
        return False

class SQLCommandsRouterTestCase(TestCase):
    def setUp(self):
        self._old_routers = router.routers
        router.routers = [TestRouter()]

    def tearDown(self):
        router.routers = self._old_routers

    def test_router_honored(self):
        app_config = apps.get_app_config('commands_sql')
        for sql_command in (sql_all, sql_create, sql_delete, sql_indexes, sql_destroy_indexes):
            if sql_command is sql_delete:
                output = sql_command(app_config, no_style(), connections[DEFAULT_DB_ALIAS], close_connection=False)
            else:
                output = sql_command(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
            self.assertEqual(len(output), 0,
                "%s command is not honoring routers" % sql_command.__name__)


text:
"""Author Alexandre De Zotti

Draws Julia sets of quadratic polynomials and exponential maps.
 More specifically, this iterates the function a fixed number of times
 then plots whether the absolute value of the last iterate is greater than
 a fixed threshold (named "escape radius"). For the exponential map this is not
 really an escape radius but rather a convenient way to approximate the Julia
 set with bounded orbits.

The examples presented here are:
- The Cauliflower Julia set, see e.g.
https://en.wikipedia.org/wiki/File:Julia_z2%2B0,25.png
- Other examples from https://en.wikipedia.org/wiki/Julia_set
- An exponential map Julia set, ambiantly homeomorphic to the examples in
https://www.math.univ-toulouse.fr/~cheritat/GalII/galery.html
 and
https://ddd.uab.cat/pub/pubmat/02141493v43n1/02141493v43n1p27.pdf

Remark: Some overflow runtime warnings are suppressed. This is because of the
 way the iteration loop is implemented, using numpy's efficient computations.
 Overflows and infinites are replaced after each step by a large number.
"""

import warnings
from collections.abc import Callable
from typing import Any

import numpy
from matplotlib import pyplot

c_cauliflower = 0.25 + 0.0j
c_polynomial_1 = -0.4 + 0.6j
c_polynomial_2 = -0.1 + 0.651j
c_exponential = -2.0
nb_iterations = 56
window_size = 2.0
nb_pixels = 666

def eval_exponential(c_parameter: complex, z_values: numpy.ndarray) -> numpy.ndarray:
    """
    Evaluate $e^z + c$.
    >>> eval_exponential(0, 0)
    1.0
    >>> abs(eval_exponential(1, numpy.pi*1.j)) < 1e-15
    True
    >>> abs(eval_exponential(1.j, 0)-1-1.j) < 1e-15
    True
    """
    return numpy.exp(z_values) + c_parameter

def eval_quadratic_polynomial(
    c_parameter: complex, z_values: numpy.ndarray
) -> numpy.ndarray:
    """
    >>> eval_quadratic_polynomial(0, 2)
    4
    >>> eval_quadratic_polynomial(-1, 1)
    0
    >>> round(eval_quadratic_polynomial(1.j, 0).imag)
    1
    >>> round(eval_quadratic_polynomial(1.j, 0).real)
    0
    """
    return z_values * z_values + c_parameter

def prepare_grid(window_size: float, nb_pixels: int) -> numpy.ndarray:
    """
    Create a grid of complex values of size nb_pixels*nb_pixels with real and
     imaginary parts ranging from -window_size to window_size (inclusive).
    Returns a numpy array.

    >>> prepare_grid(1,3)
    array([[-1.-1.j, -1.+0.j, -1.+1.j],
           [ 0.-1.j,  0.+0.j,  0.+1.j],
           [ 1.-1.j,  1.+0.j,  1.+1.j]])
    """
    x = numpy.linspace(-window_size, window_size, nb_pixels)
    x = x.reshape((nb_pixels, 1))
    y = numpy.linspace(-window_size, window_size, nb_pixels)
    y = y.reshape((1, nb_pixels))
    return x + 1.0j * y

def iterate_function(
    eval_function: Callable[[Any, numpy.ndarray], numpy.ndarray],
    function_params: Any,
    nb_iterations: int,
    z_0: numpy.ndarray,
    infinity: float | None = None,
) -> numpy.ndarray:
    """
    Iterate the function "eval_function" exactly nb_iterations times.
    The first argument of the function is a parameter which is contained in
    function_params. The variable z_0 is an array that contains the initial
    values to iterate from.
    This function returns the final iterates.

    >>> iterate_function(eval_quadratic_polynomial, 0, 3, numpy.array([0,1,2])).shape
    (3,)
    >>> numpy.round(iterate_function(eval_quadratic_polynomial,
    ... 0,
    ... 3,
    ... numpy.array([0,1,2]))[0])
    0j
    >>> numpy.round(iterate_function(eval_quadratic_polynomial,
    ... 0,
    ... 3,
    ... numpy.array([0,1,2]))[1])
    (1+0j)
    >>> numpy.round(iterate_function(eval_quadratic_polynomial,
    ... 0,
    ... 3,
    ... numpy.array([0,1,2]))[2])
    (256+0j)
    """

    z_n = z_0.astype("complex64")
    for _ in range(nb_iterations):
        z_n = eval_function(function_params, z_n)
        if infinity is not None:
            numpy.nan_to_num(z_n, copy=False, nan=infinity)
            z_n[abs(z_n) == numpy.inf] = infinity
    return z_n

def show_results(
    function_label: str,
    function_params: Any,
    escape_radius: float,
    z_final: numpy.ndarray,
) -> None:
    """
    Plots of whether the absolute value of z_final is greater than
    the value of escape_radius. Adds the function_label and function_params to
    the title.

    >>> show_results('80', 0, 1, numpy.array([[0,1,.5],[.4,2,1.1],[.2,1,1.3]]))
    """

    abs_z_final = (abs(z_final)).transpose()
    abs_z_final[:, :] = abs_z_final[::-1, :]
    pyplot.matshow(abs_z_final < escape_radius)
    pyplot.title(f"Julia set of ${function_label}$, $c={function_params}$")
    pyplot.show()

def ignore_overflow_warnings() -> None:
    """
    Ignore some overflow and invalid value warnings.

    >>> ignore_overflow_warnings()
    """
    warnings.filterwarnings(
        "ignore", category=RuntimeWarning, message="overflow encountered in multiply"
    )
    warnings.filterwarnings(
        "ignore",
        category=RuntimeWarning,
        message="invalid value encountered in multiply",
    )
    warnings.filterwarnings(
        "ignore", category=RuntimeWarning, message="overflow encountered in absolute"
    )
    warnings.filterwarnings(
        "ignore", category=RuntimeWarning, message="overflow encountered in exp"
    )

if __name__ == "__main__":

    z_0 = prepare_grid(window_size, nb_pixels)

    ignore_overflow_warnings()  # See file header for explanations

    nb_iterations = 24
    escape_radius = 2 * abs(c_cauliflower) + 1
    z_final = iterate_function(
        eval_quadratic_polynomial,
        c_cauliflower,
        nb_iterations,
        z_0,
        infinity=1.1 * escape_radius,
    )
    show_results("z^2+c", c_cauliflower, escape_radius, z_final)

    nb_iterations = 64
    escape_radius = 2 * abs(c_polynomial_1) + 1
    z_final = iterate_function(
        eval_quadratic_polynomial,
        c_polynomial_1,
        nb_iterations,
        z_0,
        infinity=1.1 * escape_radius,
    )
    show_results("z^2+c", c_polynomial_1, escape_radius, z_final)

    nb_iterations = 161
    escape_radius = 2 * abs(c_polynomial_2) + 1
    z_final = iterate_function(
        eval_quadratic_polynomial,
        c_polynomial_2,
        nb_iterations,
        z_0,
        infinity=1.1 * escape_radius,
    )
    show_results("z^2+c", c_polynomial_2, escape_radius, z_final)

    nb_iterations = 12
    escape_radius = 10000.0
    z_final = iterate_function(
        eval_exponential,
        c_exponential,
        nb_iterations,
        z_0 + 2,
        infinity=1.0e10,
    )
    show_results("e^z+c", c_exponential, escape_radius, z_final)


text:
A set of libraries for building Cloud Foundry components, such as service
brokers, on the Java platform.

##Features
* Router registration
* Cloud Controller and UAA Client API (currently focused on "Services" apis)
* Simple Service Gateway registration with Cloud Controller
* Simple support for handling NATS messages.
* Simple Spring Config Integration


text:
The following database related options can only exist in environment or `.env` file. They are not configurable via the system itself.

* **DBHOST**              `Where the DB Runs`
* **DBNAME**              `The Database Name`
* **DBPASS**              `Database user's password in *PLAIN TEXT*`
* **DBUSER**              `The Database Username`
* **DB_BACKEND**          `MyPDO module used (mysqpdo.inc)`

All of these operational configuration options may exist in environment, `.env` file or the configuration table in the database. If present in multiple locations  then Environment trumps `.env` file which trumps the database. Only the database values are configurable via the system itself. The reason for this is to allow for containerized implementations to be able to set values here externally.

* **ADMINACCOUNTS**       `Comma separated list of account IDs that are admins`
* **ADMINEMAIL**          `Email address for admin e-mails, fallback for other email`
* **CONCOMHOURS**         `Volunteer hours awarded to ConCom`
* **CONHOST**             `Name of the hosting organization and thus the web site`
* **CONSITENAME**         `Name of this site in the hosting organization`
* **DISABLEDMODULES**     `Modules disabled for this instance`
* **DUMPSECURE**          `??? Unknown related to deep links`
* **EMAIL_BACKEND**       `Mail module used (mail.inc, null.inc, sendgrid.inc)`
* **FEEDBACK_EMAIL**      `Email address for feedback e-mails`
* **G_CLIENT_SECRET**     `Google drive client secret`
* **G_ROOTFOLDER**        `Google drive client root folder`
* **HELP_EMAIL**          `Help email address`
* **MAXLOGINFAIL**        `Maximum logins failures before account is locked`
* **NEONID**              `Id for Neon CRM`
* **NEONKEY**             `Key for Neon CRM`
* **NEONTRIAL**           `Is this a Neon trial account`
* **NOREPLY_EMAIL**       `Email address for the no-reply email address`
* **PASSWORDEXPIRE**      `Duration between password expiration`
* **PASSWORDRESET**       `How long temporary passwords are valid`
* **SECURITY_EMAIL**      `Email address for security email`
* **SENDGRID_API_KEY**    `API key for sendgrid`
* **SENDGRID_MAIL_FROM**  `Sendgrid configuration`
* **TIMEZONE**            `The timezone for the convention`

There are a few options that appear in the configuration tables that should not be manually set by the administrator and instead there are other facilities that these options control and the settings should be made via those facilities.

* **DBSchemaMD5**     `Value for tracking the Database state`
* **DBSchemaVersion** `Value for tracking the Database upgrades`
* **G_CLIENT_CRED**   `Google drive client credential`
* **NEON_HOOK_NAME**  `Auto-generated name for the Neon Hooks when generated`
* **NEON_HOOK_URL**   `Base url for the presently installed Neon hooks`


text:
from django.contrib import admin

from okr.models import Company, Employee, Period

class CompanyAdmin(admin.ModelAdmin):
    list_display = ('name', 'employee_count')
    def employee_count(self, obj):
        return obj.employee_set.count()
admin.site.register(Company, CompanyAdmin)

class EmployeeAdmin(admin.ModelAdmin):
    list_display = ('name', 'email', 'company')
admin.site.register(Employee, EmployeeAdmin)

class PeriodAdmin(admin.ModelAdmin):
    pass
admin.site.register(Period, PeriodAdmin)


text:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace Plethora.Windows.Forms.Styles
{
    /// <summary>
    /// Style to be applied to a <see cref="Control"/>.
    /// </summary>
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public class ControlStyle
    {
        #region Events

        private static readonly object Changed_EventKey = new object();

        /// <summary>
        /// Raised when any of the values of this <see cref="ControlStyle"/> have changed.
        /// </summary>
        public event EventHandler Changed
        {
            add { this.Events.AddHandler(Changed_EventKey, value); }
            remove { this.Events.RemoveHandler(Changed_EventKey, value); }
        }

        protected virtual void OnChanged(EventArgs e)
        {
            var handler = this.Events[Changed_EventKey] as EventHandler;
            if (handler != null)
                handler(this, e);
        }
        #endregion

        #region Properties

        private EventHandlerList events;
        protected EventHandlerList Events
        {
            get
            {
                if (this.events == null)
                {
                    Interlocked.CompareExchange(ref this.events, new EventHandlerList(), null);
                }
                return this.events;
            }
        }

        #region ForeColor Property

        /// <summary>
        /// Raised when <see cref="ForeColor"/> changes.
        /// </summary>
        /// <seealso cref="ForeColor"/>
        public event EventHandler ForeColorChanged;

        private Color foreColor = Color.Empty;

        /// <summary>
        /// Gets and sets the foreground colour for this style.
        /// </summary>
        [Browsable(true)]
        [Category(ControlAttributes.Category.Appearance)]
        [DefaultValue(typeof(Color), "Empty")]
        [Description("The foreground colour for this style.")]
        public virtual Color ForeColor
        {
            get { return foreColor; }
            set
            {
                if (value == foreColor)
                    return;

                foreColor = value;
                OnForeColorChanged();
            }
        }

        /// <summary>
        /// Raises the <see cref="ForeColorChanged"/> event.
        /// </summary>
        protected void OnForeColorChanged()
        {
            EventHandler handlers = this.ForeColorChanged;
            if (handlers != null)
                handlers(this, EventArgs.Empty);

            OnChanged(EventArgs.Empty);
        }

        #endregion

        #region BackColor Property

        /// <summary>
        /// Raised when <see cref="BackColor"/> changes.
        /// </summary>
        /// <seealso cref="BackColor"/>
        public event EventHandler BackColorChanged;

        private Color backColor = Color.Empty;

        /// <summary>
        /// Gets and sets the foreground colour for this style.
        /// </summary>
        [Browsable(true)]
        [Category(ControlAttributes.Category.Appearance)]
        [DefaultValue(typeof(Color), "Empty")]
        [Description("The foreground colour for this style.")]
        public virtual Color BackColor
        {
            get { return backColor; }
            set
            {
                if (value == backColor)
                    return;

                backColor = value;
                OnBackColorChanged();
            }
        }

        /// <summary>
        /// Raises the <see cref="BackColorChanged"/> event.
        /// </summary>
        protected void OnBackColorChanged()
        {
            EventHandler handlers = this.BackColorChanged;
            if (handlers != null)
                handlers(this, EventArgs.Empty);

            OnChanged(EventArgs.Empty);
        }

        #endregion

        #region FontName Property

        private static readonly object FontNameChanged_EventKey = new object();
        private const string FontName_DefaultValue = null;

        /// <summary>
        /// Raised when the value of <see cref="FontName"/> has changed.
        /// </summary>
        public event EventHandler FontNameChanged
        {
            add { this.Events.AddHandler(FontNameChanged_EventKey, value); }
            remove { this.Events.RemoveHandler(FontNameChanged_EventKey, value); }
        }

        private string fontName = FontName_DefaultValue;

        /// <summary>
        /// Gets and sets the name of the font to applied for this style.
        /// </summary>
        [Browsable(true)]
        [Category(ControlAttributes.Category.Appearance)]
        [DefaultValue(FontName_DefaultValue)]
        [Description("The name of the font to applied for this style.")]
        public virtual string FontName
        {
            get { return fontName; }
            set
            {
                if (value != null)
                {
                    value = value.Trim();
                    if (value.Length == 0)
                        value = null;
                }

                if (this.fontName == value)
                    return;

                this.fontName = value;
                this.OnFontNameChanged(EventArgs.Empty);
            }
        }

        protected virtual void OnFontNameChanged(EventArgs e)
        {
            var handler = this.Events[FontNameChanged_EventKey] as EventHandler;
            if (handler != null)
                handler(this, e);

            OnChanged(EventArgs.Empty);
        }

        #endregion

        #region FontSize Property

        private static readonly object FontSizeChanged_EventKey = new object();

        /// <summary>
        /// Raised when the value of <see cref="FontSize"/> has changed.
        /// </summary>
        public event EventHandler FontSizeChanged
        {
            add { this.Events.AddHandler(FontSizeChanged_EventKey, value); }
            remove { this.Events.RemoveHandler(FontSizeChanged_EventKey, value); }
        }

        private float? fontSize = null;

        /// <summary>
        /// Gets and sets the size of the font to applied for this style.
        /// </summary>
        [Browsable(true)]
        [Category(ControlAttributes.Category.Appearance)]
        [DefaultValue(null)]
        [Description("The size of the font to applied for this style.")]
        public virtual float? FontSize
        {
            get { return fontSize; }
            set
            {
                if (value.HasValue && value.Value <= 0)
                    throw new ArgumentOutOfRangeException(nameof(value), value,
                        ResourceProvider.ArgMustBeGreaterThanZero(nameof(value)));

                if (this.fontSize == value)
                    return;

                this.fontSize = value;
                this.OnFontSizeChanged(EventArgs.Empty);
            }
        }

        protected virtual void OnFontSizeChanged(EventArgs e)
        {
            var handler = this.Events[FontSizeChanged_EventKey] as EventHandler;
            if (handler != null)
                handler(this, e);

            OnChanged(EventArgs.Empty);
        }

        #endregion

        #region FontBold Property

        private static readonly object FontBoldChanged_EventKey = new object();

        /// <summary>
        /// Raised when the value of <see cref="FontBold"/> has changed.
        /// </summary>
        public event EventHandler FontBoldChanged
        {
            add { this.Events.AddHandler(FontBoldChanged_EventKey, value); }
            remove { this.Events.RemoveHandler(FontBoldChanged_EventKey, value); }
        }

        private bool? fontBold = null;

        /// <summary>
        /// Gets and sets a flag indicating whether the font to applied for this style is bold.
        /// </summary>
        [Browsable(true)]
        [Category(ControlAttributes.Category.Appearance)]
        [DefaultValue(null)]
        [Description("A flag indicating whether the font to applied for this style is bold.")]
        public virtual bool? FontBold
        {
            get { return fontBold; }
            set
            {
                if (this.fontBold == value)
                    return;

                this.fontBold = value;
                this.OnFontBoldChanged(EventArgs.Empty);
            }
        }

        protected virtual void OnFontBoldChanged(EventArgs e)
        {
            var handler = this.Events[FontBoldChanged_EventKey] as EventHandler;
            if (handler != null)
                handler(this, e);

            OnChanged(EventArgs.Empty);
        }

        #endregion

        #region FontItalic Property

        private static readonly object FontItalicChanged_EventKey = new object();

        /// <summary>
        /// Raised when the value of <see cref="FontItalic"/> has changed.
        /// </summary>
        public event EventHandler FontItalicChanged
        {
            add { this.Events.AddHandler(FontItalicChanged_EventKey, value); }
            remove { this.Events.RemoveHandler(FontItalicChanged_EventKey, value); }
        }

        private bool? fontItalic = null;

        /// <summary>
        /// Gets and sets a flag indicating whether the font to applied for this style is italic.
        /// </summary>
        [Browsable(true)]
        [Category(ControlAttributes.Category.Appearance)]
        [DefaultValue(null)]
        [Description("A flag indicating whether the font to applied for this style is italic.")]
        public virtual bool? FontItalic
        {
            get { return fontItalic; }
            set
            {
                if (this.fontItalic == value)
                    return;

                this.fontItalic = value;
                this.OnFontItalicChanged(EventArgs.Empty);
            }
        }

        protected virtual void OnFontItalicChanged(EventArgs e)
        {
            var handler = this.Events[FontItalicChanged_EventKey] as EventHandler;
            if (handler != null)
                handler(this, e);

            OnChanged(EventArgs.Empty);
        }

        #endregion

        #region FontUnderline Property

        private static readonly object FontUnderlineChanged_EventKey = new object();

        /// <summary>
        /// Raised when the value of <see cref="FontUnderline"/> has changed.
        /// </summary>
        public event EventHandler FontUnderlineChanged
        {
            add { this.Events.AddHandler(FontUnderlineChanged_EventKey, value); }
            remove { this.Events.RemoveHandler(FontUnderlineChanged_EventKey, value); }
        }

        private bool? fontUnderline = null;

        /// <summary>
        /// Gets and sets a flag indicating whether the font to applied for this style is underlined.
        /// </summary>
        [Browsable(true)]
        [Category(ControlAttributes.Category.Appearance)]
        [DefaultValue(null)]
        [Description("A flag indicating whether the font to applied for this style is underlined.")]
        public virtual bool? FontUnderline
        {
            get { return fontUnderline; }
            set
            {
                if (this.fontUnderline == value)
                    return;

                this.fontUnderline = value;
                this.OnFontUnderlineChanged(EventArgs.Empty);
            }
        }

        protected virtual void OnFontUnderlineChanged(EventArgs e)
        {
            var handler = this.Events[FontUnderlineChanged_EventKey] as EventHandler;
            if (handler != null)
                handler(this, e);

            OnChanged(EventArgs.Empty);
        }

        #endregion

        #region FontStrikeout Property

        private static readonly object FontStrikeoutChanged_EventKey = new object();

        /// <summary>
        /// Raised when the value of <see cref="FontStrikeout"/> has changed.
        /// </summary>
        public event EventHandler FontStrikeoutChanged
        {
            add { this.Events.AddHandler(FontStrikeoutChanged_EventKey, value); }
            remove { this.Events.RemoveHandler(FontStrikeoutChanged_EventKey, value); }
        }

        private bool? fontStrikeout = null;

        /// <summary>
        /// Gets and sets a flag indicating whether the font to applied for this style has a horizontal line through it.
        /// </summary>
        [Browsable(true)]
        [Category(ControlAttributes.Category.Appearance)]
        [DefaultValue(null)]
        [Description("A flag indicating whether the font to applied for this style has a horizontal line through it.")]
        public virtual bool? FontStrikeout
        {
            get { return fontStrikeout; }
            set
            {
                if (this.fontStrikeout == value)
                    return;

                this.fontStrikeout = value;
                this.OnFontStrikeoutChanged(EventArgs.Empty);
            }
        }

        protected virtual void OnFontStrikeoutChanged(EventArgs e)
        {
            var handler = this.Events[FontStrikeoutChanged_EventKey] as EventHandler;
            if (handler != null)
                handler(this, e);

            OnChanged(EventArgs.Empty);
        }

        #endregion
        #endregion

        #region Public Methods

        /// <summary>
        /// Applies this stlye to the text box.
        /// </summary>
        /// <param name="control">
        /// The control to which the style must be applied.
        /// </param>
        public virtual void ApplyStyle(Control control)
        {
            //Validation
            if (control == null)
                throw new ArgumentNullException(nameof(control));

            if (this.ForeColor != Color.Empty)
                control.ForeColor = this.ForeColor;

            if (this.BackColor != Color.Empty)
                control.BackColor = this.BackColor;

            var controlFont = control.Font;
            bool fontChangeRequired = false;

            if (!fontChangeRequired && (this.FontName != null) && (!string.Equals(this.FontName, controlFont.Name)))
                fontChangeRequired = true;

            if (!fontChangeRequired && (this.FontSize != null) && (this.FontSize != controlFont.Size))
                fontChangeRequired = true;

            if (!fontChangeRequired && (this.FontBold != null) && (this.FontBold != controlFont.Bold))
                fontChangeRequired = true;

            if (!fontChangeRequired && (this.FontItalic != null) && (this.FontItalic != controlFont.Italic))
                fontChangeRequired = true;

            if (!fontChangeRequired && (this.FontUnderline != null) && (this.FontUnderline != controlFont.Underline))
                fontChangeRequired = true;

            if (!fontChangeRequired && (this.FontStrikeout != null) && (this.FontStrikeout != controlFont.Strikeout))
                fontChangeRequired = true;

            if (fontChangeRequired)
            {
                FontStyle style = controlFont.Style;
                if (FontBold != null)
                    style = SetFontStyleFlag(style, this.FontBold.Value, FontStyle.Bold);

                if (FontItalic != null)
                    style = SetFontStyleFlag(style, this.FontItalic.Value, FontStyle.Italic);

                if (FontUnderline != null)
                    style = SetFontStyleFlag(style, this.FontUnderline.Value, FontStyle.Underline);

                if (FontStrikeout != null)
                    style = SetFontStyleFlag(style, this.FontStrikeout.Value, FontStyle.Strikeout);

                control.Font = new Font(
                    FontName ?? controlFont.Name,
                    FontSize ?? controlFont.Size,
                    style);
            }
        }

        /// <summary>
        /// Set the default values of all properties from <see cref="control"/>.
        /// </summary>
        /// <param name="control">The control from which to copy property values.</param>
        public virtual void GetPropertyValues(Control control)
        {
            //Validation
            if (control == null)
                throw new ArgumentNullException(nameof(control));

            this.ForeColor = control.ForeColor;
            this.BackColor = control.BackColor;
            this.FontName = control.Font.Name;
            this.FontSize = control.Font.Size;
            this.FontBold = control.Font.Bold;
            this.FontItalic = control.Font.Italic;
            this.FontUnderline = control.Font.Underline;
            this.FontStrikeout = control.Font.Strikeout;
        }

        /// <summary>
        /// Override the unset properties of <see cref="style"/> using this <see cref="ControlStyle"/>
        /// values.
        /// </summary>
        /// <param name="style">
        /// The <see cref="ControlStyle"/> for which the properties are to be overridden.
        /// </param>
        public virtual void OverrideUnsetValues(ControlStyle style)
        {
            //Validation
            if (style == null)
                throw new ArgumentNullException(nameof(style));

            if (style.ForeColor == Color.Empty)
                style.ForeColor = this.ForeColor;

            if (style.BackColor == Color.Empty)
                style.BackColor = this.BackColor;

            if (style.FontName == null)
                style.FontName = this.FontName;

            if (style.FontSize == null)
                style.FontSize = this.FontSize;

            if (style.FontBold == null)
                style.FontBold = this.FontBold;

            if (style.FontItalic == null)
                style.FontItalic = this.FontItalic;

            if (style.FontUnderline == null)
                style.FontUnderline = this.FontUnderline;

            if (style.FontStrikeout == null)
                style.FontStrikeout = this.FontStrikeout;
        }
        #endregion

        #region Static Methods

        private static FontStyle SetFontStyleFlag(FontStyle originalValue, bool flag, FontStyle flagIfTrue)
        {
            if (flag)
                return originalValue | flagIfTrue;
            else
                return originalValue & ~flagIfTrue;
        }

        /// <summary>
        ///  Applies the list of styles to the text box.
        /// </summary>
        /// <param name="control">
        ///  The control to which the styles must be applied.
        /// </param>
        /// <param name="styles">
        ///  The list of styles to be applied to the text box.
        /// </param>
        /// <remarks>
        ///  The styles are applied in decresing preference order through the list.
        /// </remarks>
        public static void ApplyStyles<TStyle>(Control control, params TStyle[] styles)
            where TStyle : ControlStyle, new()
        {
            //Validation
            if (control == null)
                throw new ArgumentNullException(nameof(control));

            var combinedStyle = CombineStyles(styles);
            if (combinedStyle != null)
                combinedStyle.ApplyStyle(control);
        }

        private static TStyle CombineStyles<TStyle>(params TStyle[] styles)
            where TStyle : ControlStyle, new()
        {
            if (styles == null)
                return null;

            TStyle rtnStyle = null;
            foreach (var style in styles)
            {
                if (style == null)
                    continue;

                //Set only on the first non-null style
                if (rtnStyle == null)
                    rtnStyle = new TStyle();

                style.OverrideUnsetValues(rtnStyle);
            }

            return rtnStyle;
        }
        #endregion
    }
}


text:
Some handy scripts that I use

# Set the following environment variable
export TOOLBOX_DIR=somepath/toolbox
export PATH=${TOOLBOX_DIR}:${PATH}


text:
package ch.shaktipat.exwrapper.java.lang;

public class IllegalAccessExceptionWrapper extends RuntimeException
{
	private static final long serialVersionUID = 1L;

	public IllegalAccessExceptionWrapper( IllegalAccessException e )
	{
		super( e );
	}
}


text:
# plan

total number of hours available: __320__ (~2 months), starting September 1, 2014

verify plan with Willem, maybe Adriaan, then notify third parties, notably BALTRAD, of our plans and timeline (check e-mail about Gunter Haase)

1. decide on polarity issue [#41](https://github.com/NLeSC/enram/issues/41)
    * _the C-code still includes lines to deal with polarity scans (these are not used in the current project, although it is foreseen that we will use polarity scans later on). Deleting these lines is necessary from a code quality and maintainability point-of-view._
1.  write unit test for svdfit using all-C code except for the top level
    * _by using all-C code except for the top level, one can avoid having JNI deal with C function pointers._
    * _note that the fitting routine is currently untested (and very difficult to read --a recipe for undetected errors)._
1. collect the data subset that serves as input to svdfit
    * create new class that includes a bunch of RadarScans, together making up a volume scan
        * _most of the work done by vol2bird is relatively simple image processing based on individual scans. The bird density profile, however, is based on multiple scans (a so-called volume scan)._
1. make Java infrastructure that lets you retrieve results so that you can visualize and check them from Matlab.
    * _but dont do any calculation in Matlab, just output the results as a PolarPlot instance, for instance_
1. call the different vol2bird methods and create a bird density profile
1. let Adriaan verify the pipeline
1. read up on BALTRAD
1. the current pipeline uses data from the CZBRD station. Other stations/countries use slightly different formats, even within the ODIM-HDF5 standard. Make code to deal with this
    * see if a class already exists in the BALTRAD tool suite from which my RadarScanJava class can inherit, or implement the full specification of the ODIM scan standard (see [here](https://www.wmo.int/pages/prog/www/OSY/Meetings/ET-SBO_Workshop_Radar_Data_Ex/SBO-WxR_Exchange_3.1.6_NGaussiat.pdf))
1. test if pipeline works for many different circumstances (many different dates and stations).
1. make tools to interact with data and to visualize intermediate results
1. test Java NetCDF library with OpeNDAP over internet
1. install BALTRAD software in VM, see what's what
1. discuss with BALTRAD people how to best go about implementing vol2bird within BALTRAD tool suite (either face to face or online, whatever best suits our needs)
1. embed processing pipeline into BALTRAD suite


text:
title: Fetch List Callout
layout: reference
---

## Description
The Concur Fetch List callout allows clients to import list items from an internal system to Expense when a user is filling out list fields for an expense. The Expense service sends a request for list items to an application connector, created by the client, a third-party developer, or Concur. The connector is hosted by the client or developer, and has access to the list item system of record. The connector uses the list information sent from Expense to search for all matching list items in the system of record. Once the connector has the list items, it sends the data to Expense. The user sees the list items and can select the appropriate item for the expense. When the user saves the expense, the list item is added to the list within Expense.

This callout differs from the inbound Concur web services in the following ways:

* It uses an **outbound** **message** where Expense calls a public facing API endpoint provided by the application connector.
* The third-party developer or client can configure and maintain the public web service interface (the application connector), or the connector can be maintained by Concur. This guide specifies the request and response format required by Concur.
* Concur provides a sample connector application that the developer or client can install on their network and customize to interface with their system of record for list items. Concur can also customize the connector.
* The developer or client can choose to create their own application connector using a different language, such as PHP, if preferred.
* The client Expense administrator must configure a list (most commonly a connected list), and Concur must perform database configuration on the list before this service can be used.

## Works With These Concur Products
* **Expense** for Concur Professional/Premium
* Concur's mobile app

## Product Restrictions
Concur products are highly configurable, and not all clients will have access to all features.

Partner developers must determine which configurations are required for their solution prior to the review process. Use the [Developer Forum][2] if you have questions about the configuration settings.

Existing clients can work with Concur Advantage Technical Services to create custom applications that work with their configuration.

## Fetch List Process Overview
The configuration process has the following steps:

1. Third-party developer, client or Concur downloads, installs, configures, and customizes the application connector.
2. Concur registers the application connector.
3. Expense Admin creates a new list in List Management.
4. Concur configures the list to search for external items.
5. If using a connected list, Expense Admin creates a connected list definition in Forms and Fields.

Once the configuration is complete, the callout uses the following process:

1. The user selects the external source list field while creating an expense entry.
2. Expense sends the list field information and the item codes for the previously selected levels (for connected lists) to the application connector.
3. The application connector queries the list system of record and returns the set of list items to Expense.
4. Expense displays the list items in a drop down list.
5. The user selects the desired list item and saves the expense.

## Security
Concur will make calls to the application connector's endpoint using SSL. During configuration, Concur will connect to the application connector to validate that its hostname and access credentials are valid.

In the code Concur provides for a sample application connector, credentials are stored in a web configuration file that varies by platform, such as web.xml or web.config. However, if you are hosting the connector, you can customize where and how the credentials are stored by customizing HTTPBasicAuth.java or Authentication.cs.

Expense will not be able to connect to the application connector until a certificate signed by a Certificate Authority (CA) is installed in the application connector. You will need to install the signed certificate before Concur can access the connector.

## Authentication
Authentication between Concur and the application connector is performed using HTTP Basic Auth. By default, these credentials are stored in the appropriate web configuration file for your platform, such as web.xml or web.config. These credentials are entered in Concur on the **Register Application Connector** page in **Web Services** under **Administration**.

## Functions
[Post List Search Request][3]

##  Concur Expense Configuration

Expense must have a list field configured to use an external source before this callout can be used. The client creates the list, Concur configures it to use the external source, and the client creates the connected list definition if necessary.

##  Responses and Errors

Refer to the [HTTP Codes][4] page for details of the common responses and errors.

[3]: /api-reference/callouts/post-list-search-request.html
[4]: /tools-support/reference/http-codes.html


text:
package com.jackie.media_preview;

import android.app.Application;

import com.jackie.media_preview.utils.UniversalImageLoaderUtil;

/**
 * Created 9/24/15.
 *
 * @author Jackie
 * @version 1.0
 */
public class App extends Application {
    public static Application instance;
    /**
     * Called when the application is starting, before any activity, service,
     * or receiver objects (excluding content providers) have been created.
     * Implementations should be as quick as possible (for example using
     * lazy initialization of state) since the time spent in this function
     * directly impacts the performance of starting the first activity,
     * service, or receiver in a process.
     * If you override this method, be sure to call super.onCreate().
     */
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        UniversalImageLoaderUtil.initImageLoader(this);
    }
}


text:
package virtualbox

import (
	"bytes"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/coreos/ignition/config"
	"github.com/coreos/ignition/config/types"
	"github.com/coreos/ignition/config/validate/report"
	"github.com/coreos/ignition/internal/distro"
	"github.com/coreos/ignition/internal/providers/util"
	"github.com/coreos/ignition/internal/resource"
)

const (
	partUUID = "99570a8a-f826-4eb0-ba4e-9dd72d55ea13"
)

func FetchConfig(f resource.Fetcher) (types.Config, report.Report, error) {
	f.Logger.Debug("Attempting to read config drive")
	rawConfig, err := ioutil.ReadFile(filepath.Join(distro.DiskByPartUUIDDir(), partUUID))
	if os.IsNotExist(err) {
		f.Logger.Info("Path to ignition config does not exist, assuming no config")
		return types.Config{}, report.Report{}, config.ErrEmpty
	} else if err != nil {
		f.Logger.Err("Error reading ignition config: %v", err)
		return types.Config{}, report.Report{}, err
	}
	trimmedConfig := bytes.TrimRight(rawConfig, "\x00")
	return util.ParseConfig(f.Logger, trimmedConfig)
}


text:
import jpype
import sys
import logging
import time
import common
from jpype.types import *

try:
    import numpy as np
    gotNP = True
except ImportError:
    gotNP = False

def haveNumpy():
    return gotNP

class BufferTestCase(common.JPypeTestCase):
    def setUp(self):
        common.JPypeTestCase.setUp(self)

    def testToMemoryview(self):
        data = [1, 2, 3, 4, 5]
        ja = JArray(JInt)(data)
        m1 = memoryview(ja)

    def testDoubleOpen(self):
        data = [1, 2, 3, 4, 5]
        ja = JArray(JInt)(data)
        m1 = memoryview(ja)
        m2 = memoryview(ja)
        del m1
        del m2

    def testBytesToBytes(self):
        data = [0, 1, 2, 3, 4, 5]
        ja = JArray(JByte)(data)
        self.assertEqual(len(bytes(ja)), 6)

    def testShortToBytes(self):
        data = [0, 1, 2, 3, 4, 5]
        ja = JArray(JShort)(data)
        self.assertEqual(len(bytes(ja)), 6 * 2)

    def testIntToBytes(self):
        data = [0, 1, 2, 3, 4, 5]
        ja = JArray(JInt)(data)
        self.assertEqual(len(bytes(ja)), 6 * 4)

    def testLongToBytes(self):
        data = [0, 1, 2, 3, 4, 5]
        ja = JArray(JLong)(data)
        self.assertEqual(len(bytes(ja)), 6 * 8)

    def testMemoryViewWrite(self):
        data = [1, 2, 3, 4, 5]
        ja = JArray(JInt)(data)
        b = memoryview(ja)  # Create a view
        with self.assertRaises(TypeError):
            b[0] = 123  # Alter the memory using the view

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testSlice(self):
        data = [0, 1, 2, 3, 4, 5]
        ja = JArray(JInt)(data)
        self.assertTrue(bytes(ja[1:3]) == bytes(
            np.array(data[1:3], dtype=np.int32)))
        self.assertTrue(bytes(ja[1:]) == bytes(
            np.array(data[1:], dtype=np.int32)))
        self.assertTrue(bytes(ja[:-1]) ==
                        bytes(np.array(data[:-1], dtype=np.int32)))
        self.assertTrue(bytes(ja[::2]) == bytes(
            np.array(data[::2], dtype=np.int32)))
        self.assertTrue(bytes(ja[::-1]) ==
                        bytes(np.array(data[::-1], dtype=np.int32)))
        self.assertTrue(bytes(ja[::-2]) ==
                        bytes(np.array(data[::-2], dtype=np.int32)))

    def executeConvert(self, jtype, dtype):
        n = 100
        na = np.random.randint(0, 1, size=n).astype(np.bool)
        self.assertTrue(np.all(np.array(jtype(na), dtype=dtype)
                               == np.array(na, dtype=dtype)))
        na = np.random.randint(-2**7, 2**7 - 1, size=n, dtype=np.int8)
        self.assertTrue(np.all(np.array(jtype(na), dtype=dtype)
                               == np.array(na, dtype=dtype)))
        na = np.random.randint(0, 2**8 - 1, size=n, dtype=np.uint8)
        self.assertTrue(np.all(np.array(jtype(na), dtype=dtype)
                               == np.array(na, dtype=dtype)))
        na = np.random.randint(-2**15, 2**15 - 1, size=n, dtype=np.int16)
        self.assertTrue(np.all(np.array(jtype(na), dtype=dtype)
                               == np.array(na, dtype=dtype)))
        na = np.random.randint(0, 2**16 - 1, size=n, dtype=np.uint16)
        self.assertTrue(np.all(np.array(jtype(na), dtype=dtype)
                               == np.array(na, dtype=dtype)))
        na = np.random.randint(-2**31, 2**31 - 1, size=n, dtype=np.int32)
        self.assertTrue(np.all(np.array(jtype(na), dtype=dtype)
                               == np.array(na, dtype=dtype)))
        na = np.random.randint(0, 2**32 - 1, size=n, dtype=np.uint32)
        self.assertTrue(np.all(np.array(jtype(na), dtype=dtype)
                               == np.array(na, dtype=dtype)))
        na = np.random.randint(-2**63, 2**63 - 1, size=n, dtype=np.int64)
        self.assertTrue(np.all(np.array(jtype(na), dtype=dtype)
                               == np.array(na, dtype=dtype)))
        na = np.random.randint(0, 2**64 - 1, size=n, dtype=np.uint64)
        self.assertTrue(np.all(np.array(jtype(na), dtype=dtype)
                               == np.array(na, dtype=dtype)))
        na = np.random.random(n).astype(np.float32)
        self.assertTrue(np.all(np.array(jtype(na), dtype=dtype)
                               == np.array(na, dtype=dtype)))
        na = np.random.random(n).astype(np.float64)
        self.assertTrue(np.all(np.array(jtype(na), dtype=dtype)
                               == np.array(na, dtype=dtype)))

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testBoolConvert(self):
        self.executeConvert(JArray(JBoolean), np.bool)

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testByteConvert(self):
        self.executeConvert(JArray(JByte), np.int8)

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testShortConvert(self):
        self.executeConvert(JArray(JShort), np.int16)

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testIntConvert(self):
        self.executeConvert(JArray(JInt), np.int32)

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testLongConvert(self):
        self.executeConvert(JArray(JLong), np.int64)

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testFloatConvert(self):
        self.executeConvert(JArray(JFloat), np.float32)

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testDoubleConvert(self):
        self.executeConvert(JArray(JDouble), np.float64)

    def executeIntTest(self, jtype, limits, size, dtype, code):
        data = np.random.randint(limits[0], limits[1], size=size, dtype=dtype)
        a = JArray(jtype, data.ndim)(data.tolist())
        u = np.array(a)
        self.assertTrue(np.all(data == u))
        mv = memoryview(a)
        self.assertEqual(mv.format, code)
        self.assertEqual(mv.shape, data.shape)
        self.assertTrue(mv.readonly)

    def executeFloatTest(self, jtype, size, dtype, code):
        data = np.random.rand(*size).astype(dtype)
        a = JArray(jtype, data.ndim)(data)
        u = np.array(a)
        self.assertTrue(np.all(data == u))
        mv = memoryview(a)
        self.assertEqual(mv.format, code)
        self.assertEqual(mv.shape, data.shape)
        self.assertTrue(mv.readonly)

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testBooleanToNP1D(self):
        self.executeIntTest(JBoolean, [0, 1], (100,), np.bool, "?")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testCharToNP1D(self):
        self.executeIntTest(JChar, [0, 2**16], (100,), np.uint16, "H")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testByteToNP1D(self):
        self.executeIntTest(JByte, [-2**7, 2**7 - 1], (100,), np.int8, "b")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testShortToNP1D(self):
        self.executeIntTest(JShort, [-2**15, 2**15 - 1], (100,), np.int16, "h")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testIntToNP1D(self):
        self.executeIntTest(JInt, [-2**31, 2**31 - 1], (100,), np.int32, "i")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testLongToNP1D(self):
        self.executeIntTest(JLong, [-2**63, 2**63 - 1], (100,), np.int64, "q")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testFloatToNP1D(self):
        self.executeFloatTest(JFloat, (100,), np.float32, "f")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testDoubleToNP1D(self):
        self.executeFloatTest(JDouble, (100,), np.float64, "d")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testBooleanToNP2D(self):
        self.executeIntTest(JBoolean, [0, 1], (11, 10), np.bool, "?")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testCharToNP2D(self):
        self.executeIntTest(JChar, [0, 2**16], (11, 10), np.uint16, "H")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testByteToNP2D(self):
        self.executeIntTest(JByte, [-2**7, 2**7 - 1], (11, 10), np.int8, "b")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testShortToNP2D(self):
        self.executeIntTest(JShort, [-2**15, 2**15 - 1], (11, 10), np.int16, "h")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testIntToNP2D(self):
        self.executeIntTest(JInt, [-2**31, 2**31 - 1], (11, 10), np.int32, "i")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testLongToNP2D(self):
        self.executeIntTest(JLong, [-2**63, 2**63 - 1], (11, 10), np.int64, "q")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testFloatToNP2D(self):
        self.executeFloatTest(JFloat, (11, 10), np.float32, "f")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testDoubleToNP2D(self):
        self.executeFloatTest(JDouble, (11, 10), np.float64, "d")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testBooleanToNP3D(self):
        self.executeIntTest(JBoolean, [0, 1], (11, 10, 9), np.bool, "?")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testCharToNP3D(self):
        self.executeIntTest(JChar, [0, 2**16], (11, 10, 9), np.uint16, "H")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testByteToNP3D(self):
        self.executeIntTest(JByte, [-2**7, 2**7 - 1], (11, 10, 9), np.int8, "b")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testShortToNP3D(self):
        self.executeIntTest(JShort, [-2**15, 2**15 - 1],
                            (11, 10, 9), np.int16, "h")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testIntToNP3D(self):
        self.executeIntTest(JInt, [-2**31, 2**31 - 1],
                            (11, 10, 9), np.int32, "i")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testLongToNP3D(self):
        self.executeIntTest(JLong, [-2**63, 2**63 - 1],
                            (11, 10, 9), np.int64, "q")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testFloatToNP3D(self):
        self.executeFloatTest(JFloat, (11, 10, 9), np.float32, "f")

    @common.unittest.skipUnless(haveNumpy(), "numpy not available")
    def testDoubleToNP3D(self):
        self.executeFloatTest(JDouble, (11, 10, 9), np.float64, "d")


text:
export default {
	PAD: "pad",
	REFLECT: "reflect",
	REPEAT: "repeat"
};


text:
package org.elasticsearch.xpack.ccr.index.engine;

import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.seqno.SequenceNumbers;

/**
 * Moved preflight and assertPrimaryIncomingSequenceNumber check to its own class,
 * so that when testing writing directly into a follower index,
 * only these assertions here need to be disabled instead of all assertions in FollowingEngine class.
 */
final class FollowingEngineAssertions {

    static boolean preFlight(final Engine.Operation operation) {
        /*
         * We assert here so that this goes uncaught in unit tests and fails nodes in standalone tests (we want a harsh failure so that we
         * do not have a situation where a shard fails and is recovered elsewhere and a test subsequently passes). We throw an exception so
         * that we also prevent issues in production code.
         */
        assert operation.seqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO;
        assert (operation.origin() == Engine.Operation.Origin.PRIMARY) == (operation.versionType() == VersionType.EXTERNAL) :
            "invalid version_type in a following engine; version_type=" + operation.versionType() + "origin=" + operation.origin();
        return true;
    }

    static boolean assertPrimaryIncomingSequenceNumber(final Engine.Operation.Origin origin, final long seqNo) {
        // sequence number should be set when operation origin is primary
        assert seqNo != SequenceNumbers.UNASSIGNED_SEQ_NO : "primary operations on a following index must have an assigned sequence number";
        return true;
    }

}


text:
package dyvmsapi

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// DoubleCallSeat invokes the dyvmsapi.DoubleCallSeat API synchronously
func (client *Client) DoubleCallSeat(request *DoubleCallSeatRequest) (response *DoubleCallSeatResponse, err error) {
	response = CreateDoubleCallSeatResponse()
	err = client.DoAction(request, response)
	return
}

// DoubleCallSeatWithChan invokes the dyvmsapi.DoubleCallSeat API asynchronously
func (client *Client) DoubleCallSeatWithChan(request *DoubleCallSeatRequest) (<-chan *DoubleCallSeatResponse, <-chan error) {
	responseChan := make(chan *DoubleCallSeatResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.DoubleCallSeat(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// DoubleCallSeatWithCallback invokes the dyvmsapi.DoubleCallSeat API asynchronously
func (client *Client) DoubleCallSeatWithCallback(request *DoubleCallSeatRequest, callback func(response *DoubleCallSeatResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *DoubleCallSeatResponse
		var err error
		defer close(result)
		response, err = client.DoubleCallSeat(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// DoubleCallSeatRequest is the request struct for api DoubleCallSeat
type DoubleCallSeatRequest struct {
	*requests.RpcRequest
	ResourceOwnerId      requests.Integer `position:"Query" name:"ResourceOwnerId"`
	CallerShowNumber     string           `position:"Query" name:"CallerShowNumber"`
	SessionTimeout       requests.Integer `position:"Query" name:"SessionTimeout"`
	CalledNumber         string           `position:"Query" name:"CalledNumber"`
	VoiceCode            string           `position:"Query" name:"VoiceCode"`
	CalledShowNumber     string           `position:"Query" name:"CalledShowNumber"`
	AsrFlag              requests.Boolean `position:"Query" name:"AsrFlag"`
	CallType             string           `position:"Query" name:"CallType"`
	ResourceOwnerAccount string           `position:"Query" name:"ResourceOwnerAccount"`
	RecordFlag           requests.Boolean `position:"Query" name:"RecordFlag"`
	OwnerId              requests.Integer `position:"Query" name:"OwnerId"`
	RecordPoint          requests.Integer `position:"Query" name:"RecordPoint"`
	OutId                string           `position:"Query" name:"OutId"`
	AsrModelId           string           `position:"Query" name:"AsrModelId"`
	CallerNumber         string           `position:"Query" name:"CallerNumber"`
}

// DoubleCallSeatResponse is the response struct for api DoubleCallSeat
type DoubleCallSeatResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
	CallId    string `json:"CallId" xml:"CallId"`
	Code      string `json:"Code" xml:"Code"`
	Message   string `json:"Message" xml:"Message"`
}

// CreateDoubleCallSeatRequest creates a request to invoke DoubleCallSeat API
func CreateDoubleCallSeatRequest() (request *DoubleCallSeatRequest) {
	request = &DoubleCallSeatRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "DoubleCallSeat", "dyvms", "openAPI")
	request.Method = requests.POST
	return
}

// CreateDoubleCallSeatResponse creates a response to parse from DoubleCallSeat response
func CreateDoubleCallSeatResponse() (response *DoubleCallSeatResponse) {
	response = &DoubleCallSeatResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: soc2013/dpl/head/gnu/usr.bin/gdb/kgdb/trgt_sparc64.c 248094 2013-02-17 02:15:19Z marcel $");

#include <sys/types.h>
#include <machine/asm.h>
#include <machine/pcb.h>
#include <machine/frame.h>
#include <err.h>
#include <kvm.h>
#include <string.h>

#include <defs.h>
#include <target.h>
#include <gdbthread.h>
#include <inferior.h>
#include <regcache.h>
#include <frame-unwind.h>
#include <sparc-tdep.h>
#include <sparc64-tdep.h>

#include "kgdb.h"

CORE_ADDR
kgdb_trgt_core_pcb(u_int cpuid)
{
	return (kgdb_trgt_stop_pcb(cpuid, sizeof(struct pcb)));
}

void
kgdb_trgt_fetch_registers(int regno __unused)
{
	struct kthr *kt;
	struct pcb pcb;

	kt = kgdb_thr_lookup_tid(ptid_get_pid(inferior_ptid));
	if (kt == NULL)
		return;
	if (kvm_read(kvm, kt->pcb, &pcb, sizeof(pcb)) != sizeof(pcb)) {
		warnx("kvm_read: %s", kvm_geterr(kvm));
		memset(&pcb, 0, sizeof(pcb));
	}

	supply_register(SPARC_SP_REGNUM, (char *)&pcb.pcb_sp);
	sparc_supply_rwindow(current_regcache, pcb.pcb_sp, -1);
	supply_register(SPARC64_PC_REGNUM, (char *)&pcb.pcb_pc);
	pcb.pcb_pc += 4;
	supply_register(SPARC64_NPC_REGNUM, (char *)&pcb.pcb_pc);
}

void
kgdb_trgt_store_registers(int regno __unused)
{
	fprintf_unfiltered(gdb_stderr, "XXX: %s\n", __func__);
}

void
kgdb_trgt_new_objfile(struct objfile *objfile)
{
}

struct kgdb_frame_cache {
	CORE_ADDR	pc;
	CORE_ADDR	sp;
	CORE_ADDR	fp;
};

static struct kgdb_frame_cache *
kgdb_trgt_frame_cache(struct frame_info *next_frame, void **this_cache)
{
	char buf[MAX_REGISTER_SIZE];
	struct kgdb_frame_cache *cache;

	cache = *this_cache;
	if (cache == NULL) {
		cache = FRAME_OBSTACK_ZALLOC(struct kgdb_frame_cache);
		*this_cache = cache;
		cache->pc = frame_func_unwind(next_frame);
		frame_unwind_register(next_frame, SPARC_SP_REGNUM, buf);
		cache->sp = extract_unsigned_integer(buf,
		    register_size(current_gdbarch, SPARC_SP_REGNUM));
		frame_unwind_register(next_frame, SPARC_FP_REGNUM, buf);
		cache->fp = extract_unsigned_integer(buf,
		    register_size(current_gdbarch, SPARC_FP_REGNUM));
		cache->fp += BIAS - sizeof(struct trapframe);
	}
	return (cache);
}

static void
kgdb_trgt_trapframe_this_id(struct frame_info *next_frame, void **this_cache,
    struct frame_id *this_id)
{
	struct kgdb_frame_cache *cache;

	cache = kgdb_trgt_frame_cache(next_frame, this_cache);
	*this_id = frame_id_build(cache->sp, cache->pc);
}

static void
kgdb_trgt_trapframe_prev_register(struct frame_info *next_frame,
    void **this_cache, int regnum, int *optimizedp, enum lval_type *lvalp,
    CORE_ADDR *addrp, int *realnump, void *valuep)
{
	char dummy_valuep[MAX_REGISTER_SIZE];
	struct kgdb_frame_cache *cache;
	int ofs, regsz;

	regsz = register_size(current_gdbarch, regnum);

	if (valuep == NULL)
		valuep = dummy_valuep;
	memset(valuep, 0, regsz);
	*optimizedp = 0;
	*addrp = 0;
	*lvalp = not_lval;
	*realnump = -1;

	cache = kgdb_trgt_frame_cache(next_frame, this_cache);

	switch (regnum) {
	case SPARC_SP_REGNUM:
		ofs = offsetof(struct trapframe, tf_sp);
		break;
	case SPARC64_PC_REGNUM:
		ofs = offsetof(struct trapframe, tf_tpc);
		break;
	case SPARC64_NPC_REGNUM:
		ofs = offsetof(struct trapframe, tf_tnpc);
		break;
	case SPARC_O0_REGNUM:
	case SPARC_O1_REGNUM:
	case SPARC_O2_REGNUM:
	case SPARC_O3_REGNUM:
	case SPARC_O4_REGNUM:
	case SPARC_O5_REGNUM:
	case SPARC_O7_REGNUM:
		ofs = offsetof(struct trapframe, tf_out) +
		    (regnum - SPARC_O0_REGNUM) * 8;
		break;
	default:
		if (regnum >= SPARC_L0_REGNUM && regnum <= SPARC_I7_REGNUM) {
			ofs = (regnum - SPARC_L0_REGNUM) * 8;
			*addrp = cache->sp + BIAS + ofs;
			*lvalp = lval_memory;
			target_read_memory(*addrp, valuep, regsz);
		}
		return;
	}

	*addrp = cache->fp + ofs;
	*lvalp = lval_memory;
	target_read_memory(*addrp, valuep, regsz);
}

static const struct frame_unwind kgdb_trgt_trapframe_unwind = {
        UNKNOWN_FRAME,
        &kgdb_trgt_trapframe_this_id,
        &kgdb_trgt_trapframe_prev_register
};

const struct frame_unwind *
kgdb_trgt_trapframe_sniffer(struct frame_info *next_frame)
{
	char *pname;
	CORE_ADDR pc;

	pc = frame_func_unwind(next_frame);
	pname = NULL;
	find_pc_partial_function(pc, &pname, NULL, NULL);
	if (pname == NULL)
		return (NULL);
	if (strcmp(pname, "tl0_intr") == 0 ||
	    strcmp(pname, "tl0_trap") == 0 ||
	    strcmp(pname, "tl1_intr") == 0 ||
	    strcmp(pname, "tl1_trap") == 0)
		return (&kgdb_trgt_trapframe_unwind);
	/* printf("%s: %lx =%s\n", __func__, pc, pname); */
	return (NULL);
}


text:
'use strict';

var path          =  require('path')
  , fs            =  require('fs')
  , mutiny        =  require('../')

var argv    =  require('minimist')(
    process.argv.slice(2)
  , { 'boolean': [ 'v' ] }
)

var filter  =  argv.f
  , outdir  =  argv.o && path.resolve(argv.o)
  , rename  =  argv.r && requireModule(argv.r)
  , verbose =  argv.v || argv.verbose
  , root    =  argv._[0] && path.resolve(argv._[0])

if (!outdir)  throw new Error('Need to specify output dir via -o');
if (!root)    throw new Error('Need to specify root dir i.e. ./root');

var transform = [].concat(argv.t).filter(Boolean);

function inspect(obj, depth) {
  console.error(require('util').inspect(obj, false, depth || 5, true));
}

// Example:
// from examples/bin
// mutiny  -t ./local-transform/toUpper.js -t trim-leading -o ../../test/fixtures/mutinied  ../../test/fixtures/root/

if (verbose) inspect({ transform: transform, rename: rename, root: root, outdir: outdir })

mutiny(
      { transform: transform, rename: rename, outdir: outdir }
    , { root: root, fileFilter: filter }
  )
  .on('error', console.error)
  .on('data', function (entry) {
    if (verbose) inspect({ processed: entry });
    else process.stderr.write('.');
  })
  .on('error', console.error)
  .on('end', function () { console.error('\nSuccess: all files processed.') })


text:
using namespace isaac;

Switch::Switch(const int _p, const std::string _n, const std::string _id, const float _pC)
    : Device(_p, _n, _id),
      runTime(0s),
      lastOn(time_point_cast<seconds>(system_clock::now())),
      powerConsumption(std::abs(_pC))
{
	logger->info("Switch <{}> - pin <{}> constructed", getName(), getPowerPin());
}

Switch::Switch(const json _j, const std::string _id) : Switch(_j.at("powerPin"), _j.at("name"), _id)
{
	if (_j.find("description") != _j.end()) {
		setDescription(_j["description"]);
	}

	if (_j.find("powerConsumption") != _j.end()) {
		setPowerConsumption(_j["powerConsumption"]);
	}

	if (_j.find("lastOn") != _j.end()) {
		auto s = _j["lastOn"];
		time_point<system_clock, seconds> tp{ seconds{ s } };
		lastOn = tp;
	}
}

void Switch::setPowerConsumption(float _p) { powerConsumption = std::abs(_p); }

void Switch::on()
{
	std::lock_guard<std::mutex> lock(m_lastOn);
	lastOn = time_point_cast<seconds>(system_clock::now());
	Device::on();
}

void Switch::off()
{
	if (!isOn()) {
		return;
	}
	std::lock_guard<std::mutex> lock(m_runTime);
	auto now = duration_cast<seconds>(system_clock::now().time_since_epoch());
	runTime += now - lastOn.time_since_epoch();
	Device::off();
}

json Switch::dumpInfo() const
{
	auto j                = Device::dumpInfo();
	j["lastOn"]           = duration_cast<milliseconds>(lastOn.time_since_epoch()).count();
	j["powerConsumption"] = powerConsumption;
	j["runTime"]          = getRunTime();
	j["type"]             = dToInt(deviceType::Switch);
	return j;
}


text:
package com.example.scheduler.persistence.repository;

import com.example.scheduler.persistence.entity.ConfigurationParameter;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.util.Set;

public interface ConfigurationParameterRepository extends JpaRepository<ConfigurationParameter, Long> {

    List<ConfigurationParameter> findByNameIn(Set<String> names);

    ConfigurationParameter findByName(String name);

}


text:
import time

time.sleep(100000)


text:
Returns a logger extension that logs events generated by ReduxGTM.

```js
import { createStore, applyMiddleware } from 'redux';
import { createMiddleware, Extensions} from 'redux-gtm';

import reducer from './reducer';

const eventDefinitionsMap = {
   'SOME_REDUX_ACTION': { eventName: 'some-gtm-event' },
};

const logger = Extensions.logger();
const middleware = createMiddleware(eventDefinitionsMap, { logger });
const store = createStore(reducer, applyMiddleware(middleware));
```


text:
#ifndef HIGHLEVEL_FEATURE_EXTRACTOR_H
#define HIGHLEVEL_FEATURE_EXTRACTOR_H

#include <rcsc/player/player_agent.h>
#include "feature_extractor.h"
#include <vector>

/**
 * This feature extractor creates the high level feature set used by
 * Barrett et al.
 * (http://www.cs.utexas.edu/~sbarrett/publications/details-THESIS14-Barrett.html)
 * pages 159-160.
 */
class HighLevelFeatureExtractor : public FeatureExtractor {
public:
  HighLevelFeatureExtractor(int num_teammates, int num_opponents,
                            bool playing_offense);
  virtual ~HighLevelFeatureExtractor();

  // Updated the state features stored in feature_vec
  virtual const std::vector<float>& ExtractFeatures(const rcsc::WorldModel& wm);

protected:
  // Number of features for non-player objects.
  const static int num_basic_features = 9;
  // Number of features for each player or opponent in game.
  const static int features_per_teammate = 5;
};

#endif // HIGHLEVEL_FEATURE_EXTRACTOR_H


text:
package com.gerken.xaa.mpe.editor;

import java.util.ArrayList;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.events.IHyperlinkListener;
import org.w3c.dom.Node;

import com.gerken.xaa.mpe.constraint.ConstraintFailure;
import com.gerken.xaa.mpe.constraint.IConstraintListener;
import com.gerken.xaa.mpe.core.AbstractFormPage;
import com.gerken.xaa.mpe.core.AbstractToolSection;

public class ProblemSection extends AbstractToolSection implements IConstraintListener, IHyperlinkListener {

	private ArrayList<ConstraintFailure> problems;

	public ProblemSection(AbstractFormPage page, Composite parent) {
		super(page, parent);
		page.getMpeEditor().getConstraintManager().addConstraintListener(this);
	}

	public String getTextContent() {

		StringBuffer sb = new StringBuffer();

		problems = getPage().getMpeEditor().getConstraintManager().getCurrentProblems();
		sb.append("<form>");

		for (int i = 0; i < problems.size(); i++) {

				// write the indentation and bullet
			sb.append("
");

				// write the link tag
			sb.append("");

				// write the linked text
			sb.append(problems.get(i).getPageName());

				// write the close link tag
			sb.append("");

			sb.append(" page ");

			sb.append(": "+problems.get(i).getMessage()+"");

				// end the line item
			sb.append("
");

		}
		sb.append("</form>");

		return sb.toString();
	}

	public String getColorKey(ConstraintFailure problem) {
		if (problem.getSeverity() == ConstraintFailure.SEVERITY_ERROR) {
			return getRedKey();
		} else if (problem.getSeverity() == ConstraintFailure.SEVERITY_WARNING) {
			return getYellowKey();
		}
		return getBlueKey();
	}

	public void linkActivated(HyperlinkEvent e) {
		String href = e.getHref().toString();

		int i = Integer.parseInt(href);
		((AbstractFormPage)getPage().getMpeEditor().setActivePage(problems.get(i).getPageID())).setSelection(problems.get(i).getTarget());

	}

	public void linkEntered(HyperlinkEvent e) {}

	public void linkExited(HyperlinkEvent e) {}

	protected boolean isPrimary() {
		return true;
	}

	public String getText() {
		return "Model Errors";
	}

	public String getDescription() {
		return "The following errors were detected";
	}

	public boolean isSectionExpanded() {
		return true;
	}

	public void constraintsChecked(ArrayList<ConstraintFailure> problems) {
		if (getTextWidget() == null) { return; }
		try { getTextWidget().setText(getTextContent(), true, false); }
		catch (Exception e) { getTextWidget().setText("", false, false); } //$NON-NLS-1$
		getSection().getParent().getParent().layout(true);
	}

	@Override
	public void loadFrom(Node source) {
		getPage().getMpeEditor().modelChanged();

		super.loadFrom(source);
	}

}


text:
require 'spec_helper'

describe HashModel do

  context "when flattening" do

    it "should set the first field given as the default flatten index" do
      @hm << {:switch => ["-x", "--xtended"], :description => "Xish stuff"}
      @hm.add(:description => "blah,blah,blah")
      @hm.flatten_index.should == :switch
    end

    it "should set the flatten index properly if specified using parameter :flatten_index" do
      @hm = HashModel.new(:raw_data=>@records, :flatten_index=>:parameter)
      @hm.should == [
        {:parameter=>{:type=>String}, :switch=>["-x", "--xtended"], :description=>"Xish stuff", :_id=>0, :_group_id=>0},
        {:parameter=>{:required=>true}, :switch=>["-x", "--xtended"], :description=>"Xish stuff", :_id=>1, :_group_id=>0},
        {:parameter=>nil, :switch=>["-y", "--why"], :description=>"lucky what?", :_id=>2, :_group_id=>1},
        {:parameter=>{:type=>String}, :switch=>"-z", :description=>"zee svitch zu moost calz", :_id=>3, :_group_id=>2}
      ]

    end

    it "should allow you to change the flatten index" do
      @hm << {:switch => ["-x", "--xtended"], :description => "Xish stuff"}
      proc do
        @hm.flatten_index = :description
      end.should change(@hm, :flatten_index).from(:switch).to(:description)
    end

    it "should throw an error if an invalid flatten index is given" do
        @records = [
          { :switch => [ [5, 6], [1, :blah=>2] ] }
        ]
        @hm = HashModel.new(:raw_data=>@records)
        proc {@hm.flatten_index = :switch__blah}.should raise_error(ArgumentError)
    end

    it "shouldn't throw an error if a valid flatten index is given" do
      proc {@hm.flatten_index = :parameter__type}.should_not raise_error
    end

    it "should reset the flatten index if an invalid flatten index is given" do
        @records = [
          { :switch => [ [5, 6], [1, :blah=>2] ] }
        ]
        @hm = HashModel.new(:raw_data=>@records)
        proc {@hm.flatten_index = :switch__blah}.should raise_error(ArgumentError)
        @hm.flatten_index.should == :switch
    end

    it "should set the flatten index when adding to an empty HashModel" do
      @hm.flatten_index.should == :switch
    end

    it "should assign the flattened data to self correctly when adding records using <<" do
      @hm = HashModel.new
      @hm << @records[0]
      @hm << @records[1]
      @hm << @records[2]
      @hm.should == @flat_records
    end

    it "should assign the flattened data to self correctly when adding with :raw_data=>records" do
      @hm.should == @flat_records
    end

    it "should add a nil value for the field index for records that don't have a field with the field index" do
      @hm = HashModel.new
      @hm << @records[0]
      @hm << {:foo=>"bar"}
      @hm.last.should == {:switch=>nil, :foo=>"bar", :_id=>2, :_group_id=>1}
    end

    it "should change the flattened data when changing the flatten index" do
      @hm = HashModel.new(:raw_data=>@records)
      @hm.flatten_index = :parameter__type
      @hm.should == [
        {:parameter__type=>String, :switch=>["-x", "--xtended"], :parameter__required=>true, :description=>"Xish stuff", :_id=>0, :_group_id=>0},
        {:parameter__type=>nil, :switch=>["-y", "--why"], :description=>"lucky what?", :_id=>1, :_group_id=>1},
        {:parameter__type=>String, :switch=>"-z", :description=>"zee svitch zu moost calz", :_id=>2, :_group_id=>2}
      ]
    end

    it "should update the flattened data if the raw data is changed" do
      @hm.raw_data = @records2.clone
      @hm.should == @flat_records2
    end

  end # flattening behvior

end


text: int testLibPerConfigDest(void) { return 0; }


text:
package com.github.sbouclier.result;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;

import java.io.IOException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;

/**
 * OpenPositionsResult test
 *
 * @author Stéphane Bouclier
 */
public class OpenPositionsResultTest {

    @Test
    public void should_return_to_string() throws IOException {

        // Given
        final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/open_positions.mock.json");
        OpenPositionsResult mockResult = new ObjectMapper().readValue(jsonResult, OpenPositionsResult.class);

        // When
        final String toString = mockResult.toString();

        // Then
        assertThat(toString, startsWith("OpenPositionsResult"));
    }
}


text:
use crate::database::Database;
use crate::image::Image;
use crate::stats::ScopedDuration;
use crate::vec::*;
use crate::view::View;
use crate::Stopwatch;
use crate::TileRef;
use crate::R;
use crate::{Metadata, MetadataState};
use piston_window::{
    color, rectangle, DrawState, G2d, G2dTexture, G2dTextureContext, Texture, TextureSettings,
    Transformed,
};
use std::cmp::Ordering;
use std::collections::{BTreeMap, VecDeque};

#[derive(Debug)]
pub struct Group {
    pub extents: [Vector2<u32>; 2],
    pub tiles: BTreeMap<TileRef, G2dTexture>,
    pub images: BTreeMap<Vector2<u32>, Image>,
    pub cache_todo: [VecDeque<Vector2<u32>>; 2],
    pub thumb_todo: [VecDeque<Vector2<u32>>; 2],
}

impl Group {
    pub fn new(extents: [Vector2<u32>; 2]) -> Self {
        Self {
            extents,
            tiles: BTreeMap::new(),
            images: BTreeMap::new(),
            cache_todo: [VecDeque::new(), VecDeque::new()],
            thumb_todo: [VecDeque::new(), VecDeque::new()],
        }
    }

    pub fn insert(&mut self, coords: Vector2<u32>, image: Image) {
        self.images.insert(coords, image);
    }

    pub fn reset(&mut self) {
        for image in self.images.values_mut() {
            image.reset();
        }
        self.tiles.clear();

        for queue in &mut self.cache_todo {
            queue.clear();
        }

        for queue in &mut self.thumb_todo {
            queue.clear();
        }
    }

    pub fn recheck(&mut self, view: &View) {
        for queue in &mut self.thumb_todo {
            queue.clear();
        }

        for queue in &mut self.cache_todo {
            queue.clear();
        }

        let mut mouse_dist: Vec<(&Vector2<u32>, &Image)> = Vec::with_capacity(self.images.len());
        mouse_dist.extend(self.images.iter());
        mouse_dist.sort_by_key(|(&coords, _)| vec2_square_len(view.mouse_dist(coords)) as isize);

        for (&coords, image) in &mouse_dist {
            let p = !view.is_visible(view.trans(coords)) as usize;

            match image.metadata {
                MetadataState::Some(_) => {
                    self.cache_todo[p].push_back(coords);
                }
                MetadataState::Missing => {
                    self.thumb_todo[p].push_back(coords);
                }
                MetadataState::Errored => continue,
            }
        }
    }

    pub fn load_cache(
        &mut self,
        p: usize,
        view: &View,
        db: &Database,
        texture_context: &mut G2dTextureContext,
        stopwatch: &Stopwatch,
    ) -> bool {
        let _s3 = ScopedDuration::new("Group::load_cache");

        let target_size = view.target_size();

        let texture_settings = TextureSettings::new();

        while let Some(coords) = self.cache_todo[p].pop_front() {
            let image = self.images.get_mut(&coords).unwrap();

            let metadata = image.get_metadata().expect("Image::get_metadata");

            let view_coords = view.trans(coords);

            let shift = if p == 0 {
                0
            } else {
                let ratio = view.visible_ratio(view_coords);
                f64::max(0.0, ratio - 1.0).floor() as usize
            };

            let new_size = metadata.nearest(target_size >> shift);

            let current_size = image.size.unwrap_or(0);

            // Progressive resizing.
            let new_size = match new_size.cmp(&current_size) {
                Ordering::Less => current_size - 1,
                Ordering::Equal => {
                    // Already loaded target size.
                    continue;
                }
                Ordering::Greater => current_size + 1,
            };

            // Load new tiles.
            for tile_ref in &metadata.thumbs[new_size].tile_refs {
                // Already loaded.
                if self.tiles.contains_key(tile_ref) {
                    continue;
                }

                if stopwatch.done() {
                    self.cache_todo[p].push_front(coords);
                    return false;
                }

                let data = db.get(*tile_ref).expect("db get").expect("missing tile");

                let image = ::image::load_from_memory(&data).expect("load image");

                // TODO: Would be great to move off thread.
                let image =
                    Texture::from_image(texture_context, &image.to_rgba8(), &texture_settings)
                        .expect("texture");

                self.tiles.insert(*tile_ref, image);
            }

            // Unload old tiles.
            for (j, thumb) in metadata.thumbs.iter().enumerate() {
                if j == new_size {
                    continue;
                }
                for tile_ref in &thumb.tile_refs {
                    self.tiles.remove(tile_ref);
                }
            }

            image.size = Some(new_size);
            self.cache_todo[p].push_back(coords);
        }

        true
    }

    pub fn make_thumbs(&mut self, p: usize, thumbnailer: &mut crate::Thumbnailer) -> bool {
        loop {
            if thumbnailer.is_full() {
                return false;
            }

            if let Some(coords) = self.thumb_todo[p].pop_front() {
                let image = self.images.get(&coords).unwrap();
                if !thumbnailer.make_thumbs(image) {
                    return false;
                }
            } else {
                break true;
            }
        }
    }

    pub fn update_metadata(&mut self, coords: Vector2<u32>, metadata_res: R<Metadata>) {
        let image = self.images.get_mut(&coords).unwrap();
        image.metadata = match metadata_res {
            Ok(metadata) => {
                self.cache_todo[0].push_front(coords);
                MetadataState::Some(metadata)
            }
            Err(e) => {
                error!("make_thumb: {}", e);
                MetadataState::Errored
            }
        };
    }

    pub fn draw(&self, trans: [[f64; 3]; 2], view: &View, draw_state: &DrawState, g: &mut G2d) {
        //{
        //    let [min, max] = self.extents;
        //    let op_color = color::hex("FF0000");
        //    let [x, y] = view.trans(min);
        //    let [w, h] = vec2_scale(vec2_f64(vec2_sub(max, min)), view.zoom);
        //    let trans = trans.trans(x, y);
        //    rectangle(op_color, [0.0, 0.0, w, 1.0], trans, g);
        //    rectangle(op_color, [0.0, 0.0, 1.0, h], trans, g);
        //    rectangle(op_color, [w, 0.0, 1.0, h], trans, g);
        //    rectangle(op_color, [0.0, h, w, 1.0], trans, g);
        //}

        let dot_color = color::hex("444444");
        let mid_zoom = view.zoom * 0.5;

        for (&coords, image) in &self.images {
            let coords = view.trans(coords);

            if !view.is_visible(coords) {
                continue;
            }

            let trans = trans.trans(coords[0], coords[1]);

            if image.draw(trans, view, &self.tiles, draw_state, g) {
                continue;
            } else {
                rectangle(dot_color, [mid_zoom, mid_zoom, 1.0, 1.0], trans, g);
            }
        }
    }

    pub fn mouse_dist(&self, view: &View) -> usize {
        let midpoint = vec2_div(vec2_add(self.extents[0], self.extents[1]), [2, 2]);
        let mouse_dist = view.mouse_dist(midpoint);
        vec2_square_len(mouse_dist) as usize
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.luaj</groupId>
		<artifactId>luaj-parent</artifactId>
		<version>3.0-SNAPSHOT</version>
	</parent>

	<groupId>li.cil.repack.org.luaj</groupId>
	<artifactId>oc-luaj</artifactId>

	<name>oc-luaj</name>
	<description>LuaJ for OpenComputers</description>

	<dependencies>
		<dependency>
			<groupId>org.luaj</groupId>
			<artifactId>luaj-core</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>org.luaj</groupId>
			<artifactId>luaj-jse</artifactId>
			<version>${project.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>3.3.0</version>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<minimizeJar>false</minimizeJar>
					<artifactSet>
						<includes>
							<include>org.luaj:luaj-core</include>
							<include>org.luaj:luaj-jse</include>
						</includes>
					</artifactSet>
					<relocations>
						<relocation>
							<pattern>org.luaj</pattern>
							<shadedPattern>li.cil.repack.org.luaj</shadedPattern>
						</relocation>
					</relocations>
					<filters>
						<filter>
							<artifact>*:*</artifact>
							<excludes>
								<exclude>*.class</exclude>
								<exclude>li/cil/repack/org/luaj/vm2/luajc/**</exclude>
								<exclude>li/cil/repack/org/luaj/vm2/script/**</exclude>
								<exclude>org/luaj/vm2/luajc/**</exclude>
								<exclude>org/luaj/vm2/script/**</exclude>
							</excludes>
						</filter>
					</filters>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
GIT_VERSION=`git rev-parse --short HEAD`

rm -rf vendor composer.lock
composer install --no-dev
printf "<?php\nrequire __DIR__ . '/vendor/autoload.php';\n?>" > sendgrid-php.php
cd ..
zip -r sendgrid-php.zip sendgrid-php -x \*.git\* \*composer.json\* \*scripts\* \*test\* \*.travis.yml\* \*prism\*

exit 0


text:
\SetAPI{J-C}
\section{cache.cascadeload.toone}
\label{configuration:CacheCascadeloadToone}
\ClearAPI
\TODO
%% GENERATED USAGE REFERENCE - DO NOT EDIT
%% GENERATED USAGE REFERENCE END
\type{com.koch.ambeth.config.ServiceConfigurationConstants.ToOneDefaultCascadeLoadMode}
\begin{lstlisting}[style=Props,caption={Usage example for \textit{cache.cascadeload.toone}}]
cache.cascadeload.toone=
\end{lstlisting}