text:
/*
 * FileHandlerTest.java
 * JUnit based test
 *
 * Created on April 4, 2007, 7:48 PM
 */

package coreedit;

import junit.framework.*;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 *
 * @author alex
 */
public class FileHandlerTest extends TestCase
{

    File testfile;

    public FileHandlerTest(String testName)
    {
	super(testName);
    }

	protected void setUp() throws Exception
	{
	    //TODO : create here set of tests files
	    try
	    {
		testfile = File.createTempFile("FileHandler","test");
	    }
	    catch (IOException ex)
	    {
		StringBuilder errorStr = new StringBuilder();
		errorStr.append("IO Exception raised in setUp : ");
		errorStr.append("TmpDir = ");
		errorStr.append( System.getProperty("java.io.tmpdir"));
		errorStr.append(" ");
		errorStr.append(ex.getMessage());

		fail(errorStr.toString());
	    }

	    FileWriter fw = new FileWriter(testfile);
	    fw.write("test");
	    fw.close();
	}

	protected void tearDown() throws Exception
	{
	    //TODO : delete here the set of test files
	    testfile.delete();
	}

	/**
	 * Test of getInputStream method, of class coreedit.FileHandler.
	 */
	public void testGetInputStream()
	{
		System.out.println("getInputStream");

		try
		{
		    FileHandler instance = new FileHandler(testfile);

		    byte[] expResult = {'t','e','s','t'};
		    FileInputStream resultstream = instance.getInputStream();
		    assertEquals(4,resultstream.available());

		    byte[] btable = new byte[expResult.length];
		    assertEquals(4,resultstream.read(btable));

		    for (int i=0; i<expResult.length; i++)
		    {
			assertEquals(expResult[i],btable[i]);
		    }
		}
		catch (FileNotFoundException ex)
		{
		    fail("FileNotFound Exception raised.");
		}
		catch (IOException ex)
		{
		    fail("IO Exception raised.");
		}
	}

	/**
	 * Test of getReader method, of class coreedit.FileHandler.
	 */
	public void testGetReader()
	{
		System.out.println("getReader");
		try
		{
		    FileHandler instance = new FileHandler(testfile);

		    char[] expResult = {'t','e','s','t'};
		    InputStreamReader result = instance.getReader();
		    assertEquals(true,result.ready());

		    char[] ctable = new char[expResult.length];
		    assertEquals(4,result.read(ctable) );

		    for (int i=0; i<expResult.length; i++)
		    {
			assertEquals(expResult[i],ctable[i]);
		    }
		}
		catch (FileNotFoundException ex)
		{
		    fail("FileNotFound Exception raised.");
		}
		catch (IOException ex)
		{
		    fail("IO Exception raised.");
		}
	}

	/**
	 * Test of getOutputStream method, of class coreedit.FileHandler.
	 */
	public void testGetOutputStream()
	{
		System.out.println("getOutputStream");

		try
		{
		    FileHandler instance = new FileHandler(testfile);
		    FileOutputStream result = instance.getOutputStream();

		    byte[] outtxt = {'i','n','g'};
		    result.write(outtxt);
		    result.close();

		    byte[] expResult = {'t','e','s','t','i','n','g'};
		    FileInputStream resultstream = instance.getInputStream();
		    assertEquals(7,resultstream.available());

		    byte[] btable = new byte[expResult.length];
		    assertEquals(7,resultstream.read(btable));

		    for (int i=0; i<expResult.length; i++)
		    {
			assertEquals(expResult[i],btable[i]);
		    }
		}
		catch (FileNotFoundException ex)
		{
		    fail("FileNotFound Exception raised.");
		}
		catch (IOException ex)
		{
		    fail("IO Exception raised.");
		}

	}

	/**
	 * Test of getWriter method, of class coreedit.FileHandler.
	 */
	public void testGetWriter()
	{
		System.out.println("getWriter");

		try
		{
		    FileHandler instance = new FileHandler(testfile);
		    OutputStreamWriter resultwriter = instance.getWriter();

		    char[] outtxt = {'i','n','g'};
		    resultwriter.write(outtxt);
		    resultwriter.close();

		    char[] expResult = {'t','e','s','t','i','n','g'};
		    InputStreamReader result = instance.getReader();
		    assertEquals(true,result.ready());

		    char[] ctable = new char[expResult.length];
		    assertEquals(7,result.read(ctable) );

		    for (int i=0; i<expResult.length; i++)
		    {
			assertEquals(expResult[i],ctable[i]);
		    }
		}
		catch (FileNotFoundException ex)
		{
		    fail("FileNotFound Exception raised.");
		}
		catch (IOException ex)
		{
		    fail("IO Exception raised.");
		}
	}

}


text:
require "devops-client/handler/handler"
require "devops-client/options/network_options"
require "json"
require "devops-client/output/network"

class Network < Handler

  include Output::Network

  def initialize(host, def_options={})
    self.host = host
    self.options = def_options
    @options_parser = NetworkOptions.new(ARGV, def_options)
  end

  def handle
    case ARGV[1]
    when "list"
      self.options = @options_parser.list_options
      list_handler @options_parser.args
      output
    else
      @options_parser.invalid_command
    end
  end

  def list_handler args
    r = inspect_parameters @options_parser.list_params, args[2]
    unless r.nil?
      @options_parser.invalid_list_command
      abort(r)
    end
    @provider = args[2]
    @list = get("/networks/#{args[2]}").sort!{|x,y| x["name"] <=> y["name"]}
  end

end

redpajama_set_name: RedPajamaGithub


text:
#include <stdlib.h>
#include <string.h>

#include <openssl/conf.h>
#include <openssl/ct.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/safestack.h>

#include "internal/cryptlib.h"

/*
 * Information about a CT log server.
 */
struct ctlog_st {
    OSSL_LIB_CTX *libctx;
    char *propq;
    char *name;
    uint8_t log_id[CT_V1_HASHLEN];
    EVP_PKEY *public_key;
};

/*
 * A store for multiple CTLOG instances.
 * It takes ownership of any CTLOG instances added to it.
 */
struct ctlog_store_st {
    OSSL_LIB_CTX *libctx;
    char *propq;
    STACK_OF(CTLOG) *logs;
};

/* The context when loading a CT log list from a CONF file. */
typedef struct ctlog_store_load_ctx_st {
    CTLOG_STORE *log_store;
    CONF *conf;
    size_t invalid_log_entries;
} CTLOG_STORE_LOAD_CTX;

/*
 * Creates an empty context for loading a CT log store.
 * It should be populated before use.
 */
static CTLOG_STORE_LOAD_CTX *ctlog_store_load_ctx_new(void);

/*
 * Deletes a CT log store load context.
 * Does not delete any of the fields.
 */
static void ctlog_store_load_ctx_free(CTLOG_STORE_LOAD_CTX* ctx);

static CTLOG_STORE_LOAD_CTX *ctlog_store_load_ctx_new(void)
{
    CTLOG_STORE_LOAD_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));

    if (ctx == NULL)
        ERR_raise(ERR_LIB_CT, ERR_R_MALLOC_FAILURE);

    return ctx;
}

static void ctlog_store_load_ctx_free(CTLOG_STORE_LOAD_CTX* ctx)
{
    OPENSSL_free(ctx);
}

/* Converts a log's public key into a SHA256 log ID */
static int ct_v1_log_id_from_pkey(CTLOG *log, EVP_PKEY *pkey)
{
    int ret = 0;
    unsigned char *pkey_der = NULL;
    int pkey_der_len = i2d_PUBKEY(pkey, &pkey_der);
    unsigned int len;
    EVP_MD *sha256 = NULL;

    if (pkey_der_len <= 0) {
        ERR_raise(ERR_LIB_CT, CT_R_LOG_KEY_INVALID);
        goto err;
    }
    sha256 = EVP_MD_fetch(log->libctx, "SHA2-256", log->propq);
    if (sha256 == NULL) {
        ERR_raise(ERR_LIB_CT, ERR_R_EVP_LIB);
        goto err;
    }

    ret = EVP_Digest(pkey_der, pkey_der_len, log->log_id, &len, sha256,
                     NULL);
err:
    EVP_MD_free(sha256);
    OPENSSL_free(pkey_der);
    return ret;
}

CTLOG_STORE *CTLOG_STORE_new_ex(OSSL_LIB_CTX *libctx, const char *propq)
{
    CTLOG_STORE *ret = OPENSSL_zalloc(sizeof(*ret));

    if (ret == NULL) {
        ERR_raise(ERR_LIB_CT, ERR_R_MALLOC_FAILURE);
        return NULL;
    }

    ret->libctx = libctx;
    if (propq != NULL) {
        ret->propq = OPENSSL_strdup(propq);
        if (ret->propq == NULL) {
            ERR_raise(ERR_LIB_CT, ERR_R_MALLOC_FAILURE);
            goto err;
        }
    }

    ret->logs = sk_CTLOG_new_null();
    if (ret->logs == NULL) {
        ERR_raise(ERR_LIB_CT, ERR_R_MALLOC_FAILURE);
        goto err;
    }

    return ret;
err:
    CTLOG_STORE_free(ret);
    return NULL;
}

CTLOG_STORE *CTLOG_STORE_new(void)
{
    return CTLOG_STORE_new_ex(NULL, NULL);
}

void CTLOG_STORE_free(CTLOG_STORE *store)
{
    if (store != NULL) {
        OPENSSL_free(store->propq);
        sk_CTLOG_pop_free(store->logs, CTLOG_free);
        OPENSSL_free(store);
    }
}

static int ctlog_new_from_conf(CTLOG_STORE *store, CTLOG **ct_log,
                               const CONF *conf, const char *section)
{
    const char *description = NCONF_get_string(conf, section, "description");
    char *pkey_base64;

    if (description == NULL) {
        ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_MISSING_DESCRIPTION);
        return 0;
    }

    pkey_base64 = NCONF_get_string(conf, section, "key");
    if (pkey_base64 == NULL) {
        ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_MISSING_KEY);
        return 0;
    }

    return CTLOG_new_from_base64_ex(ct_log, pkey_base64, description,
                                    store->libctx, store->propq);
}

int CTLOG_STORE_load_default_file(CTLOG_STORE *store)
{
    const char *fpath = ossl_safe_getenv(CTLOG_FILE_EVP);

    if (fpath == NULL)
      fpath = CTLOG_FILE;

    return CTLOG_STORE_load_file(store, fpath);
}

/*
 * Called by CONF_parse_list, which stops if this returns <= 0,
 * Otherwise, one bad log entry would stop loading of any of
 * the following log entries.
 * It may stop parsing and returns -1 on any internal (malloc) error.
 */
static int ctlog_store_load_log(const char *log_name, int log_name_len,
                                void *arg)
{
    CTLOG_STORE_LOAD_CTX *load_ctx = arg;
    CTLOG *ct_log = NULL;
    /* log_name may not be null-terminated, so fix that before using it */
    char *tmp;
    int ret = 0;

    /* log_name will be NULL for empty list entries */
    if (log_name == NULL)
        return 1;

    tmp = OPENSSL_strndup(log_name, log_name_len);
    if (tmp == NULL)
        goto mem_err;

    ret = ctlog_new_from_conf(load_ctx->log_store, &ct_log, load_ctx->conf, tmp);
    OPENSSL_free(tmp);

    if (ret < 0) {
        /* Propagate any internal error */
        return ret;
    }
    if (ret == 0) {
        /* If we can't load this log, record that fact and skip it */
        ++load_ctx->invalid_log_entries;
        return 1;
    }

    if (!sk_CTLOG_push(load_ctx->log_store->logs, ct_log)) {
        goto mem_err;
    }
    return 1;

mem_err:
    CTLOG_free(ct_log);
    ERR_raise(ERR_LIB_CT, ERR_R_MALLOC_FAILURE);
    return -1;
}

int CTLOG_STORE_load_file(CTLOG_STORE *store, const char *file)
{
    int ret = 0;
    char *enabled_logs;
    CTLOG_STORE_LOAD_CTX* load_ctx = ctlog_store_load_ctx_new();

    if (load_ctx == NULL)
        return 0;
    load_ctx->log_store = store;
    load_ctx->conf = NCONF_new(NULL);
    if (load_ctx->conf == NULL)
        goto end;

    if (NCONF_load(load_ctx->conf, file, NULL) <= 0) {
        ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID);
        goto end;
    }

    enabled_logs = NCONF_get_string(load_ctx->conf, NULL, "enabled_logs");
    if (enabled_logs == NULL) {
        ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID);
        goto end;
    }

    if (!CONF_parse_list(enabled_logs, ',', 1, ctlog_store_load_log, load_ctx) ||
        load_ctx->invalid_log_entries > 0) {
        ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID);
        goto end;
    }

    ret = 1;
end:
    NCONF_free(load_ctx->conf);
    ctlog_store_load_ctx_free(load_ctx);
    return ret;
}

/*
 * Initialize a new CTLOG object.
 * Takes ownership of the public key.
 * Copies the name.
 */
CTLOG *CTLOG_new_ex(EVP_PKEY *public_key, const char *name, OSSL_LIB_CTX *libctx,
                    const char *propq)
{
    CTLOG *ret = OPENSSL_zalloc(sizeof(*ret));

    if (ret == NULL) {
        ERR_raise(ERR_LIB_CT, ERR_R_MALLOC_FAILURE);
        return NULL;
    }

    ret->libctx = libctx;
    if (propq != NULL) {
        ret->name = OPENSSL_strdup(propq);
        if (ret->propq == NULL) {
            ERR_raise(ERR_LIB_CT, ERR_R_MALLOC_FAILURE);
            goto err;
        }
    }

    ret->name = OPENSSL_strdup(name);
    if (ret->name == NULL) {
        ERR_raise(ERR_LIB_CT, ERR_R_MALLOC_FAILURE);
        goto err;
    }

    if (ct_v1_log_id_from_pkey(ret, public_key) != 1)
        goto err;

    ret->public_key = public_key;
    return ret;
err:
    CTLOG_free(ret);
    return NULL;
}

CTLOG *CTLOG_new(EVP_PKEY *public_key, const char *name)
{
    return CTLOG_new_ex(public_key, name, NULL, NULL);
}

/* Frees CT log and associated structures */
void CTLOG_free(CTLOG *log)
{
    if (log != NULL) {
        OPENSSL_free(log->name);
        EVP_PKEY_free(log->public_key);
        OPENSSL_free(log->propq);
        OPENSSL_free(log);
    }
}

const char *CTLOG_get0_name(const CTLOG *log)
{
    return log->name;
}

void CTLOG_get0_log_id(const CTLOG *log, const uint8_t **log_id,
                       size_t *log_id_len)
{
    *log_id = log->log_id;
    *log_id_len = CT_V1_HASHLEN;
}

EVP_PKEY *CTLOG_get0_public_key(const CTLOG *log)
{
    return log->public_key;
}

/*
 * Given a log ID, finds the matching log.
 * Returns NULL if no match found.
 */
const CTLOG *CTLOG_STORE_get0_log_by_id(const CTLOG_STORE *store,
                                        const uint8_t *log_id,
                                        size_t log_id_len)
{
    int i;

    for (i = 0; i < sk_CTLOG_num(store->logs); ++i) {
        const CTLOG *log = sk_CTLOG_value(store->logs, i);
        if (memcmp(log->log_id, log_id, log_id_len) == 0)
            return log;
    }

    return NULL;
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

Issue 1460

NotoSansMalayalam-mlm2

മ്പ്ലൢ

 Test details:
Tested font directory: https://github.com/googlefonts/noto-fonts/tree/main/unhinted/otf/NotoSansMalayalam/NotoSansMalayalam-Regular.otf
Test created date:


text:
/**
 * {@code byte[]} array key/value store API and related utility classes.
 */
package org.jsimpledb.kv;


text:
This plugin will provide metrics from one or more [Gearman](http://gearman.org/) servers to NewRelic. Metrics are provided for the number of queued jobs, number of workers and number of running jobs for the whole server and for each queue.

## Prerequisites

- Ruby
- Bundler
- A NewRelic account

## Installation

1. Download the [latest release](https://github.com/channelgrabber/newrelic-gearman-plugin/releases/latest) to the location you want to run the Gearman agent from
2. Run `bundle install` in the folder you downloaded the agent to
2. Copy `config/newrelic_plugin.yml.dist` to `config/newrelic_plugin.yml`
3. Edit `config/newrelic_plugin.yml` and replace "YOUR_LICENSE_KEY_HERE" with your New Relic license key
4. Configure the servers to monitor under the servers collection in the config file
5. Run `./newrelic_gearman_agent`


text:
<?php

if (!function_exists('curl_init')) {
  throw new Exception('aceitaFacil needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
  throw new Exception('aceitaFacil needs the JSON PHP extension.');
}

// aceitaFacil singleton
require(dirname(__FILE__) . '/aceitaFacil/aceitaFacil.php');

// Resources
require(dirname(__FILE__) . '/aceitaFacil/apiRequestor.php');

// aF API Resources
require(dirname(__FILE__) . '/aceitaFacil/card.php');
require(dirname(__FILE__) . '/aceitaFacil/vendor.php');
require(dirname(__FILE__) . '/aceitaFacil/payment.php');


text:
<?php

namespace Scripted\Exceptions;

use Exception;

class AccessTokenIsUnauthorized extends Exception
{

}


text:
'use strict';

let React = require('react/addons');
let jquery = require('jquery');
window.jQuery = jquery;
window.$ = jquery;

let Velocity = require('velocity-animate');
let bla = require('velocity-animate/velocity.ui');
window.Velocity = Velocity;

let App = require('./App.js');
let FoldersList = require('./components/FoldersList.js');
let FeedsList = require('./components/FeedsList.js');
let ArticlesList = require('./components/ArticlesList.js');
let NotFound = require('./components/NotFound.js');

let AppUtils = require('./AppUtils.js');
let Animations = require('./Animations.js');

let ReactRouter = require('react-router');
let Router = ReactRouter;
let Route = ReactRouter.Route;

let DefaultRoute = ReactRouter.DefaultRoute;
let NotFoundRoute = ReactRouter.NotFoundRoute;

let i18n = {
    locales: ['en-US']
};

let routes = (
    <Route name='home' path='/' handler={App}>
        <Route name='folderFeeds' path='/:folderName' handler={FeedsList}></Route>
        <Route name='feedItems' path='/:folderName/:feedUrl' handler={ArticlesList}></Route>
        <DefaultRoute name='root' handler={FoldersList} />
        <NotFoundRoute handler={NotFound}/>
    </Route>
);

Router.run(routes, function (Handler) {
    React.render(<Handler locales={i18n.locales} />, document.body);
});


text:
{% extends 'pages/import/base.html' %}

{% block subtitle %}Select Import Rarities{% endblock %}

{% block content_class %}import{% endblock %}

{% block link_import %}active{% endblock %}

{% block wrapper_classes %}
    col-md-8 col-md-offset-2
    col-sm-12 col-sm-offset-0
    col-xs-12 col-xs-offset-0
{% endblock %}

{% block content_small %}

            Select card rarities

            Some of the cards you are trying to import have multiple rarities and you did not specify one (or it was incorrect). Please select the rarities for your cards.

    <form class="form import-rarities" method="post" action="">
        {% csrf_token %}

                    #
                    Set Number
                    Card Name
                    Rarities

                {% for key, data in view.import_data.not_found_rarities.items %}
                    {% for rarity_identifier, rarity_data in data.rarities.items %}

                            {% if forloop.counter == 1 %}

                                    {{ forloop.parentloop.counter }}

                                    {{ key }}

                                    {{ data.name }}

                            {% endif %}

                                {{ rarity_data.name }}

                                <input type="hidden" name="rarity[{{ key }}][{{ rarity_identifier }}]" class="rarity-input" data-max="{{ data.count }}" />

                    {% endfor %}
                {% endfor %}

            <button type="submit" class="btn btn-primary pull-right">
                Submit
            </button>

    </form>
{% endblock %}


text:
import * as oauth from 'oauth';

import { Configuration } from './types/configuration';
import { OAuthProvider, OAuthUser } from '@accounts/oauth';

export class AccountsOAuthTwitter implements OAuthProvider {
  private config: Configuration;
  private oauth: any;

  public getRegistrationPayload?: (oauthUser: OAuthUser) => Promise<any>;

  constructor(config: Configuration) {
    this.config = config;
    this.oauth = new oauth.OAuth(
      'https://twitter.com/oauth/request_token',
      'https://twitter.com/oauth/access_token',
      this.config.key,
      this.config.secret,
      '1.0A',
      null,
      'HMAC-SHA1'
    );

    this.getRegistrationPayload = config.getRegistrationPayload;
  }

  public authenticate(params: any): Promise<OAuthUser> {
    return new Promise((resolve, reject) => {
      this.oauth.get(
        'https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true',
        params.access_token,
        params.access_token_secret,
        (err: any, data: any) => {
          if (err) {
            reject(err);
          } else {
            data = JSON.parse(data);
            const user = {
              id: data.id_str,
              screenName: data.screen_name,
              profilePicture: data.profile_image_url_https,
              email: data.email,
              accessToken: params.access_token,
              accessTokenSecret: params.access_token_secret,
            };
            resolve(user);
          }
        }
      );
    });
  }
}


text:
package org.pdfsam.eventstudio;

/**
 * Listener for events of the generic type
 *
 * @author Andrea Vacondio
 * @param <T>
 *            type of the event the listener is interested in
 */
public interface Listener<T> {

    /**
     * Notify the listener of the given event
     */
    void onEvent(T event);
}


text:
namespace Google.Cloud.Dialogflow.V2Beta1.Snippets
{
    // [START dialogflow_v2beta1_generated_Agents_GetAgent_async_flattened_resourceNames2]
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.Dialogflow.V2Beta1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedAgentsClientSnippets
    {
        /// <summary>Snippet for GetAgentAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task GetAgentResourceNames2Async()
        {
            // Create client
            AgentsClient agentsClient = await AgentsClient.CreateAsync();
            // Initialize request argument(s)
            LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
            // Make the request
            Agent response = await agentsClient.GetAgentAsync(parent);
        }
    }
    // [END dialogflow_v2beta1_generated_Agents_GetAgent_async_flattened_resourceNames2]
}


text:
package busetabot

import (
	"context"
	"encoding/json"
	"fmt"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/pkg/errors"
	"github.com/yi-jiayu/datamall/v3"
	"google.golang.org/appengine"

	"github.com/yi-jiayu/bus-eta-bot/v4/telegram"
)

var (
	errInvalidBusStopCode = errors.New("bus stop code invalid")
)

var (
	sgt = time.FixedZone("SGT", 8*3600)
)

type ETA struct {
	BusStop  BusStop
	Now      time.Time
	Services []datamall.Service
	Error    string
}

type FormatterFactory interface {
	GetFormatter(ctx context.Context, userID int) Formatter
}

type BusStopGetter interface {
	Get(ID string) *BusStop
}

// BusEtas represents the calculated time before buses arrive at a bus stop
type BusEtas struct {
	BusStopID   string
	UpdatedTime time.Time
	Services    []IncomingBuses
}

// IncomingBuses contains information about incoming buses for a single service at a bus stop.
type IncomingBuses struct {
	ServiceNo string
	Etas      [3]string
	Loads     [3]string
	Features  [3]string
	Types     [3]string
}

// CallbackData represents the data to be included with the Refresh inline keyboard button in eta messages.
type CallbackData struct {
	Type       string   `json:"t"`
	BusStopID  string   `json:"b,omitempty"`
	ServiceNos []string `json:"s,omitempty"`
	Argstr     string   `json:"a,omitempty"`
	Formatter  string   `json:"f,omitempty"`
}

type ETAFormatter interface {
	Format(etas BusEtas, services []string) string
}

// SummaryETAFormatter displays ETAs for up to the next 3 buses at a bus stop.
type SummaryETAFormatter struct{}

type ETARequest struct {
	UserID   int
	Time     time.Time
	Code     string
	Services []string
}

type ETAMessageFactory struct {
	busStopGetter    BusStopGetter
	etaService       ETAService
	formatterFactory FormatterFactory
}

func (f ETAMessageFactory) Text(ctx context.Context, request ETARequest) (string, error) {
	var wg sync.WaitGroup
	var eta ETA
	var formatter Formatter
	wg.Add(2)
	go func() {
		eta = NewETA(ctx, f.busStopGetter, f.etaService, request)
		wg.Done()
	}()
	go func() {
		formatter = f.formatterFactory.GetFormatter(ctx, request.UserID)
		wg.Done()
	}()
	wg.Wait()
	return formatter.Format(eta)
}

func NewETA(ctx context.Context, busStopGetter BusStopGetter, etaService ETAService, request ETARequest) (eta ETA) {
	eta.Now = request.Time
	stop := busStopGetter.Get(request.Code)
	if stop != nil {
		eta.BusStop = *stop
	} else {
		eta.BusStop.BusStopCode = request.Code
	}
	arrival, err := etaService.GetBusArrival(request.Code, "")
	if err != nil {
		if err, ok := err.(*datamall.Error); ok {
			eta.Error = fmt.Sprintf("LTA DataMall could be down at the moment (status code %d)", err.StatusCode)
			// TODO: record metrics about DataMall disruptions
		} else {
			eta.Error = fmt.Sprintf("An error occurred while fetching ETAs (request ID: %s)", appengine.RequestID(ctx))
			logError(ctx, err)
		}
		return
	}
	if len(request.Services) == 0 {
		eta.Services = arrival.Services
	} else {
		for _, svc := range arrival.Services {
			if contains(request.Services, svc.ServiceNo) {
				eta.Services = append(eta.Services, svc)
			}
		}
	}
	return
}

func (SummaryETAFormatter) Format(etas BusEtas, serviceNos []string) string {
	showing := 0
	services := make([][4]string, 0)
	for _, service := range etas.Services {
		serviceNo := service.ServiceNo
		if serviceNos != nil && len(serviceNos) != 0 && !contains(serviceNos, serviceNo) {
			continue
		}

		arrivals := [4]string{serviceNo, service.Etas[0], service.Etas[1], service.Etas[2]}
		services = append(services, arrivals)
		showing++
	}

	sort.Sort(byServiceNo(services))

	table := EtaTable(services)

	var servicesNoun string
	if len(etas.Services) > 1 {
		servicesNoun = "services"
	} else {
		servicesNoun = "service"
	}
	shown := fmt.Sprintf("Showing %d out of %d %s for this bus stop.", showing, len(etas.Services), servicesNoun)

	// the first line break immediately after the opening triple backticks is needed
	// otherwise the first pipe gets swallowed
	formatted := fmt.Sprintf("```\n%s```\n%s", table, shown)

	return formatted
}

// InferEtaQuery extracts a bus stop ID and service numbers from a text message.
func InferEtaQuery(text string) (string, []string, error) {
	m := busStopRegex.FindStringSubmatch(text)
	if m == nil {
		return "", nil, errInvalidBusStopCode
	}
	code := m[1]
	rest := strings.TrimPrefix(text, code)
	services := strings.Fields(rest)
	return code, services, nil
}

// CalculateEtas calculates the time before buses arrive from the LTA DataMall bus arrival response
func CalculateEtas(t time.Time, busArrival datamall.BusArrival) BusEtas {
	services := make([]IncomingBuses, 0)

	for _, service := range busArrival.Services {
		incomingBuses := IncomingBuses{
			ServiceNo: service.ServiceNo,
		}

		placeholder := "?"

		for i := 0; i < 3; i++ {
			var incomingBus datamall.ArrivingBus
			switch i {
			case 0:
				incomingBus = service.NextBus
			case 1:
				incomingBus = service.NextBus2
			case 2:
				incomingBus = service.NextBus3
			}

			if estArrival := incomingBus.EstimatedArrival; estArrival != (time.Time{}) {
				diff := (estArrival.Unix() - t.Unix()) / 60
				incomingBuses.Etas[i] = fmt.Sprintf("%d", diff)
			} else {
				incomingBuses.Etas[i] = placeholder
			}

			incomingBuses.Loads[i] = incomingBus.Load
			incomingBuses.Features[i] = incomingBus.Feature
			incomingBuses.Types[i] = incomingBus.Type
		}

		services = append(services, incomingBuses)
	}

	return BusEtas{
		BusStopID:   busArrival.BusStopCode,
		UpdatedTime: t,
		Services:    services,
	}
}

func contains(serviceNos []string, serviceNo string) bool {
	for _, s := range serviceNos {
		if s == serviceNo {
			return true
		}
	}

	return false
}

type byServiceNo [][4]string

func (s byServiceNo) Len() int           { return len(s) }
func (s byServiceNo) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byServiceNo) Less(i, j int) bool { return s[i][0] < s[j][0] }

func padLeft(s string, l int, c string) string {
	for {
		if len(s) >= l {
			return s
		}

		s = c + s
	}
}

func padRight(s string, l int, c string) string {
	for {
		if len(s) >= l {
			return s
		}

		s += c
	}
}

// EtaTable generates the table of bus etas used in a eta message
func EtaTable(etas [][4]string) string {
	table := [][4]string{
		{"Svc", "Next", " 2nd", " 3rd"},
	}

	for _, eta := range etas {
		table = append(table, eta)
	}

	maxWidths := make([]int, len(table[0]))
	for _, row := range table {
		for pos, col := range row {
			if len(col) > maxWidths[pos] {
				maxWidths[pos] = len(col)
			}
		}
	}

	output := ""
	for i, row := range table {
		if i == 1 {
			for pos := range row {
				switch pos {
				case 0:
					output += "|-" + padRight("", maxWidths[pos], "-")
				case 3:
					output += "-|-" + padRight("", maxWidths[pos], "-") + "-|"
				default:
					output += "-|-" + padRight("", maxWidths[pos], "-")
				}
			}

			output += "\n"
		}

		for pos, col := range row {
			switch pos {
			case 0:
				output += "| " + padRight(col, maxWidths[pos], " ")
			case 3:
				output += " | " + padLeft(col, maxWidths[pos], " ") + " |"
			default:
				output += " | " + padLeft(col, maxWidths[pos], " ")
			}
		}

		output += "\n"
	}

	// remove final newline
	return output[:len(output)-1]
}

func NewRefreshButton(busStopCode string, serviceNos []string, formatter string) telegram.InlineKeyboardButton {
	data := CallbackData{
		Type:       "refresh",
		BusStopID:  busStopCode,
		ServiceNos: serviceNos,
		Formatter:  formatter,
	}
	JSON, _ := json.Marshal(data)
	return telegram.InlineKeyboardButton{
		Text:         "Refresh",
		CallbackData: string(JSON),
	}
}

func NewIncomingBusDetailsButton(busStopCode string, serviceNos []string) telegram.InlineKeyboardButton {
	data := CallbackData{
		Type:       "refresh",
		BusStopID:  busStopCode,
		ServiceNos: serviceNos,
		Formatter:  FormatterFeatures,
	}
	JSON, _ := json.Marshal(data)
	return telegram.InlineKeyboardButton{
		Text:         "Show incoming bus details",
		CallbackData: string(JSON),
	}
}

func NewIncomingBusSummaryButton(busStopCode string, serviceNos []string) telegram.InlineKeyboardButton {
	data := CallbackData{
		Type:       "refresh",
		BusStopID:  busStopCode,
		ServiceNos: serviceNos,
		Formatter:  FormatterSummary,
	}
	JSON, _ := json.Marshal(data)
	return telegram.InlineKeyboardButton{
		Text:         "Show incoming bus summary",
		CallbackData: string(JSON),
	}
}

func NewResendButton(busStopCode string, serviceNos []string, formatter string) telegram.InlineKeyboardButton {
	data := CallbackData{
		Type:       "resend",
		BusStopID:  busStopCode,
		ServiceNos: serviceNos,
		Formatter:  formatter,
	}
	JSON, _ := json.Marshal(data)
	return telegram.InlineKeyboardButton{
		Text:         "Resend",
		CallbackData: string(JSON),
	}
}

func NewToggleFavouriteButton(busStopCode string, serviceNos []string) telegram.InlineKeyboardButton {
	argstr := busStopCode
	if len(serviceNos) > 0 {
		argstr += " " + strings.Join(serviceNos, " ")
	}
	data := CallbackData{
		Type:   "togf",
		Argstr: argstr,
	}
	JSON, _ := json.Marshal(data)
	return telegram.InlineKeyboardButton{
		Text:         "⭐",
		CallbackData: string(JSON),
	}
}

func NewETAMessageReplyMarkup(busStopCode string, serviceNos []string, formatter string, inline bool) telegram.InlineKeyboardMarkup {
	row := []telegram.InlineKeyboardButton{
		NewRefreshButton(busStopCode, serviceNos, formatter),
	}
	if !inline {
		row = append(row,
			NewResendButton(busStopCode, serviceNos, formatter),
			NewToggleFavouriteButton(busStopCode, serviceNos))
	}
	keyboard := [][]telegram.InlineKeyboardButton{
		row,
	}
	if formatter == FormatterFeatures {
		keyboard = append(keyboard, []telegram.InlineKeyboardButton{
			NewIncomingBusSummaryButton(busStopCode, serviceNos),
		})
	} else {
		keyboard = append(keyboard, []telegram.InlineKeyboardButton{
			NewIncomingBusDetailsButton(busStopCode, serviceNos),
		})
	}
	return telegram.InlineKeyboardMarkup{
		InlineKeyboard: keyboard,
	}
}


text:
export const pushChild = (el: Element, child: Element) => {
    if (el.hasChildNodes()) {
        el.insertBefore(child, el.firstChild);
    } else {
        el.appendChild(child);
    }
};

// from: https://stackoverflow.com/a/9899701/87207
export function docReady(fn: () => void) {
    if (document.readyState === "complete" || document.readyState === "interactive") {
        setTimeout(fn, 1);
    } else {
        document.addEventListener("DOMContentLoaded", fn);
    }
}

// https://javascript.info/cookie#getcookie-name
export function get_cookie(name: string): string | undefined {
    const matches = document.cookie.match(
        new RegExp("(?:^|; )" + name.replace(/([.$?*|{}()[]\\\/\+^])/g, "\\$1") + "=([^;]*)")
    );
    return matches ? decodeURIComponent(matches[1]) : undefined;
}

interface CookieOptions {
    expires?: Date | string;
    path?: string;
    secure?: boolean;
    samesite?: string;
    "max-age"?: number;
}

// https://javascript.info/cookie#setcookie-name-value-options
export function set_cookie(name: string, value: string, options: CookieOptions = {}): void {
    options = {
        ...options,
        path: "/",
        secure: true,
        samesite: "strict",
    };

    if (options.expires instanceof Date) {
        options.expires = options.expires.toUTCString();
    }

    let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);

    for (const optionKey in options) {
        updatedCookie += "; " + optionKey;
        const optionValue = (options as Record<string, any>)[optionKey];
        if (optionValue !== true) {
            updatedCookie += "=" + optionValue;
        }
    }

    document.cookie = updatedCookie;
}

export function delete_cookie(name: string): void {
    set_cookie(name, "", { expires: "Thu, 01 Jan 1970 00:00:00 UTC" });
}

// from: https://formcarry.com/documentation/fetch-api-example
export const encode_form_data = (data: Record<string, string>): string => {
    return Object.keys(data)
        .map((key) => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
        .join("&");
};

// see python's `partition` function.
// split at the first instance of the given separacter, returning [before, sep, after].
// if the separator doesn't exist, return everything in `before`, other elements empty strings.
export function partition(s: string, c: string): [string, string, string] {
    const i = s.indexOf(c);
    if (i === -1) {
        return [s, "", ""];
    } else {
        return [s.substring(0, i), c, s.substring(i + c.length)];
    }
}

export function rpartition(s: string, c: string): [string, string, string] {
    const i = s.lastIndexOf(c);
    if (i === -1) {
        return ["", "", s];
    } else {
        return [s.substring(0, i), c, s.substring(i + c.length)];
    }
}

export function open_tab(url: string) {
    window.open(url, "_blank");
}

export function assert(condition: any, msg?: string): asserts condition {
    if (!condition) {
        throw new Error(msg);
    }
}

const _inserted_stylesheets = new Set();

// this is a function intended to be used as a template literal tag,
// like this:
//
//     css`
//       body { color: red; }
//     `;
//
// it installs the css into the current document on first invocation.
// otherwise, its a nop.
//
// this enables you to colocate styles with elements.
// note: the style is not scoped to any element.
export function css(stylesheet: string) {
    if (!_inserted_stylesheets.has(stylesheet)) {
        const style = document.createElement("style");
        style.type = "text/css";
        style.appendChild(document.createTextNode(stylesheet));
        document.head.appendChild(style);

        _inserted_stylesheets.add(stylesheet);
    }
}

// https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#union-exhaustiveness-checking
export function assertNever(x: never): never {
    throw new Error("Unexpected object: " + x);
}

// timestamp in UTC.
// like: "2021-06-17T19:50:48.520Z"
export function get_timestamp(): string {
    return new Date().toISOString();
}

export function has_property(object: Record<string, unknown>, key: string): boolean {
    return Object.prototype.hasOwnProperty.call(object, key);
}

export const RENDERED_HEX: string[] = [];
for (let i = 0; i < 0x100; i++) {
    RENDERED_HEX.push(i.toString(0x10).padStart(2, "0"));
}

export const RENDERED_ASCII: string[] = [];
for (let i = 0; i < 0x100; i++) {
    // " " to "~", which are all the printable ascii characters.
    // does not include tab or newline (which may take more than one column).
    if (i >= 0x20 && i <= 0x7f) {
        RENDERED_ASCII.push(String.fromCharCode(i));
    } else {
        RENDERED_ASCII.push(".");
    }
}

export function hexdump(buf: Uint8Array, address: bigint | number): string {
    const ret = [];
    for (let i = 0; i < buf.length; i += 0x10) {
        const hex: string[] = [];
        const ascii: string[] = [];

        const temporary = buf.slice(i, i + 0x10);
        for (const b of temporary) {
            hex.push(RENDERED_HEX[b]);
            ascii.push(RENDERED_ASCII[b]);
        }

        const addr_prefix = (BigInt(address) + BigInt(i)).toString(0x10).padStart(8, "0");
        const hex_column = hex.join(" ");
        const ascii_column = ascii.join("");

        const line = `${addr_prefix}  ${hex_column}  ${ascii_column}`;
        ret.push(line);
    }
    return ret.join("\n");
}

export function hex(buf: Uint8Array, separator = " "): string {
    const ret: string[] = [];
    buf.forEach((b) => ret.push(RENDERED_HEX[b]));
    return ret.join(separator);
}


text:
package test.failedreporter.issue1297.groups;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;

public class GroupsSampleBase {
  @BeforeTest(groups = "run")
  public void baseBeforeTest() {}

  @BeforeClass(alwaysRun = true)
  public void baseBeforeClassAlwaysRun() {}

  @BeforeMethod
  public void baseBeforeMethod() {}

  @AfterClass
  public void baseAfterClass() {}
}


text:
layout: post
title: 'Updating the Site'
date: 2008-12-17 12:31
comments: true
categories : [Drupal, Open Source, Acquia]
---

This site has been running on a Drupal 5 codebase for quite some time. This morning I took the time to upgrade to Drupal 6.8 then upgraded to the lastest version of the Acquia Network Community Server.

So far it's gone well and has been relatively drama free. There are some older Drupal 5 modules that I need to update to get full functionality back so if you see any issues please use the contact form to drop me a note and let me know.

thanks


text:
package com.opengamma.strata.product.swap;

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

import java.io.Serializable;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;

import org.joda.beans.Bean;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaBean;
import org.joda.beans.MetaProperty;
import org.joda.beans.gen.BeanDefinition;
import org.joda.beans.gen.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.date.DayCount;
import com.opengamma.strata.basics.index.Index;
import com.opengamma.strata.basics.schedule.Schedule;
import com.opengamma.strata.basics.schedule.SchedulePeriod;
import com.opengamma.strata.basics.value.ValueSchedule;
import com.opengamma.strata.collect.array.DoubleArray;
import com.opengamma.strata.collect.tuple.Pair;
import com.opengamma.strata.product.rate.FixedOvernightCompoundedAnnualRateComputation;
import com.opengamma.strata.product.rate.FixedRateComputation;
import com.opengamma.strata.product.rate.RateComputation;

/**
 * Defines the calculation of a fixed rate swap leg.
 *

 * This defines the data necessary to calculate the amount payable on the leg.
 * The amount is based on a fixed rate, which can vary over the lifetime of the leg.
 */
@BeanDefinition
public final class FixedRateCalculation
    implements RateCalculation, ImmutableBean, Serializable {

  /**
   * The day count convention.
   *

   * This is used to convert schedule period dates to a numerical value.
   */
  @PropertyDefinition(validate = "notNull", overrideGet = true)
  private final DayCount dayCount;
  /**
   * The interest rate to be paid.
   * A 5% rate will be expressed as 0.05.
   *

   * This defines the rate as an initial amount and a list of adjustments.
   * The rate is only permitted to change at accrual period boundaries.
   */
  @PropertyDefinition(validate = "notNull")
  private final ValueSchedule rate;
  /**
   * The initial stub, optional.
   *

   * The initial stub of a swap may have a different rate from the regular accrual periods.
   * This property allows the stub rate to be specified, either as a known amount or a rate.
   * If this property is not present, then the rate derived from the {@code rate} property applies during the stub.
   * If this property is present and there is no initial stub, it is ignored.
   */
  @PropertyDefinition(get = "optional")
  private final FixedRateStubCalculation initialStub;
  /**
   * The final stub, optional.
   *

   * The final stub of a swap may have a different rate from the regular accrual periods.
   * This property allows the stub rate to be specified, either as a known amount or a rate.
   * If this property is not present, then the rate derived from the {@code rate} property applies during the stub.
   * If this property is present and there is no initial stub, it is ignored.
   */
  @PropertyDefinition(get = "optional")
  private final FixedRateStubCalculation finalStub;
  /**
   * The future value notional.
   *

   * This property is used when the fixed leg of a swap has a future value notional.
   * This is typically used for Brazilian swaps.
   */
  @PropertyDefinition(get = "optional")
  private final FutureValueNotional futureValueNotional;

  //-------------------------------------------------------------------------
  /**
   * Obtains a rate calculation for the specified day count and rate.
   *

   * The rate specified here does not vary during the life of the swap.
   * If this method provides insufficient control, use the {@linkplain #builder() builder}.
   *
   * @param rate  the rate
   * @param dayCount  the day count
   * @return the calculation
   */
  public static FixedRateCalculation of(double rate, DayCount dayCount) {
    return FixedRateCalculation.builder()
        .dayCount(dayCount)
        .rate(ValueSchedule.of(rate))
        .build();
  }

  //-------------------------------------------------------------------------
  @Override
  public SwapLegType getType() {
    return SwapLegType.FIXED;
  }

  @Override
  public void collectCurrencies(ImmutableSet.Builder<Currency> builder) {
    // no currencies
  }

  @Override
  public void collectIndices(ImmutableSet.Builder<Index> builder) {
    // no indices
  }

  @Override
  public ImmutableList<RateAccrualPeriod> createAccrualPeriods(
      Schedule accrualSchedule,
      Schedule paymentSchedule,
      ReferenceData refData) {

    // avoid null stub definitions if there are stubs
    FixedRateStubCalculation initialStub = firstNonNull(this.initialStub, FixedRateStubCalculation.NONE);
    FixedRateStubCalculation finalStub = firstNonNull(this.finalStub, FixedRateStubCalculation.NONE);

    // resolve data by schedule
    DoubleArray resolvedRates = rate.resolveValues(accrualSchedule);

    // future value notional present
    if (getFutureValueNotional().isPresent()) {
      if (accrualSchedule.size() != 1) {
        throw new IllegalArgumentException(
            "Invalid swap, only one accrual period allowed when future value notional is present");
      }
      SchedulePeriod period = accrualSchedule.getPeriod(0);
      double yearFraction = period.yearFraction(dayCount, accrualSchedule);
      double resolvedRate = resolvedRates.get(0);
      RateComputation rateComputation = FixedOvernightCompoundedAnnualRateComputation.of(resolvedRate, yearFraction);
      RateAccrualPeriod accrualPeriod = new RateAccrualPeriod(period, yearFraction, rateComputation);
      return ImmutableList.of(accrualPeriod);
    }

    // need to use getStubs(boolean) and not getInitialStub()/getFinalStub() to ensure correct stub allocation
    Pair<Optional<SchedulePeriod>, Optional<SchedulePeriod>> scheduleStubs =
        accrualSchedule.getStubs(this.initialStub == null && this.finalStub != null);
    Optional<SchedulePeriod> scheduleInitialStub = scheduleStubs.getFirst();
    Optional<SchedulePeriod> scheduleFinalStub = scheduleStubs.getSecond();

    // normal case
    ImmutableList.Builder<RateAccrualPeriod> accrualPeriods = ImmutableList.builder();
    for (int i = 0; i < accrualSchedule.size(); i++) {
      SchedulePeriod period = accrualSchedule.getPeriod(i);
      double yearFraction = period.yearFraction(dayCount, accrualSchedule);
      // handle stubs
      RateComputation rateComputation;
      if (scheduleInitialStub.isPresent() && scheduleInitialStub.get() == period) {
        rateComputation = initialStub.createRateComputation(resolvedRates.get(i));
      } else if (scheduleFinalStub.isPresent() && scheduleFinalStub.get() == period) {
        rateComputation = finalStub.createRateComputation(resolvedRates.get(i));
      } else {
        rateComputation = FixedRateComputation.of(resolvedRates.get(i));
      }
      accrualPeriods.add(new RateAccrualPeriod(period, yearFraction, rateComputation));
    }
    return accrualPeriods.build();
  }

  //------------------------- AUTOGENERATED START -------------------------
  /**
   * The meta-bean for {@code FixedRateCalculation}.
   * @return the meta-bean, not null
   */
  public static FixedRateCalculation.Meta meta() {
    return FixedRateCalculation.Meta.INSTANCE;
  }

  static {
    MetaBean.register(FixedRateCalculation.Meta.INSTANCE);
  }

  /**
   * The serialization version id.
   */
  private static final long serialVersionUID = 1L;

  /**
   * Returns a builder used to create an instance of the bean.
   * @return the builder, not null
   */
  public static FixedRateCalculation.Builder builder() {
    return new FixedRateCalculation.Builder();
  }

  private FixedRateCalculation(
      DayCount dayCount,
      ValueSchedule rate,
      FixedRateStubCalculation initialStub,
      FixedRateStubCalculation finalStub,
      FutureValueNotional futureValueNotional) {
    JodaBeanUtils.notNull(dayCount, "dayCount");
    JodaBeanUtils.notNull(rate, "rate");
    this.dayCount = dayCount;
    this.rate = rate;
    this.initialStub = initialStub;
    this.finalStub = finalStub;
    this.futureValueNotional = futureValueNotional;
  }

  @Override
  public FixedRateCalculation.Meta metaBean() {
    return FixedRateCalculation.Meta.INSTANCE;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the day count convention.
   *

   * This is used to convert schedule period dates to a numerical value.
   * @return the value of the property, not null
   */
  @Override
  public DayCount getDayCount() {
    return dayCount;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the interest rate to be paid.
   * A 5% rate will be expressed as 0.05.
   *

   * This defines the rate as an initial amount and a list of adjustments.
   * The rate is only permitted to change at accrual period boundaries.
   * @return the value of the property, not null
   */
  public ValueSchedule getRate() {
    return rate;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the initial stub, optional.
   *

   * The initial stub of a swap may have a different rate from the regular accrual periods.
   * This property allows the stub rate to be specified, either as a known amount or a rate.
   * If this property is not present, then the rate derived from the {@code rate} property applies during the stub.
   * If this property is present and there is no initial stub, it is ignored.
   * @return the optional value of the property, not null
   */
  public Optional<FixedRateStubCalculation> getInitialStub() {
    return Optional.ofNullable(initialStub);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the final stub, optional.
   *

   * The final stub of a swap may have a different rate from the regular accrual periods.
   * This property allows the stub rate to be specified, either as a known amount or a rate.
   * If this property is not present, then the rate derived from the {@code rate} property applies during the stub.
   * If this property is present and there is no initial stub, it is ignored.
   * @return the optional value of the property, not null
   */
  public Optional<FixedRateStubCalculation> getFinalStub() {
    return Optional.ofNullable(finalStub);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the future value notional.
   *

   * This property is used when the fixed leg of a swap has a future value notional.
   * This is typically used for Brazilian swaps.
   * @return the optional value of the property, not null
   */
  public Optional<FutureValueNotional> getFutureValueNotional() {
    return Optional.ofNullable(futureValueNotional);
  }

  //-----------------------------------------------------------------------
  /**
   * Returns a builder that allows this bean to be mutated.
   * @return the mutable builder, not null
   */
  public Builder toBuilder() {
    return new Builder(this);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      FixedRateCalculation other = (FixedRateCalculation) obj;
      return JodaBeanUtils.equal(dayCount, other.dayCount) &&
          JodaBeanUtils.equal(rate, other.rate) &&
          JodaBeanUtils.equal(initialStub, other.initialStub) &&
          JodaBeanUtils.equal(finalStub, other.finalStub) &&
          JodaBeanUtils.equal(futureValueNotional, other.futureValueNotional);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(dayCount);
    hash = hash * 31 + JodaBeanUtils.hashCode(rate);
    hash = hash * 31 + JodaBeanUtils.hashCode(initialStub);
    hash = hash * 31 + JodaBeanUtils.hashCode(finalStub);
    hash = hash * 31 + JodaBeanUtils.hashCode(futureValueNotional);
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(192);
    buf.append("FixedRateCalculation{");
    buf.append("dayCount").append('=').append(JodaBeanUtils.toString(dayCount)).append(',').append(' ');
    buf.append("rate").append('=').append(JodaBeanUtils.toString(rate)).append(',').append(' ');
    buf.append("initialStub").append('=').append(JodaBeanUtils.toString(initialStub)).append(',').append(' ');
    buf.append("finalStub").append('=').append(JodaBeanUtils.toString(finalStub)).append(',').append(' ');
    buf.append("futureValueNotional").append('=').append(JodaBeanUtils.toString(futureValueNotional));
    buf.append('}');
    return buf.toString();
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code FixedRateCalculation}.
   */
  public static final class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code dayCount} property.
     */
    private final MetaProperty<DayCount> dayCount = DirectMetaProperty.ofImmutable(
        this, "dayCount", FixedRateCalculation.class, DayCount.class);
    /**
     * The meta-property for the {@code rate} property.
     */
    private final MetaProperty<ValueSchedule> rate = DirectMetaProperty.ofImmutable(
        this, "rate", FixedRateCalculation.class, ValueSchedule.class);
    /**
     * The meta-property for the {@code initialStub} property.
     */
    private final MetaProperty<FixedRateStubCalculation> initialStub = DirectMetaProperty.ofImmutable(
        this, "initialStub", FixedRateCalculation.class, FixedRateStubCalculation.class);
    /**
     * The meta-property for the {@code finalStub} property.
     */
    private final MetaProperty<FixedRateStubCalculation> finalStub = DirectMetaProperty.ofImmutable(
        this, "finalStub", FixedRateCalculation.class, FixedRateStubCalculation.class);
    /**
     * The meta-property for the {@code futureValueNotional} property.
     */
    private final MetaProperty<FutureValueNotional> futureValueNotional = DirectMetaProperty.ofImmutable(
        this, "futureValueNotional", FixedRateCalculation.class, FutureValueNotional.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "dayCount",
        "rate",
        "initialStub",
        "finalStub",
        "futureValueNotional");

    /**
     * Restricted constructor.
     */
    private Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case 1905311443:  // dayCount
          return dayCount;
        case 3493088:  // rate
          return rate;
        case 1233359378:  // initialStub
          return initialStub;
        case 355242820:  // finalStub
          return finalStub;
        case -282775858:  // futureValueNotional
          return futureValueNotional;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public FixedRateCalculation.Builder builder() {
      return new FixedRateCalculation.Builder();
    }

    @Override
    public Class<? extends FixedRateCalculation> beanType() {
      return FixedRateCalculation.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code dayCount} property.
     * @return the meta-property, not null
     */
    public MetaProperty<DayCount> dayCount() {
      return dayCount;
    }

    /**
     * The meta-property for the {@code rate} property.
     * @return the meta-property, not null
     */
    public MetaProperty<ValueSchedule> rate() {
      return rate;
    }

    /**
     * The meta-property for the {@code initialStub} property.
     * @return the meta-property, not null
     */
    public MetaProperty<FixedRateStubCalculation> initialStub() {
      return initialStub;
    }

    /**
     * The meta-property for the {@code finalStub} property.
     * @return the meta-property, not null
     */
    public MetaProperty<FixedRateStubCalculation> finalStub() {
      return finalStub;
    }

    /**
     * The meta-property for the {@code futureValueNotional} property.
     * @return the meta-property, not null
     */
    public MetaProperty<FutureValueNotional> futureValueNotional() {
      return futureValueNotional;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 1905311443:  // dayCount
          return ((FixedRateCalculation) bean).getDayCount();
        case 3493088:  // rate
          return ((FixedRateCalculation) bean).getRate();
        case 1233359378:  // initialStub
          return ((FixedRateCalculation) bean).initialStub;
        case 355242820:  // finalStub
          return ((FixedRateCalculation) bean).finalStub;
        case -282775858:  // futureValueNotional
          return ((FixedRateCalculation) bean).futureValueNotional;
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      metaProperty(propertyName);
      if (quiet) {
        return;
      }
      throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
    }

  }

  //-----------------------------------------------------------------------
  /**
   * The bean-builder for {@code FixedRateCalculation}.
   */
  public static final class Builder extends DirectFieldsBeanBuilder<FixedRateCalculation> {

    private DayCount dayCount;
    private ValueSchedule rate;
    private FixedRateStubCalculation initialStub;
    private FixedRateStubCalculation finalStub;
    private FutureValueNotional futureValueNotional;

    /**
     * Restricted constructor.
     */
    private Builder() {
    }

    /**
     * Restricted copy constructor.
     * @param beanToCopy  the bean to copy from, not null
     */
    private Builder(FixedRateCalculation beanToCopy) {
      this.dayCount = beanToCopy.getDayCount();
      this.rate = beanToCopy.getRate();
      this.initialStub = beanToCopy.initialStub;
      this.finalStub = beanToCopy.finalStub;
      this.futureValueNotional = beanToCopy.futureValueNotional;
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
      switch (propertyName.hashCode()) {
        case 1905311443:  // dayCount
          return dayCount;
        case 3493088:  // rate
          return rate;
        case 1233359378:  // initialStub
          return initialStub;
        case 355242820:  // finalStub
          return finalStub;
        case -282775858:  // futureValueNotional
          return futureValueNotional;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
    }

    @Override
    public Builder set(String propertyName, Object newValue) {
      switch (propertyName.hashCode()) {
        case 1905311443:  // dayCount
          this.dayCount = (DayCount) newValue;
          break;
        case 3493088:  // rate
          this.rate = (ValueSchedule) newValue;
          break;
        case 1233359378:  // initialStub
          this.initialStub = (FixedRateStubCalculation) newValue;
          break;
        case 355242820:  // finalStub
          this.finalStub = (FixedRateStubCalculation) newValue;
          break;
        case -282775858:  // futureValueNotional
          this.futureValueNotional = (FutureValueNotional) newValue;
          break;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
      return this;
    }

    @Override
    public Builder set(MetaProperty<?> property, Object value) {
      super.set(property, value);
      return this;
    }

    @Override
    public FixedRateCalculation build() {
      return new FixedRateCalculation(
          dayCount,
          rate,
          initialStub,
          finalStub,
          futureValueNotional);
    }

    //-----------------------------------------------------------------------
    /**
     * Sets the day count convention.
     *

     * This is used to convert schedule period dates to a numerical value.
     * @param dayCount  the new value, not null
     * @return this, for chaining, not null
     */
    public Builder dayCount(DayCount dayCount) {
      JodaBeanUtils.notNull(dayCount, "dayCount");
      this.dayCount = dayCount;
      return this;
    }

    /**
     * Sets the interest rate to be paid.
     * A 5% rate will be expressed as 0.05.
     *

     * This defines the rate as an initial amount and a list of adjustments.
     * The rate is only permitted to change at accrual period boundaries.
     * @param rate  the new value, not null
     * @return this, for chaining, not null
     */
    public Builder rate(ValueSchedule rate) {
      JodaBeanUtils.notNull(rate, "rate");
      this.rate = rate;
      return this;
    }

    /**
     * Sets the initial stub, optional.
     *

     * The initial stub of a swap may have a different rate from the regular accrual periods.
     * This property allows the stub rate to be specified, either as a known amount or a rate.
     * If this property is not present, then the rate derived from the {@code rate} property applies during the stub.
     * If this property is present and there is no initial stub, it is ignored.
     * @param initialStub  the new value
     * @return this, for chaining, not null
     */
    public Builder initialStub(FixedRateStubCalculation initialStub) {
      this.initialStub = initialStub;
      return this;
    }

    /**
     * Sets the final stub, optional.
     *

     * The final stub of a swap may have a different rate from the regular accrual periods.
     * This property allows the stub rate to be specified, either as a known amount or a rate.
     * If this property is not present, then the rate derived from the {@code rate} property applies during the stub.
     * If this property is present and there is no initial stub, it is ignored.
     * @param finalStub  the new value
     * @return this, for chaining, not null
     */
    public Builder finalStub(FixedRateStubCalculation finalStub) {
      this.finalStub = finalStub;
      return this;
    }

    /**
     * Sets the future value notional.
     *

     * This property is used when the fixed leg of a swap has a future value notional.
     * This is typically used for Brazilian swaps.
     * @param futureValueNotional  the new value
     * @return this, for chaining, not null
     */
    public Builder futureValueNotional(FutureValueNotional futureValueNotional) {
      this.futureValueNotional = futureValueNotional;
      return this;
    }

    //-----------------------------------------------------------------------
    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(192);
      buf.append("FixedRateCalculation.Builder{");
      buf.append("dayCount").append('=').append(JodaBeanUtils.toString(dayCount)).append(',').append(' ');
      buf.append("rate").append('=').append(JodaBeanUtils.toString(rate)).append(',').append(' ');
      buf.append("initialStub").append('=').append(JodaBeanUtils.toString(initialStub)).append(',').append(' ');
      buf.append("finalStub").append('=').append(JodaBeanUtils.toString(finalStub)).append(',').append(' ');
      buf.append("futureValueNotional").append('=').append(JodaBeanUtils.toString(futureValueNotional));
      buf.append('}');
      return buf.toString();
    }

  }

  //-------------------------- AUTOGENERATED END --------------------------
}


text:
/*
 * Created by SharpDevelop.
 * User: alex
 * Date: 23.01.2014
 * Time: 22:20
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;

namespace KegelApp.Server.Domain.Entities
{
	[Serializable]
	public class Shot
	{
		public virtual int Id {get; protected set;}
		public virtual bool NullShot {get; set;}
		public virtual bool Fault {get; set;}
		public virtual int Value {get; set;}

	   // public virtual Move InMove { get; set; }
	}
}


text:
import collections
import glob
import os
import pandas as pd
import shutil
import toolz as tz

from bcbio import utils
from bcbio import broad
from bcbio.broad.metrics import PicardMetricsParser, PicardMetrics
from bcbio import bam
from bcbio.distributed.transaction import tx_tmpdir
from bcbio.provenance import do
from bcbio.pipeline import datadict as dd

def run(bam_file, data, out_dir):
    config = data["config"]
    if "picard" not in dd.get_tools_on(data):
        return {}
    ref_file = dd.get_ref_file(data)
    sample = dd.get_sample_name(data)
    target_file = dd.get_variant_regions(data)
    broad_runner = broad.PicardCmdRunner("picard", config)
    bam_fname = os.path.abspath(bam_file)
    path = os.path.dirname(bam_fname)
    utils.safe_makedir(out_dir)
    hsmetric_file = os.path.join(out_dir, "%s-sort.hs_metrics" % sample)
    hsinsert_file = os.path.join(out_dir, "%s-sort.insert_metrics" % sample)
    if utils.file_exists(hsmetric_file):
        return hsmetric_file
    with utils.chdir(out_dir):
        with tx_tmpdir() as tmp_dir:
            cur_bam = os.path.basename(bam_fname)
            if not os.path.exists(cur_bam):
                os.symlink(bam_fname, cur_bam)
            gen_metrics = PicardMetrics(broad_runner, tmp_dir)
            gen_metrics.report(cur_bam, ref_file,
                               bam.is_paired(bam_fname),
                               target_file, target_file, None, config)
    do.run("sed -i 's/-sort.bam//g' %s" % hsmetric_file, "")
    do.run("sed -i 's/-sort.bam//g' %s" % hsinsert_file, "")
    return hsmetric_file


text:
define([
	"dojo/_base/lang",
	"dojo/_base/sniff"
], function(lang, has){
	// module:
	//		dojox/mobile/compat

	var dm = lang.getObject("dojox.mobile", true);
	if(!has("webkit")){
		var s = "dojox/mobile/_compat"; // assign to a variable so as not to be picked up by the build tool
		require([s]);
	}

	/*=====
	return {
		// summary:
		//		CSS3 compatibility module.
		// description:
		//		This module provides to dojox/mobile support for some of the CSS3 features
		//		in non-CSS3 browsers, such as IE or Firefox.
		//		If you require this module, when running in a non-CSS3 browser it directly
		//		replaces some of the methods of	dojox/mobile classes, without any subclassing.
		//		This way, HTML pages remain the same regardless of whether this compatibility
		//		module is used or not.
		//
		//		Example of usage:
		//		|	require([
		//		|		"dojox/mobile",
		//		|		"dojox/mobile/compat",
		//		|		...
		//		|	], function(...){
		//		|		...
		//		|	});
		//
		//		This module also loads compatibility CSS files, which have a -compat.css
		//		suffix. You can use either the `<link>` tag or `@import` to load theme
		//		CSS files. Then, this module searches for the loaded CSS files and loads
		//		compatibility CSS files. For example, if you load dojox/mobile/themes/iphone/iphone.css
		//		in a page, this module automatically loads dojox/mobile/themes/iphone/iphone-compat.css.
		//		If you explicitly load iphone-compat.css with `<link>` or `@import`,
		//		this module will not load again the already loaded file.
		//
		//		Note that, by default, compatibility CSS files are only loaded for CSS files located
		//		in a directory containing a "mobile/themes" path. For that, a matching is done using
		//		the default pattern	"/\/mobile\/themes\/.*\.css$/". If a custom theme is not located
		//		in a directory containing this path, the data-dojo-config needs to specify a custom
		//		pattern using the "mblLoadCompatPattern" configuration parameter, for instance:
		// |	data-dojo-config="mblLoadCompatPattern: /\/mycustomtheme\/.*\.css$/"
	};
	=====*/
	return dm;
});


text:
<?php
namespace Lobby\Module;

use \Lobby\UI\Panel;

class app_downloader extends \Lobby\Module {

  public function init(){
    $this->app->downloadExists();

    if(isset($_POST["dName"]) && isset($_POST['newDInfo'])){
      $dName = $_POST["dName"];
      $newDInfo = json_decode($_POST["newDInfo"], true);

      if($this->app->downloadExists($dName)){
        $dInfo = $this->app->data->getArray($dName);

        if($dInfo["paused"] == "1"){
          echo "paused";
        }else{
          $this->app->data->saveArray($dName, $newDInfo);
        }
      }else{
        echo "cancelled";
      }
      $this->app->data->saveValue("lastDownloadStatusCheck", time());

      /**
       * We don't need to completely load Lobby.
       * So terminate
       */
      exit;
    }else if($this->app->isDownloadRunning()){
      $this->addDownloadNotifyItem();
    }else if($this->app->data->getValue("startOnLobbyOpen") === "1" && count($this->app->getActiveDownloads()) !== 0){
      /**
       * Start all active downloads
       */
      $moduleInit = 1;
      $this->app->inc("src/ar/init.php", array(
        "moduleInit" => true
      ));
    }else{
      /**
       * All downloads have been completed, so remove Notify item
       */
      $this->app->panel->removeNotifyItem("download_info");
    }
  }

  public function addDownloadNotifyItem(){
    $percentage = 1;
    foreach($this->app->getActiveDownloads() as $dInfo){
      $percentage *= $dInfo["percentage"] / 100;
    }

    /**
     * Get the combined percentage
     */
    $percentage *= 100;

    $this->app->panel->addNotifyItem("download_info", array(
      "contents" => "Downloading - ". round($percentage, 2) ."%

",
      "iconURL" => $this->app->srcURL . "/src/image/logo.svg"
    ));
  }

}


text:
var expect = require("chai").expect;
var chainSinon = require("../chainSinon");

describe("chainSinon", function() {

	it("stubs one call", function() {
		var stubs = chainSinon("one");
		expect(stubs.oneObj).to.be.an("object");
		expect(stubs.one()).to.be.an("object");
	});

	it("stubs a string with multiple calls", function() {
		var stubs = chainSinon("first.second.third");
		expect(stubs.first()).to.be.an("object");
		expect(stubs.first().second()).to.be.an("object");
		expect(stubs.first().second().third()).to.be.an("object");
		expect(stubs.firstObj).to.be.an("object");
		expect(stubs["first.secondObj"]).to.be.an("object");
		expect(stubs["first.second.thirdObj"]).to.be.an("object");
	});

	it("stubs an array of strings", function() {
		var stubs = chainSinon(["one.thing", "another"]);
		expect(stubs.one()).to.be.an("object");
		expect(stubs.one().thing()).to.be.an("object");
		expect(stubs.another()).to.be.an("object");
		expect(stubs["one.thingObj"]).to.be.an("object");
		expect(stubs["anotherObj"]).to.be.an("object");
	});

	describe("custom objects", function() {
		var TestObject = (function() {
			function TestObject() {}
			TestObject.prototype.a = function() {
				return 'a';
			};
			TestObject.prototype.b = function() {
				return 'b';
			};
			return TestObject;
		})();

		it('stubs methods of the object', function() {
			var obj = new TestObject();
			var stubs = chainSinon(obj, ["a", "b"]);
			stubs.a.returns(4);
			expect(stubs.aObj).to.be.an("object");
			expect(stubs.bObj).to.be.an("object");
			expect(obj.a()).to.equal(4);
		});

		it('stubs sub-methods of the object', function() {
			var obj = new TestObject();
			var stubs = chainSinon(obj, ["a.b.c", "b"]);
			stubs['a.b.c'].returns(4);
			expect(stubs["a.b.cObj"]).to.be.an("object");
			expect(obj.a().b().c()).to.equal(4);
		});

		it('restores to the original implementation', function() {
			var obj = new TestObject();
			var stubs = chainSinon(obj, "a.b.c");
			// restoring brings back the original implementation:
			expect(obj.a()).to.be.an("object");
			obj.a.restore();
			expect(obj.a()).to.equal('a');
		});
	});
});


text:
class QQmlEngine;
class QJsEngine;

namespace com { namespace cutehacks { namespace duperagent {

class ResponseType : public QObject {
    Q_OBJECT
    Q_ENUMS(Types)
public:
    enum Types {
        Auto        = 0,
        Text        = 1,
        Json        = 2,
        Blob        = 3,
        ArrayBuffer = 4
    };
};

class Request : public QObject
{
    Q_OBJECT

public:
    Request(QQmlEngine *engine, QObject *parent = 0);

    Q_PROPERTY(QJSValue cookie READ cookie WRITE setCookie)

    Q_INVOKABLE void config(const QJSValue &);

    Q_INVOKABLE QJSValue get(const QJSValue&,
                              const QJSValue& = QJSValue(),
                              const QJSValue& = QJSValue()) const;
    Q_INVOKABLE QJSValue head(const QJSValue&,
                              const QJSValue& = QJSValue(),
                              const QJSValue& = QJSValue()) const;
    Q_INVOKABLE QJSValue del(const QJSValue&,
                              const QJSValue& = QJSValue()) const;
    Q_INVOKABLE QJSValue patch(const QJSValue&,
                              const QJSValue& = QJSValue(),
                              const QJSValue& = QJSValue()) const;
    Q_INVOKABLE QJSValue post(const QJSValue&,
                              const QJSValue& = QJSValue(),
                              const QJSValue& = QJSValue()) const;
    Q_INVOKABLE QJSValue put(const QJSValue&,
                              const QJSValue& = QJSValue(),
                              const QJSValue& = QJSValue()) const;

    QJSValue cookie() const;
    void setCookie(const QJSValue &);

    Q_INVOKABLE void clearCookies();

private:
    QQmlEngine *m_engine;
};

} } }

#endif // DUPERAGENT_H


text:
package org.apache.calcite.interpreter;

import org.apache.calcite.rel.core.Filter;

import com.google.common.collect.ImmutableList;

/**
 * Interpreter node that implements a
 * {@link org.apache.calcite.rel.core.Filter}.
 */
public class FilterNode extends AbstractSingleNode<Filter> {
  private final Scalar condition;
  private final Context context;

  public FilterNode(Interpreter interpreter, Filter rel) {
    super(interpreter, rel);
    this.condition =
        interpreter.compile(ImmutableList.of(rel.getCondition()),
            rel.getInputs());
    this.context = interpreter.createContext();
  }

  public void run() throws InterruptedException {
    Row row;
    while ((row = source.receive()) != null) {
      context.values = row.getValues();
      Boolean b = (Boolean) condition.execute(context);
      if (b != null && b) {
        sink.send(row);
      }
    }
  }
}

// End FilterNode.java


text:
using System;
using System.IO;
using System.Xml;
using Carbonfrost.Commons.PropertyTrees;

namespace Tests {

    public abstract class TestBase {

        protected static PropertyTree LoadTree(string fileName) {
            return PropertyTree.FromFile(GetContentPath(fileName));
        }

        protected static PropertyTreeReader LoadContent(string fileName) {
			if (fileName.EndsWith(".xml", StringComparison.Ordinal))
				return PropertyTreeReader.CreateXml(GetContentPath(fileName));
			else
				throw new NotImplementedException();
        }

        protected static string GetContentPath(string fileName) {
            return Path.Combine("./Content/", fileName);
        }

        protected static XmlReader GetXmlReader(string fileName) {
            return XmlReader.Create(Path.Combine("./Content/", fileName));
        }

        protected static string GetContent(string fileName) {
            return File.ReadAllText(GetContentPath(fileName));
        }

    }
}


text:
package com.qihoo360.replugin.loader.a;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;

import com.qihoo360.replugin.RePluginInternal;
import com.qihoo360.replugin.helper.LogRelease;

import java.lang.reflect.Field;

/**
 * @author RePlugin Team
 */
public abstract class PluginAppCompatActivity extends AppCompatActivity {

    @Override
    protected void attachBaseContext(Context newBase) {
        newBase = RePluginInternal.createActivityContext(this, newBase);
        super.attachBaseContext(newBase);
    }

    @Override
    public Context getBaseContext() {

        return super.getBaseContext();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //
        RePluginInternal.handleActivityCreateBefore(this, savedInstanceState);

        super.onCreate(savedInstanceState);

        //
        RePluginInternal.handleActivityCreate(this, savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        //
        RePluginInternal.handleActivityDestroy(this);

        super.onDestroy();
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        //
        RePluginInternal.handleRestoreInstanceState(this, savedInstanceState);

        try {
            super.onRestoreInstanceState(savedInstanceState);
        } catch (Throwable e) {
            // Added by Jiongxuan Zhang
            // Crash Hash: B1F67129BC6A67C882AF2BBE62202BF0
            // java.lang.IllegalArgumentException: Wrong state class异常
            // 原因:恢复现场时,Activity坑位找错了。通常是用于占坑的Activity的层级过深导致
            // 举例:假如我们只有一个坑位可用,A和B分别是清理和通讯录的两个Activity
            //      如果进程重启,系统原本恢复B,却走到了A,从而出现此问题
            // 解决:将其Catch住,这样系统在找ViewState时不会出错。
            // 后遗症:
            // 1、可能无法恢复系统级View的保存的状态;
            // 2、如果自己代码处理不当,可能会出现异常。故自己代码一定要用SecExtraUtils来获取Bundle数据
            if (LogRelease.LOGR) {
                LogRelease.e("PluginFragmentActivity", "o r i s: p=" + getPackageCodePath() + "; " + e.getMessage(), e);
            }
        }
    }

    @Override
    public void startActivity(Intent intent) {
        //
        if (RePluginInternal.startActivity(this, intent)) {
            // 这个地方不需要回调startActivityAfter,因为RePluginInternal最终还是会回调回来,最终还是要走super.startActivity()
            return;
        }

        super.startActivity(intent);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode, null);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        //
        if (RePluginInternal.startActivityForResult(this, intent, requestCode, options)) {
            return;
        }

        if (Build.VERSION.SDK_INT >= 16) {
            super.startActivityForResult(intent, requestCode, options);
        } else {
            super.startActivityForResult(intent, requestCode);
        }
    }

    /**
     * 这里的做法是支持Fragment中调用startActivityForResult特性
     * <p>
     * 由于卫士的插件需要hook住XXX-Activity的startActivity和startActivityForResult接口
     * 但早期版本的support-v4在startActivityFromFragment中直接调用了super.startActivityForResult, 因此这里还需要hook住这个点
     * 但新版的support-v4中Fragment最终的调用链还是会走到本XXX-Activity的startActivityForResult接口,因此不需要适配startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, @Nullable Bundle options)接口
     *
     * @param fragment
     * @param intent
     * @param requestCode
     */
    @Override
    public void startActivityFromFragment(Fragment fragment, Intent intent, int requestCode) {
        if (requestCode == -1) {
            startActivityForResult(intent, -1);
        } else if ((requestCode & -65536) != 0) {
            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
        } else {
            int newRequestCode = -1;
            try {
                Field f = Fragment.class.getDeclaredField("mIndex");
                boolean acc = f.isAccessible();
                if (!acc) {
                    f.setAccessible(true);
                }
                Object o = f.get(fragment);
                if (!acc) {
                    f.setAccessible(acc);
                }
                int index = (Integer) o;
                newRequestCode = ((index + 1) << 16) + (requestCode & '\uffff');
            } catch (Throwable e) {
                // Do Noting
            }
            startActivityForResult(intent, newRequestCode);
        }
    }

    @Override
    public String getPackageCodePath() {
        return super.getPackageCodePath();
    }
}


text:
layout: post
title: Blue Angel And Sasha Rose
titleinfo: pornvd
desc: Watch Blue Angel And Sasha Rose. Pornhub is the ultimate xxx porn and sex site.
---

Blue Angel And Sasha Rose

Watch Blue Angel And Sasha Rose. Pornhub is the ultimate xxx porn and sex site.


text:
<?php

namespace App\Console\Commands;

use App\Image;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;

class DeleteDuplicates extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'foto:deleteduplicates';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Find and delete duplicates';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $duplicateList = DB::select( 'select * from images group by file_hash having count(*) > 1' );
        //   echo count($duplicateList);
        foreach ( $duplicateList as $record ) {
            $file = $record->path . '/' . $record->file_name;

            echo $file . "\n";

            Image::destroy($record->id);
            exec('rm "'.$file.'" ');

        }
        //   DB::Select()

        /* $files = File::allFiles( Config::get( 'images.source_path' ) );
         $extensions = [ ];
         foreach ( $files as $file ) {
             $extension = strtolower(pathinfo( $file, PATHINFO_EXTENSION ));
             @$extensions[ $extension ] += 1;
             if ($extension != 'jpg')
                 echo $file."\n";
         }
        */
        // print_R($extensions);
    }
}


text:
import * as ZennObject from '../toolbox/ZennObject';
import * as Lodash from '../tree-shakers/lodash';
import QueryString from 'qs';
import { zennHistory as errors } from '../errors';

const methods = ZennObject.flatDataStorage.create({
    push    : 'pushState',
    replace : 'replaceState',
});

/**
 * @type {{ state: (()), title: (()), url: (()), protocol: (()), queryObject: (()) }}
 */
const CURRENT = {

    /**
     * Returns the state object of the current history state.
     *
     * @returns {Object}
     */
    state() {
        return window.history.state;
    },

    /**
     * Returns the document title of the current history state.
     *
     * @returns {string}
     */
    title() {
        return document.title.toString();
    },

    /**
     * Returns the current URL of the browser tab.
     *
     * @returns {string}
     */
    url() {
        return window.location.href;
    },

    /**
     * Returns the protocol of the current connection.
     *
     * @returns {string}
     */
    protocol() {
        return window.location.protocol;
    },

    /**
     * Returns the query-string - parsed to an object - of the current URL.
     */
    queryObject() {
        return QueryString.parse(window.location.search.replace(/^\?/, ''));
    },
};

/**
 * @class HistoryAction
 *
 * @property {string} method - The name of the method of the History API this object should address.
 */
class HistoryAction {

    /**
     * @param {string} method - The name of the method of the History API this object should address.
     */
    constructor(method) {
        if (! Lodash.isFunction(window.history[method])) {
            throw new Error(errors.historyMethodError(method));
        }
        this.method = method;
    }

    /**
     *
     * @param {Object} params - The object representation of the query string to assign to the URL.
     */
    replaceQuery(params = {}) {
        this.run({ url: '?' + QueryString.stringify(params) });
    }

    /**
     *
     * @param {Object} params - The object representation of the query parameters to append to
     *                          the existing query-string.
     *
     * @param {boolean} overrideExisting
     */
    assignQuery(params = {}, overrideExisting = true) {

        let currentParams   = CURRENT.queryObject();
        let newParams       = overrideExisting
            ? ZennObject.assign.hard.recursive(currentParams, params)
            : ZennObject.assign.soft.recursive(currentParams, params);

        this.run({ url: '?' + QueryString.stringify(newParams) });
    }

    /**
     * @param {object} arguments
     * @param {object} [arguments.data]
     * @param {string} [arguments.title]
     * @param {string} [arguments.url]
     */
    run({ data = CURRENT.state(), title = CURRENT.title(), url = CURRENT.url() }) {
        window.history[this.method](data, title, url);
    }
}

/** @type {HistoryAction} */
export const PUSH = new HistoryAction(methods.push);

/** @type {HistoryAction} */
export const REPLACE = new HistoryAction(methods.replace);


text:
package org.apache.catalina.core;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.junit.Assert;
import org.junit.Test;

import org.apache.catalina.Context;
import org.apache.catalina.startup.Constants;
import org.apache.catalina.startup.ContextConfig;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.catalina.util.IOTools;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.descriptor.web.WebXml;

public class TestStandardContextResources extends TomcatBaseTest {

    @Override
    public void setUp() throws Exception {
        super.setUp();

        Tomcat tomcat = getTomcatInstance();

        // BZ 49218: The test fails if JreMemoryLeakPreventionListener is not
        // present. The listener affects the JVM, and thus not only the current,
        // but also the subsequent tests that are run in the same JVM. So it is
        // fair to add it in every test.
        tomcat.getServer().addLifecycleListener(
                new JreMemoryLeakPreventionListener());
    }

    @Test
    public void testResources() throws Exception {
        Tomcat tomcat = getTomcatInstance();

        File appDir = new File("test/webapp-fragments");
        // app dir is relative to server home
        Context ctx = tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());

        tomcat.start();

        assertPageContains("/test/resourceA.jsp",
                "
resourceA.jsp in the web application
");
        assertPageContains("/test/resourceB.jsp",
                "
resourceB.jsp in resources.jar
");
        assertPageContains("/test/folder/resourceC.jsp",
                "
resourceC.jsp in the web application
");
        assertPageContains("/test/folder/resourceD.jsp",
                "
resourceD.jsp in resources.jar
");
        assertPageContains("/test/folder/resourceE.jsp",
                "
resourceE.jsp in the web application
");
        assertPageContains("/test/resourceG.jsp",
                "
resourceG.jsp in WEB-INF/classes
", 404);

        // For BZ 54391. Relative ordering is specified in resources2.jar.
        // It is not absolute-ordering, so there may be other jars in the list
        @SuppressWarnings("unchecked")
        List<String> orderedLibs = (List<String>) ctx.getServletContext()
                .getAttribute(ServletContext.ORDERED_LIBS);
        if (orderedLibs.size() > 2) {
            log.warn("testResources(): orderedLibs: " + orderedLibs);
        }
        int index = orderedLibs.indexOf("resources.jar");
        int index2 = orderedLibs.indexOf("resources2.jar");
        Assert.assertTrue(orderedLibs.toString(), index >= 0 && index2 >= 0
                && index < index2);
    }

    @Test
    public void testResourcesWebInfClasses() throws Exception {
        Tomcat tomcat = getTomcatInstance();

        // app dir is relative to server home
        File appDir = new File("test/webapp-fragments");

        // Need to cast to be able to set StandardContext specific attribute
        StandardContext ctxt = (StandardContext)
            tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
        ctxt.setAddWebinfClassesResources(true);

        tomcat.start();

        assertPageContains("/test/resourceA.jsp",
                "
resourceA.jsp in the web application
");
        assertPageContains("/test/resourceB.jsp",
                "
resourceB.jsp in resources.jar
");
        assertPageContains("/test/folder/resourceC.jsp",
                "
resourceC.jsp in the web application
");
        assertPageContains("/test/folder/resourceD.jsp",
                "
resourceD.jsp in resources.jar
");
        assertPageContains("/test/folder/resourceE.jsp",
                "
resourceE.jsp in the web application
");
        assertPageContains("/test/resourceG.jsp",
                "
resourceG.jsp in WEB-INF/classes
");
    }

    @Test
    public void testResourcesAbsoluteOrdering() throws Exception {
        Tomcat tomcat = getTomcatInstance();
        File appDir = new File("test/webapp-fragments");

        AbsoluteOrderContextConfig absoluteOrderConfig = new AbsoluteOrderContextConfig();

        // app dir is relative to server home
        StandardContext ctx = (StandardContext) tomcat.addWebapp(null, "/test",
                appDir.getAbsolutePath(), absoluteOrderConfig);

        Tomcat.addServlet(ctx, "getresource", new GetResourceServlet());
        ctx.addServletMappingDecoded("/getresource", "getresource");

        tomcat.start();
        assertPageContains("/test/getresource?path=/resourceF.jsp",
        "
resourceF.jsp in resources2.jar
");
        assertPageContains("/test/getresource?path=/resourceB.jsp",
        "
resourceB.jsp in resources.jar
");

        // Check ordering, for BZ 54391
        Assert.assertEquals(Arrays.asList("resources.jar", "resources2.jar"), ctx
                .getServletContext().getAttribute(ServletContext.ORDERED_LIBS));

        tomcat.getHost().removeChild(ctx);
        tomcat.getHost().stop();

        // change ordering
        absoluteOrderConfig.swap();

        ctx = (StandardContext) tomcat.addWebapp(null, "/test",
                appDir.getAbsolutePath(), absoluteOrderConfig);
        Tomcat.addServlet(ctx, "getresource", new GetResourceServlet());
        ctx.addServletMappingDecoded("/getresource", "getresource");

        tomcat.getHost().start();

        assertPageContains("/test/getresource?path=/resourceF.jsp",
        "
resourceF.jsp in resources2.jar
");
        assertPageContains("/test/getresource?path=/resourceB.jsp",
        "
resourceB.jsp in resources2.jar
");

        // Check ordering, for BZ 54391
        Assert.assertEquals(Arrays.asList("resources2.jar", "resources.jar"), ctx
                .getServletContext().getAttribute(ServletContext.ORDERED_LIBS));
    }

    public static class AbsoluteOrderContextConfig extends ContextConfig {

        private boolean swap = false;

        public AbsoluteOrderContextConfig() {
            super();
            // Prevent it from looking (if it finds one - it'll have dup error)
            setDefaultWebXml(Constants.NoDefaultWebXml);
        }

        @Override
        protected WebXml createWebXml() {
            WebXml wxml = new WebXml();
            if (swap) {
                wxml.addAbsoluteOrdering("resources2");
                wxml.addAbsoluteOrdering("resources");
            } else {
                wxml.addAbsoluteOrdering("resources");
                wxml.addAbsoluteOrdering("resources2");
            }
            return wxml;
        }

        protected void swap() {
            swap = !swap;
        }
    }

    @Test
    public void testResources2() throws Exception {
        Tomcat tomcat = getTomcatInstance();

        File appDir = new File("test/webapp-fragments");
        // app dir is relative to server home
        StandardContext ctx = (StandardContext) tomcat.addWebapp(null, "/test",
                appDir.getAbsolutePath());
        skipTldsForResourceJars(ctx);

        Tomcat.addServlet(ctx, "getresource", new GetResourceServlet());
        ctx.addServletMappingDecoded("/getresource", "getresource");

        tomcat.start();

        assertPageContains("/test/getresource?path=/resourceF.jsp",
                "
resourceF.jsp in resources2.jar
");
        assertPageContains("/test/getresource?path=/resourceA.jsp",
                "
resourceA.jsp in the web application
");
        assertPageContains("/test/getresource?path=/resourceB.jsp",
                "
resourceB.jsp in resources.jar
");
        assertPageContains("/test/getresource?path=/folder/resourceC.jsp",
                "
resourceC.jsp in the web application
");
        assertPageContains("/test/getresource?path=/folder/resourceD.jsp",
                "
resourceD.jsp in resources.jar
");
        assertPageContains("/test/getresource?path=/folder/resourceE.jsp",
                "
resourceE.jsp in the web application
");
    }

    /**
     * A servlet that prints the requested resource. The path to the requested
     * resource is passed as a parameter, path.
     */
    public static class GetResourceServlet extends HttpServlet {

        private static final long serialVersionUID = 1L;

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {

            resp.setContentType("text/plain");

            ServletContext context = getServletContext();

            // Check resources individually
            URL url = context.getResource(req.getParameter("path"));
            if (url == null) {
                resp.getWriter().println("Not found");
                return;
            }

            try (InputStream input = url.openStream();
                    OutputStream output = resp.getOutputStream()) {
                IOTools.flow(input, output);
            }
        }
    }

    private void assertPageContains(String pageUrl, String expectedBody)
            throws IOException {

        assertPageContains(pageUrl, expectedBody, 200);
    }

    private void assertPageContains(String pageUrl, String expectedBody,
            int expectedStatus) throws IOException {
        ByteChunk res = new ByteChunk();
        int sc = getUrl("http://localhost:" + getPort() + pageUrl, res, null);

        Assert.assertEquals(expectedStatus, sc);

        if (expectedStatus == 200) {
            String result = res.toString();
            Assert.assertTrue(result, result.indexOf(expectedBody) > 0);
        }
    }
}


text:
using namespace std;
using namespace MarkovChannel;

using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::ZeroCopyOutputStream;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::Message;

int print_ic (Graph::Graph& G)
{
  double* ic = (double*) calloc(2*G.E*G.N, sizeof(double));
  for(int i=0; i<G.E; i++) {
    Graph::Edge& e = G.edges[i];
    ic[2*G.E*e.V1 + 2*i] = -1;
    ic[2*G.E*e.V2 + 2*i] = 1;
    ic[2*G.E*e.V1 + 2*i+1] = 1;
    ic[2*G.E*e.V2 + 2*i+1] = -1;
  }
  for (int i=0; i<G.N; i++) {
    for (int j=0; j<2*G.E; j++) {
      printf("%8.4f\t", ic[i*2*G.E+j]);
    }
    printf("\n");
  }
  free(ic);
}

void print_mat (double* A, int n, int m) {
  for (int i=0; i<n; i++) {
    for (int j=0; j<m; j++) {
      printf("%8.4f\t", A[i*m+j]);
    }
    printf("\n");
  }
}

MarkovChannel::SolverParameter solver_param;
vector<ChannelProtocol> protos;

double cost_f(Model::Model* m, ostream* os)
{
  return cost(*m, protos, solver_param, os);
}

void load_protocols(char *protolst)
{
  char datapath[PATH_MAX+1];
  realpath(protolst, datapath);
  std::ifstream protofile;
  protofile.open(protolst);

  std::string p1(datapath);
  int i = p1.size() - 1;
  while (p1[i] != '/') i--;
  std::string pth = p1.substr(0, i+1);

  std::string line;
  while ( protofile >> line ) {
    std::cout << pth+line << std::endl;
    std::string proto_file = pth + line;
    protos.push_back(ChannelProtocol(proto_file));
  }
}

int main(int argc, char* argv[])
{

  // google told me to do this
  GOOGLE_PROTOBUF_VERIFY_VERSION;
  Math::init_stream(time(NULL));

  int fd = open(argv[1], O_RDONLY);
  FileInputStream* input = new FileInputStream(fd);

  google::protobuf::TextFormat::Parse(input, &solver_param);
  Model::prms = solver_param.model_param(); delete input;
  load_protocols(argv[2]);

  vector<Model::Model*> models;
  MarkovChannel::SAParameter sa_param = solver_param.sa_param();
  SimulatedAnnealing::solve(cost_f, sa_param);

  // google told me to do this too
  google::protobuf::ShutdownProtobufLibrary();
  exit(0);

}