text:
import { formatTime } from './helpers';
import diffLogger from './diff';

/**
 * Get log level string based on supplied params
 *
 * @param {string | function | object} level - console[level]
 * @param {object} action - selected action
 * @param {array} payload - selected payload
 * @param {string} type - log entry type
 *
 * @returns {string} level
 */
function getLogLevel(level, action, payload, type) {
  switch (typeof level) {
    case `object`:
      return typeof level[type] === `function` ? level[type](...payload) : level[type];
    case `function`:
      return level(action);
    default:
      return level;
  }
}

function defaultTitleFormatter(options) {
  const {
    timestamp,
    duration,
  } = options;

  return (action, time, took) => {
    const parts = [`action`];

    if (timestamp) parts.push(`@ ${time}`);
    parts.push(String(action.type));
    if (duration) parts.push(`(in ${took.toFixed(2)} ms)`);

    return parts.join(` `);
  };
}

export function printBuffer(buffer, options) {
  const {
    logger,
    actionTransformer,
    titleFormatter = defaultTitleFormatter(options),
    collapsed,
    colors,
    level,
    diff,
  } = options;

  buffer.forEach((logEntry, key) => {
    const { started, startedTime, action, prevState, error } = logEntry;
    let { took, nextState } = logEntry;
    const nextEntry = buffer[key + 1];

    if (nextEntry) {
      nextState = nextEntry.prevState;
      took = nextEntry.started - started;
    }

    // Message
    const formattedAction = actionTransformer(action);
    const isCollapsed = (typeof collapsed === `function`) ? collapsed(() => nextState, action, logEntry) : collapsed;

    const formattedTime = formatTime(startedTime);
    const titleCSS = colors.title ? `color: ${colors.title(formattedAction)};` : null;
    const title = titleFormatter(formattedAction, formattedTime, took);

    // Render
    try {
      if (isCollapsed) {
        if (colors.title) logger.groupCollapsed(`%c ${title}`, titleCSS);
        else logger.groupCollapsed(title);
      } else {
        if (colors.title) logger.group(`%c ${title}`, titleCSS);
        else logger.group(title);
      }
    } catch (e) {
      logger.log(title);
    }

    const prevStateLevel = getLogLevel(level, formattedAction, [prevState], `prevState`);
    const actionLevel = getLogLevel(level, formattedAction, [formattedAction], `action`);
    const errorLevel = getLogLevel(level, formattedAction, [error, prevState], `error`);
    const nextStateLevel = getLogLevel(level, formattedAction, [nextState], `nextState`);

    if (prevStateLevel) {
      if (colors.prevState) logger[prevStateLevel](`%c prev state`, `color: ${colors.prevState(prevState)}; font-weight: bold`, prevState);
      else logger[prevStateLevel](`prev state`, prevState);
    }

    if (actionLevel) {
      if (colors.action) logger[actionLevel](`%c action`, `color: ${colors.action(formattedAction)}; font-weight: bold`, formattedAction);
      else logger[actionLevel](`action`, formattedAction);
    }

    if (error && errorLevel) {
      if (colors.error) logger[errorLevel](`%c error`, `color: ${colors.error(error, prevState)}; font-weight: bold`, error);
      else logger[errorLevel](`error`, error);
    }

    if (nextStateLevel) {
      if (colors.nextState) logger[nextStateLevel](`%c next state`, `color: ${colors.nextState(nextState)}; font-weight: bold`, nextState);
      else logger[nextStateLevel](`next state`, nextState);
    }

    if (diff) {
      diffLogger(prevState, nextState, logger, isCollapsed);
    }

    try {
      logger.groupEnd();
    } catch (e) {
      logger.log(`—— log end ——`);
    }
  });
}


text:
package validate

import (
	"io"

	"github.com/spf13/cobra"
	"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)

const (
	ValidateRecommendedName = "validate"

	validateDeprecationMessage = `and will be removed. Use "oc adm diagnostics" to run configuration validations instead.
See sub-command help text for specific instructions with "oc adm diagnostics".`
)

var validateLong = templates.LongDesc(`
	Validate configuration file integrity

	The commands here allow administrators to validate the integrity of configuration files.`)

func NewCommandValidate(name, fullName string, out, errOut io.Writer) *cobra.Command {
	// Parent command to which all subcommands are added.
	cmds := &cobra.Command{
		Use:        name,
		Short:      "Validate configuration file integrity",
		Long:       validateLong,
		Deprecated: validateDeprecationMessage,
		Run:        cmdutil.DefaultSubCommandRun(errOut),
	}

	cmds.AddCommand(NewCommandValidateMasterConfig(ValidateMasterConfigRecommendedName,
		fullName+" "+ValidateMasterConfigRecommendedName, out))
	cmds.AddCommand(NewCommandValidateNodeConfig(ValidateNodeConfigRecommendedName,
		fullName+" "+ValidateNodeConfigRecommendedName, out))
	return cmds
}

redpajama_set_name: RedPajamaGithub


text:
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include "mldb/http/http_endpoint.h"
#include "mldb/soa/service/active_endpoint.h"
#include "mldb/soa/service/passive_endpoint.h"
#include <sys/socket.h>
#include "mldb/base/scope.h"
#include "mldb/arch/exception_handler.h"
#include "mldb/utils/testing/watchdog.h"
#include "mldb/jml/utils/testing/fd_exhauster.h"
#include "test_connection_error.h"

using namespace std;
using namespace ML;
using namespace MLDB;

BOOST_AUTO_TEST_CASE( test_active_endpoint_nothing_listening )
{
    Watchdog watchdog(60.0);  // give it a reasonable amount of time

    for (unsigned i = 0;  i < 50;  ++i) {
        BOOST_REQUIRE_EQUAL(TransportBase::created, TransportBase::destroyed);
        BOOST_REQUIRE_EQUAL(ConnectionHandler::created,
                            ConnectionHandler::destroyed);
        Watchdog watchdog;

        cerr << endl << "iter " << i << endl;
        ActiveEndpointT<SocketTransport> connector("connector");
        connector.init(9997, "localhost", 0, 1, true,
                       false /* throw on error */);
        doTestConnectionError(connector, "Connection refused",
                              "Timer expired");

        connector.sleepUntilIdle();
        connector.shutdown();

        BOOST_CHECK_EQUAL(connector.numActiveConnections(), 0);
        BOOST_CHECK_EQUAL(connector.numInactiveConnections(), 0);
        BOOST_CHECK_EQUAL(connector.threadsActive(), 0);
        BOOST_CHECK_EQUAL(TransportBase::created, TransportBase::destroyed);
        BOOST_CHECK_EQUAL(ConnectionHandler::created,
                          ConnectionHandler::destroyed);
    }
}


text:
/*
 * Please do not edit this file.
 * It was generated using rpcgen.
 */

#include "square.h"
#include <stdio.h>
#include <stdlib.h>
#include <rpc/pmap_clnt.h>
#include <string.h>
#include <memory.h>
#include <sys/socket.h>
#include <netinet/in.h>

#ifndef SIG_PF
#define SIG_PF void(*)(int)
#endif

static void
square_prog_1(struct svc_req *rqstp, register SVCXPRT *transp)
{
	union {
		square_in squareprog_1_arg;
	} argument;
	char *result;
	xdrproc_t _xdr_argument, _xdr_result;
	char *(*local)(char *, struct svc_req *);

	switch (rqstp->rq_proc) {
	case NULLPROC:
		(void) svc_sendreply (transp, (xdrproc_t) xdr_void, (char *)NULL);
		return;

	case SQUAREPROG:
		_xdr_argument = (xdrproc_t) xdr_square_in;
		_xdr_result = (xdrproc_t) xdr_square_out;
		local = (char *(*)(char *, struct svc_req *)) squareprog_1_svc;
		break;

	default:
		svcerr_noproc (transp);
		return;
	}
	memset ((char *)&argument, 0, sizeof (argument));
	if (!svc_getargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) {
		svcerr_decode (transp);
		return;
	}
	result = (*local)((char *)&argument, rqstp);
	if (result != NULL && !svc_sendreply(transp, (xdrproc_t) _xdr_result, result)) {
		svcerr_systemerr (transp);
	}
	if (!svc_freeargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) {
		fprintf (stderr, "%s", "unable to free arguments");
		exit (1);
	}
	return;
}

int
main (int argc, char **argv)
{
	register SVCXPRT *transp;

	pmap_unset (SQUARE_PROG, SQUARE_VERS);

	transp = svcudp_create(RPC_ANYSOCK);
	if (transp == NULL) {
		fprintf (stderr, "%s", "cannot create udp service.");
		exit(1);
	}
	if (!svc_register(transp, SQUARE_PROG, SQUARE_VERS, square_prog_1, IPPROTO_UDP)) {
		fprintf (stderr, "%s", "unable to register (SQUARE_PROG, SQUARE_VERS, udp).");
		exit(1);
	}

	transp = svctcp_create(RPC_ANYSOCK, 0, 0);
	if (transp == NULL) {
		fprintf (stderr, "%s", "cannot create tcp service.");
		exit(1);
	}
	if (!svc_register(transp, SQUARE_PROG, SQUARE_VERS, square_prog_1, IPPROTO_TCP)) {
		fprintf (stderr, "%s", "unable to register (SQUARE_PROG, SQUARE_VERS, tcp).");
		exit(1);
	}

	svc_run ();
	fprintf (stderr, "%s", "svc_run returned");
	exit (1);
	/* NOTREACHED */
}


text:
Dans quel pays ou région du monde devons-nous livrer ?

<select name="region" id="region-select" class="form-control">
    <option value="0">France Métropolitaine</option>
    <optgroup label="Europe">
        <option value="1">Allemagne</option>
        <option value="3">Autriche</option>
        <option value="1">Belgique</option>
        <option value="3">Danemark</option>
        <option value="2">Espagne</option>
        <option value="4">Finlande</option>
        <option value="2">Grande Bretagne</option>
        <option value="5">Grèce</option>
        <option value="5">Hongrie</option>
        <option value="3">Irlande</option>
        <option value="5">Islande</option>
        <option value="2">Italie</option>
        <option value="1">Luxembourg</option>
        <option value="4">Norvège</option>
        <option value="1">Pays Bas</option>
        <option value="5">Pologne</option>
        <option value="3">Portugal</option>
        <option value="5">République Tchèque</option>
        <option value="5">Slovaquie</option>
        <option value="5">Slovénie</option>
        <option value="2">Suisse</option>
        <option value="4">Suède</option>
        <option value="6">Autres pays d'europe</option>
    </optgroup>
        <optgroup label="Outre Mer">
        <option value="OM1">Guadeloupe</option>
        <option value="OM1">Martinique</option>
        <option value="OM1">Réunion</option>
        <option value="OM1">Guyanne</option>
        <option value="OM1">St. Pierre et Miquelon</option>
        <option value="OM2">Nouvelle Calédonie</option>
        <option value="OM2">Polynésie Française</option>
    </optgroup>
        <optgroup label="Amérique">
        <option value="7">USA</option>
        <option value="7">Canada</option>
        <option value="8">Amérique Centrale</option>
        <option value="8">Amérique du Sud</option>
    </optgroup>
    <optgroup label="Afrique">
        <option value="6">Algérie</option>
        <option value="6">Maroc</option>
        <option value="6">Tunisie</option>
        <option value="7">Afrique Centrale</option>
        <option value="7">Afrique Australe</option>
    </optgroup>
    <optgroup label="Asie">
        <option value="8">Chine</option>
        <option value="8">Corée</option>
        <option value="8">Japon</option>
        <option value="8">Thailande</option>
        <option value="8">Vietnam</option>
        <option value="8">Autre pays d'asie</option>
    </optgroup>
</select>


text:
<!DOCTYPE html>

    <title>FriendFace.com | Friends... with faces</title>
    <link type="text/css" rel="stylesheet" media="screen" href="css/ui-lightness/jquery-ui-1.8.17.custom.css" />

FriendFace

      <form id="new-friend" method="POST" action="">
        <fieldset>

            Add a friend!
            Update a friend!
            <input name="new-friend" type="text" data-id="" />
            <button> + </button>
            <button id="reset">Reset</button>

        </fieldset>
      </form>

Mark

Josh

Bryan

Jeff

      <button id="friend-count">How many friends do I have?</button>

Tab 1

Tab 2

Tab 3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate massa vel leo rutrum ut commodo quam dapibus. Etiam vel nulla felis, ut ultrices odio. Vivamus sed tortor mauris. Aliquam felis lorem, posuere eu blandit ac, rhoncus ac arcu. Nullam vel mauris at diam pretium tincidunt. Sed malesuada luctus enim vel ultrices. Vestibulum at mi eu enim consectetur feugiat. Suspendisse potenti. Phasellus pellentesque congue luctus. Donec sed augue augue. Vestibulum ultricies neque a tortor dictum tincidunt. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

Quisque tellus nunc, rhoncus sit amet venenatis at, pellentesque quis turpis. Donec vestibulum dolor ut nisi consequat vitae venenatis nisl aliquet. Pellentesque ipsum ante, volutpat non volutpat at, ultricies sit amet odio. Mauris condimentum commodo mi, vitae fringilla ante pulvinar et. Integer faucibus viverra diam, sit amet mattis nisl dapibus non. Morbi cursus pharetra commodo. Maecenas lobortis feugiat interdum. Maecenas arcu lacus, euismod ut porttitor id, sodales sed massa. Nulla posuere sapien nisl, tincidunt molestie ipsum. Phasellus quis est massa, vel hendrerit tellus. Integer a venenatis nibh. Suspendisse potenti. Pellentesque consequat augue quis sem consectetur mollis. Nulla volutpat cursus leo, vitae molestie elit varius ut. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Phasellus lacinia sollicitudin nunc at scelerisque. Sed sagittis, lacus quis vehicula ultricies, eros arcu pulvinar lectus, quis feugiat enim urna ut justo. Donec ut nunc ante. Nam sed ipsum massa, vitae consequat nunc. Phasellus imperdiet velit eget metus volutpat bibendum tempus felis pellentesque. Sed ligula est, tincidunt id blandit nec, molestie id lorem. Pellentesque eleifend mi non justo laoreet ornare non vel justo. In hac habitasse platea dictumst. Integer ut ligula eu augue ornare aliquet vel ac enim. Integer vehicula blandit nisl, ut pretium tortor pellentesque non. In volutpat, quam eu gravida tempus, eros turpis rhoncus velit, vitae consectetur mauris augue eu ipsum. Nullam sed mauris mi. Mauris ornare sem sed massa egestas quis sodales sapien molestie. Suspendisse ac eros nec libero scelerisque placerat elementum ut libero. Nam a dui et risus dignissim tempor. Integer quis odio et tellus convallis cursus id a mi.

      Shizzle my nizzle crocodizzle ipsizzle dolizzle sit fizzle, consectetuer adipiscing check it out. Nullam sapizzle velizzle, aliquet volutpizzle, suscipit quis, gravida vizzle, arcu. Pellentesque eget tortizzle. Sed erizzle. I'm in the shizzle crackalackin dolizzle check out this fo shizzle tempizzle shiznit. Mauris pellentesque nibh et stuff. Get down get down in tortizzle. Pellentesque eleifend gangster nisi. In hac that's the shizzle platea gangster. Shut the shizzle up dapibizzle. Curabitur dope shiznit, pretium i saw beyonces tizzles and my pizzle went crizzle, mattis bizzle, eleifend for sure, nunc. Fo suscipizzle. Integer yo mamma velit sizzle the bizzle.


text:
package com.orientechnologies.orient.core.index;

import com.orientechnologies.orient.core.collate.OCollate;
import com.orientechnologies.orient.core.collate.ODefaultCollate;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.OSQLEngine;
import com.orientechnologies.orient.core.type.ODocumentWrapperNoClass;

/**
 * Abstract index definiton implementation.
 *
 * @author Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 */
public abstract class OAbstractIndexDefinition extends ODocumentWrapperNoClass implements OIndexDefinition {
  protected OCollate collate = new ODefaultCollate();

  protected OAbstractIndexDefinition() {
    super(new ODocument());
  }

  public OCollate getCollate() {
    return collate;
  }

  public void setCollate(final OCollate collate) {
    if (collate == null)
      throw new IllegalArgumentException("COLLATE cannot be null");
    this.collate = collate;
  }

  public void setCollate(String iCollate) {
    if (iCollate == null)
      iCollate = ODefaultCollate.NAME;

    setCollate(OSQLEngine.getCollate(iCollate));
  }
}


text:
require 'yt'
require 'yt/url'

require 'slack-ruby-bot'

require 'commands/youtube'
require 'commands/url'

require 'bot'


text:
exercicio

* app que manipule a tabela users com pdo
 * crie mais tres usuarios
 * atualize um
 * exclua outro
 * liste os de id > 2 (parametro)


text:
require 'spec_helper'

describe NDFD::Client::SelectionAttributes do
  let(:attr) { :blah }

  subject { NDFD::Client::SelectionAttributes.new(attr) }

  describe "#valid?" do
    it "raises an error if an invalid selection attribute is used" do
      expect { subject.valid?(:wrong) }.to raise_error(NDFD::Client::InvalidSelectionAttributeError)
    end
  end
end


text:
package org.apache.ode.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.Statement;
import java.util.*;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;

public class LoggingInterceptor<T> implements InvocationHandler {

    private static final Set<String> PARAMSTYPES = new HashSet<String>();
    static {
        PARAMSTYPES.add("setArray");
        PARAMSTYPES.add("setBigDecimal");
        PARAMSTYPES.add("setBoolean");
        PARAMSTYPES.add("setByte");
        PARAMSTYPES.add("setBytes");
        PARAMSTYPES.add("setDate");
        PARAMSTYPES.add("setDouble");
        PARAMSTYPES.add("setFloat");
        PARAMSTYPES.add("setInt");
        PARAMSTYPES.add("setLong");
        PARAMSTYPES.add("setObject");
        PARAMSTYPES.add("setRef");
        PARAMSTYPES.add("setShort");
        PARAMSTYPES.add("setString");
        PARAMSTYPES.add("setTime");
        PARAMSTYPES.add("setTimestamp");
        PARAMSTYPES.add("setURL");
    }

    private Log _log;
    private T _delegate;
    private Map<String, Object> _paramsByName = new TreeMap<String, Object>();
    private Map<Integer, Object> _paramsByIdx = new TreeMap<Integer, Object>();

    public LoggingInterceptor(T delegate, Log log) {
        _log = log;
        _delegate = delegate;
    }

	public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        try {
            if (method.getDeclaringClass() == DataSource.class
                    && "getConnection".equals(method.getName())) {
                Connection conn = (Connection)method.invoke(_delegate, args);
                print("getConnection (tx=" + conn.getTransactionIsolation() + ")");
                return Proxy.newProxyInstance(_delegate.getClass().getClassLoader(),
                        new Class[] {Connection.class}, new LoggingInterceptor<Connection>(conn, _log));
            } else if (method.getDeclaringClass() == Connection.class
                    && Statement.class.isAssignableFrom(method.getReturnType())) {
                Statement stmt = (Statement)method.invoke(_delegate, args);
                print(method, args);
                return Proxy.newProxyInstance(_delegate.getClass().getClassLoader(),
                        new Class[] {method.getReturnType()}, new LoggingInterceptor<Statement>(stmt, _log));
            } else {
                print(method, args);
                return method.invoke(_delegate, args);
            }
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }

	private void print(Method method, Object[] args) {
        if (shouldPrint()) {
            // JDBC Connection
            if ("prepareStatement".equals(method.getName())) {
                print("prepareStatement: " + args[0]);
            } else if ("prepareCall".equals(method.getName())) {
                print("prepareCall: " + args[0]);
            } else if ("close".equals(method.getName())) {
                print("close()");
            } else if ("commit".equals(method.getName())) {
                print("commit()");
            } else if ("rollback".equals(method.getName())) {
                print("rollback()");
            } else if ("setTransactionIsolation".equals(method.getName())) {
                print("Set isolation level to " + args[0]);
            }
            // JDBC Statement
            else if (method.getName().startsWith("execute")) {
                print(method.getName() + ", " + getParams());
            } else if ("clearParameters".equals(method.getName())) {
                _paramsByIdx.clear();
                _paramsByName.clear();
            } else if ("setNull".equals(method.getName())) {
                if (String.class.isAssignableFrom(args[0].getClass())) {
                    _paramsByName.put((String)args[0], null);
                } else if (Integer.class.isAssignableFrom(args[0].getClass())) {
                    _paramsByIdx.put((Integer)args[0], null);
                }
            } else if (PARAMSTYPES.contains(method.getName())){
                if (String.class.isAssignableFrom(args[0].getClass())) {
                    _paramsByName.put((String)args[0], args[1]);
                } else if (Integer.class.isAssignableFrom(args[0].getClass())) {
                    _paramsByIdx.put((Integer)args[0], args[1]);
                }
            }
        }
    }

    private String getParams() {
        if (_paramsByIdx.size() > 0 || _paramsByName.size() > 0) {
            StringBuffer buf = new StringBuffer();
            buf.append("bound ");
            for (Map.Entry<Integer, Object> entry : _paramsByIdx.entrySet()) {
                try {
                    buf.append("(").append(entry.getKey()).append(",").append(entry.getValue()).append(") ");
                } catch (Throwable e) {
                    // We don't want to mess with the connection just for logging
                	return "[e]";
                }
            }
            for (Map.Entry<String, Object> entry : _paramsByName.entrySet()) {
                try {
                    buf.append("(").append(entry.getKey()).append(",").append(entry.getValue()).append(") ");
                } catch (Throwable e) {
                    // We don't want to mess with the connection just for logging
                    return "[e]";
                }
            }
            return buf.toString();
        }
        return "w/o params";
    }

	private boolean shouldPrint() {
        if (_log != null)
            return _log.isDebugEnabled();
        else return true;
    }

    private void print(String str) {
        if (_log != null)
            _log.debug(str);
        else System.out.println(str);
    }

    public static DataSource createLoggingDS(DataSource ds, Log log) {
        return (DataSource)Proxy.newProxyInstance(ds.getClass().getClassLoader(),
                new Class[] {DataSource.class}, new LoggingInterceptor<DataSource>(ds,log));
    }
}


text:
var path = require('path');
var expect = require('chai').expect;

describe('cli-command:', function() {
  it('should use debug middleware', function(done) {
    var cli = require('../../..');
    cli = cli()
      .use(require('cli-mid-debug'))
      .on('complete', function(req) {
        expect(this.debug).to.eql(true);
        done();
      })
      .parse(['--debug']);
  });
  it('should use debug middleware (--no-debug)', function(done) {
    var cli = require('../../..');
    cli = cli()
      .use(require('cli-mid-debug'))
      .on('complete', function(req) {
        expect(this.debug).to.eql(false);
        done();
      })
      .parse(['--no-debug']);
  });
  it('should use debug middleware with logger', function(done) {
    var cli = require('../../..');
    cli = cli()
      .use(require('cli-mid-logger'))
      .use(require('cli-mid-debug'))
      .on('complete', function(req) {
        expect(this.debug).to.eql(true);
        done();
      })
      .parse(['--debug']);
  });
  it('should use debug middleware with bitwise logger', function(done) {
    var cli = require('../../..');
    cli = cli()
      .use(require('cli-mid-logger'), {bitwise: true})
      .use(require('cli-mid-debug'))
      .on('complete', function(req) {
        expect(this.debug).to.eql(true);
        done();
      })
      .parse(['--debug']);
  });
});


text:
package org.cloudsdale.response.v1;

import org.cloudsdale.model.v1.Message;

import java.util.List;

public class MessageResponse extends Response {

	private Message			result;
	private List<Message>	results;

	public Message getResult() {
		return result;
	}

	public void setResult(Message result) {
		this.result = result;
	}

	public List<Message> getResults() {
		return results;
	}

	public void setResults(List<Message> results) {
		this.results = results;
	}
}


text:
GSMCoverage
===========
GSMCoverage is compilation of Python and R code for analyzing the GSM Signal (.log) file obtained from Android app. Antennas. It has two main components, A. Geo-coded GSM Signal Extractor (based on Python implementation), B. Geospatial Signal Data Analysis tool (based on R software)

A. Geocoded Signal Extractor
===========
The Antennas app. provides interface to capture the GPS enabled GSM/CDMA signal strength. This signal strength is logged periodically in a log file. The Geo-coded Signal Extractor comprises of three different ways to extract the data from .log file.

1. A method for extracting the best signal strength for best location (Best location is given by GPS reading)
	A. In PgSQL .SQL format
	B. .csv format

2. A method for extracting all GSM signal strengths (i.e. from sampled available networks) for best location (Best location is given by GPS reading)
	A. In PgSQL .sql format
	B. .csv format

3. A method for extracting all GSM signal strengths (i.e. from sampled available networks) with all details for best location (Best location is given by GPS reading)
	Each row comprises of
	Operator ID, network ID/Antena ID/CID, Sampling Time, Latitude, Longitude, Signal Strength

B. Antenna Signal Data Processing tool
===========
R Script to convert .csv into raster Geotiff file (csvToGeotiff.R).


text:
{-# LANGUAGE OverloadedStrings, ViewPatterns #-}

module Y2016.M07.D15.Solution where

import Control.Monad ((>=>))
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Time

import Network.HTTP

import Data.Time.Calendar.Month (readTweetDate)

type ID = String

data Tweet = Tweet { tweetId :: ID, created :: String } deriving Show

-- so we simply create a FromJSON instance here

instance FromJSON Tweet where
   parseJSON = withObject "tweet" $ \t ->
      Tweet <$> t .: "id_str" <*> t .: "created_at"

dateFromTweet :: FilePath -> IO Day
dateFromTweet = readFile >=> \json -> let (Just tweet) = decode (BL.pack json)
   in pure (readTweetDate (created tweet))

{--
*Y2016.M07.D15.Solution> dateFromTweet "Y2016/M07/D15/tweet.json" ~>
2016-04-26
--}


text:
module Fog
  module AWS
    class Compute
      class Real
        require 'fog/aws/parsers/compute/describe_volumes'

        # Describe all or specified volumes.
        #
        # ==== Parameters
        # * filters<~Hash> - List of filters to limit results with
        #
        # ==== Returns
        # * response<~Excon::Response>:
        #   * body<~Hash>:
        #     * 'volumeSet'<~Array>:
        #       * 'availabilityZone'<~String> - Availability zone for volume
        #       * 'createTime'<~Time> - Timestamp for creation
        #       * 'encrypted'<~Boolean> - Indicates whether the volume will be encrypted
        #       * 'iops'<~Integer> - Number of IOPS volume supports
        #       * 'size'<~Integer> - Size in GiBs for volume
        #       * 'snapshotId'<~String> - Snapshot volume was created from, if any
        #       * 'status'<~String> - State of volume
        #       * 'volumeId'<~String> - Reference to volume
        #       * 'volumeType'<~String> - Type of volume
        #       * 'attachmentSet'<~Array>:
        #         * 'attachmentTime'<~Time> - Timestamp for attachment
        #         * 'deleteOnTermination'<~Boolean> - Whether or not to delete volume on instance termination
        #         * 'device'<~String> - How value is exposed to instance
        #         * 'instanceId'<~String> - Reference to attached instance
        #         * 'status'<~String> - Attachment state
        #         * 'volumeId'<~String> - Reference to volume
        #
        # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumes.html]
        def describe_volumes(filters = {})
          unless filters.is_a?(Hash)
            Fog::Logger.deprecation("describe_volumes with #{filters.class} param is deprecated, use describe_volumes('volume-id' => []) instead [light_black](#{caller.first})[/]")
            filters = {'volume-id' => [*filters]}
          end
          params = Fog::AWS.indexed_filters(filters)
          request({
            'Action'    => 'DescribeVolumes',
            :idempotent => true,
            :parser     => Fog::Parsers::AWS::Compute::DescribeVolumes.new
          }.merge!(params))
        end
      end

      class Mock
        def describe_volumes(filters = {})
          unless filters.is_a?(Hash)
            Fog::Logger.deprecation("describe_volumes with #{filters.class} param is deprecated, use describe_volumes('volume-id' => []) instead [light_black](#{caller.first})[/]")
            filters = {'volume-id' => [*filters]}
          end

          response = Excon::Response.new

          volume_set = self.data[:volumes].values
          volume_set = apply_tag_filters(volume_set, filters, 'volumeId')

          aliases = {
            'availability-zone' => 'availabilityZone',
            'create-time' => 'createTime',
            'encrypted' => 'encrypted',
            'size' => 'size',
            'snapshot-id' => 'snapshotId',
            'status' => 'status',
            'volume-id' => 'volumeId'
          }
          attachment_aliases = {
            'attach-time' => 'attachTime',
            'delete-on-termination' => 'deleteOnTermination',
            'device'      => 'device',
            'instance-id' => 'instanceId',
            'status'      => 'status'
          }

          for filter_key, filter_value in filters
            if attachment_key = filter_key.split('attachment.')[1]
              aliased_key = attachment_aliases[filter_key]
              volume_set = volume_set.reject{|volume| !volume['attachmentSet'].find {|attachment| [*filter_value].include?(attachment[aliased_key])}}
            else
              aliased_key = aliases[filter_key]
              volume_set = volume_set.reject{|volume| ![*filter_value].include?(volume[aliased_key])}
            end
          end

          volume_set.each do |volume|
            case volume['status']
            when 'attaching'
              if Time.now - volume['attachmentSet'].first['attachTime'] >= Fog::Mock.delay
                volume['attachmentSet'].first['status'] = 'in-use'
                volume['status'] = 'in-use'
              end
            when 'creating'
              if Time.now - volume['createTime'] >= Fog::Mock.delay
                volume['status'] = 'available'
              end
            when 'deleting'
              if Time.now - self.data[:deleted_at][volume['volumeId']] >= Fog::Mock.delay
                self.data[:deleted_at].delete(volume['volumeId'])
                self.data[:volumes].delete(volume['volumeId'])
              end
            end
          end
          volume_set = volume_set.reject {|volume| !self.data[:volumes][volume['volumeId']]}
          volume_set = volume_set.map {|volume| volume.merge('tagSet' => self.data[:tag_sets][volume['volumeId']]) }

          response.status = 200
          response.body = {
            'requestId' => Fog::AWS::Mock.request_id,
            'volumeSet' => volume_set
          }
          response
        end
      end
    end
  end
end


text:
require 'test_helper'

class SearchForUserTest < ActionController::IntegrationTest
  def setup
    @carla = profiles(:one)
    @carla.confirmed_at = Time.now
    @carla.email = "carla@railsgirls.com"
    @carla.firstname = "Carla"
    @carla.lastname = "Drago"
    @carla.bio = "weather, programming, sleeping, shopping, veggiemite and photos"
    @carla.twitter = "tweeter"
    @carla.published = true
    @carla.save!
  end

  test "search for and find a user" do

    visit('/en')
    fill_in('search-field', :with => 'weather')
    click_button('Search')
    click_link(@carla.fullname)

    assert_equal current_path, profile_path(@carla, {:locale=>"en"})
  end
end


text:
package org.bitcoins.core.util

import scodec.bits.ByteVector

class NetworkUtilTest extends BitcoinSUtilTest {
  "NetworkUtil" must "convert torV3 pubkey to correct .onion address and vice versa" in {
    val pubkey = ByteVector.fromValidHex(
      "98908ec971ad17171365865a249c420d04a66f103f973a62d8404ce2f4af1ee2")
    val address =
      "tcii5slrvulroe3fqzncjhccbuckm3yqh6ltuywyibgof5fpd3rpycyd.onion"
    val addressFromKey = NetworkUtil.parseUnresolvedInetSocketAddress(pubkey)
    val pubkeyFromAddress = ByteVector(NetworkUtil.torV3AddressToBytes(address))
    assert(address == addressFromKey)
    assert(pubkey == pubkeyFromAddress)
  }
}


text:
package io.craigmiller160.utils.reflect;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * A utility class for operations involving methods that
 * need to be performed before they can be reflectively
 * invoked.
 *
 * Created by Craig on 2/14/2016.
 */
public class MethodUtils {

    MethodUtils(){}

    public static Object[] validateInvocationAndConvertParams(Method method, Object...newParams){
        return ParamUtils.validateInvocationAndConvertParams(method.getParameterTypes(), method.isVarArgs(), newParams);
    }

     /**
     * Compare the two provided methods and test if they are duplicates.
     * This is different from Method.equals(...), because this method
     * only takes into account method name and argument types, not
     * the owning class. This is designed to weed out methods from
     * separate classes that are otherwise identical.
     *
     * @param m1 the first method to test.
     * @param m2 the second method to test.
     * @return true if the two methods are duplicates.
     */
    public static boolean isDuplicateMethod(Method m1, Method m2){
        boolean duplicate = false;
        if(m1.getName().equals(m2.getName())){
            Class<?>[] m1ParamTypes = m1.getParameterTypes();
            Class<?>[] m2ParamTypes = m2.getParameterTypes();
            if(m1ParamTypes.length == m2ParamTypes.length){
                if(Arrays.equals(m1ParamTypes, m2ParamTypes)){
                    duplicate = true;
                }
            }
        }

        return duplicate;
    }
}


text:
//@@author A0125566B
package carelender.view.gui.components;

import carelender.model.strings.AppColours;
import carelender.model.strings.DateFormats;
import carelender.model.strings.FontLoader;
import carelender.view.gui.CanvasRenderer;
import javafx.geometry.VPos;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import carelender.model.data.DateRange;
import carelender.model.data.Event;
import carelender.model.data.EventList;

/**
 * This class contains methods to render the Timeline View
 */
public class TimelineRenderer extends CanvasRenderer {
    private static final double BAR_SIZE_MIN_RATIO = 0.5;

    private static final double FADEOUT_ALPHA = 0.3;
    private static final double DEFAULT_ALPHA = 1;

    private static final double FONT_SIZE_RATIO = 0.2;
    private static final double FONT_LARGE_SIZE_RATIO = 0.3;

    private static final double DIVISOR_SCALE_RATIO = 3;
    private static final double DIVISOR_LARGE_FONT_MOD = 6;

    private static final String FREE_BAR_TEXT_LINE1 = "Days";
    private static final String FREE_BAR_TEXT_LINE2 = "Free";

    private Map<String, ArrayList<TimelineBarRenderer>> weekDisplay;

    private double xPadding;
    private double yPadding;
    private double maxBarWidth;
    private double minBarWidth;
    private double labelWidth;

    private int displayStart;

    public TimelineRenderer() {
        this.weekDisplay = new TreeMap<>();
        this.displayStart = 0;
    }

    /**
     * Set up the dimensions for the timeline view.
     *
     * @param xPad
     * @param yPad
     * @param maxBarWidth
     * 		Maximum size of each timeline bar.
     * @param labelWidth
     * 		Size to be reserved on the left for time labels.
     */
    public void setParams (double xPad, double yPad, double maxBarWidth, double labelWidth) {
        this.xPadding = xPad;
        this.yPadding = yPad;

        this.maxBarWidth = maxBarWidth;
        this.minBarWidth = maxBarWidth * BAR_SIZE_MIN_RATIO;
        this.labelWidth = labelWidth;
    }

    @Override
    public void draw (GraphicsContext gc, double x, double y, double width, double height) {
        super.draw(gc, x, y, width, height);

        Font font = FontLoader.load( labelWidth * FONT_SIZE_RATIO);
        Font fontLarge = FontLoader.load( labelWidth * FONT_LARGE_SIZE_RATIO);

        double xCurrent = x + this.labelWidth - this.xPadding;
        double yCurrent = y + (this.yPadding * 2) + font.getSize();

        gc.setFill(AppColours.panelBackground);
        gc.fillRect(x, y, width, height);

        renderDivisors(gc, xCurrent, yCurrent, width, height, font, fontLarge);

        xCurrent = x + this.labelWidth;
        renderBars(gc, xCurrent, yCurrent, width, height, font);
    }

    public void clear () {
        this.weekDisplay.clear();
        this.displayStart = 0;
    }

    public void scrollDown () {
        if ( this.displayStart > 0 ) {
            this.displayStart--;
        }
        redraw();
    }

    public void scrollUp () {
        if ( this.displayStart < this.weekDisplay.size() - 1 ) {
            this.displayStart++;
        }
        redraw();
    }

    /**
     * Add events from EventList to weekDisplay.
     * Events are indexed according to the order within toDisplay.
     *
     * @param toDisplay
     * 		EventList to add to weekDisplay.
     */
    public void addEvents ( EventList toDisplay ) {
        int index = 1;
        for ( Event event : toDisplay ) {
            DateRange [] dateRange = event.getDateRange();
            if ( dateRange == null ) {
                continue;
            }
            for ( DateRange date : dateRange ) {
                String keyEnd = DateFormats.FORMAT_KEY(date.getEnd());
                String keyStart = DateFormats.FORMAT_KEY(date.getStart());
                //Event has a single date
                if (keyEnd.equals(keyStart)) {
                    addDateRangeToDisplay(keyStart, DateFormats.TIME_IN_MINUTES(date.getStart()),
                                            DateFormats.TIME_IN_MINUTES(date.getEnd()), String.valueOf(index));
                } else {
                    addDateRangeToDisplay(keyStart, DateFormats.TIME_IN_MINUTES(date.getStart()),
                                            TimelineBarRenderer.MINUTES_IN_DAY, String.valueOf(index));
                    Date currentDay = date.getStart();
                    //Event spans multiple days, add event to each day between start and end dates.
                    for ( int i = 0; i < date.getDaysBetween(); i++ ) {
                        currentDay = DateFormats.ADD_DAYS(currentDay, 1);
                        if (!(keyEnd.equals(DateFormats.FORMAT_KEY(currentDay)))) {
                            addDateRangeToDisplay(DateFormats.FORMAT_KEY(currentDay), 0,
                                                    TimelineBarRenderer.MINUTES_IN_DAY, String.valueOf(index));

                        }
                    }
                    this.addDateRangeToDisplay(keyEnd, 0, DateFormats.TIME_IN_MINUTES(date.getEnd()),
                                                String.valueOf(index));
                }
            }
            index++;
        }
    }

    /**
     * Render all the bars in the timeline.
     *
     * @param gc
     * @param xCurrent
     * @param yCurrent
     * @param width
     * @param height
     * @param font
     */
    private void renderBars (GraphicsContext gc, double xCurrent, double yCurrent,
                                double width, double height, Font font) {
        int currentTaskToDisplay = 0;
        int lastDay = -1;
        int numberOfBars = getNumberOfBars();

        double barWidth = (width - (xPadding * (numberOfBars - 1)) - font.getSize()) / (numberOfBars);
        barWidth = (barWidth > maxBarWidth) ? maxBarWidth : barWidth;
        barWidth = (barWidth < minBarWidth) ? minBarWidth : barWidth;

        double usableWidth = width - labelWidth - (xPadding * 2);
        double usableHeight = height - labelWidth - (yPadding * 2);

        double remainingHeight = usableWidth;

        for ( Map.Entry<String, ArrayList<TimelineBarRenderer>> entry : weekDisplay.entrySet()) {
            if ( currentTaskToDisplay >= displayStart ) {
                String key = entry.getKey();
                ArrayList<TimelineBarRenderer> value = entry.getValue();

                gc.setTextAlign(TextAlignment.CENTER);
                gc.setFont(font);
                gc.setTextBaseline(VPos.CENTER);

                String [] keyWords = key.split(" ");
                if ( lastDay != -1 ) {
                    int freeDays = Integer.parseInt(keyWords[1]) - lastDay - 1;

                    if ( freeDays > 0 ) {
                        if ( (remainingHeight - barWidth - xPadding) >= 0 ) {
                            yCurrent = y + (yPadding * 2) + font.getSize();

                            renderFreeBar(gc, xCurrent, yCurrent, barWidth, usableHeight,
                                            font, String.valueOf(freeDays));

                            xCurrent += ( barWidth + xPadding );
                            remainingHeight -= (barWidth + xPadding);
                        } else {
                            break;
                        }
                    }
                }
                lastDay = Integer.parseInt(keyWords[1]);

                if ( (remainingHeight - barWidth - xPadding) >= 0 ) {
                    yCurrent = y + yPadding;

                    renderTimelineBar(gc, xCurrent, yCurrent, barWidth, usableHeight,
                                        font, keyWords[2], keyWords[3], value);

                    xCurrent += (barWidth + xPadding);
                    remainingHeight -= (barWidth + xPadding);
                } else {
                    break;
                }
            }
            currentTaskToDisplay++;
        }
    }

    /**
     * Render bars used to display free days between two days.
     *
     * @param gc
     * @param xCurrent
     * @param yCurrent
     * @param width
     * 		Width of each bar.
     * @param height
     * 		Maximum height of each bar.
     * @param font
     * @param text
     * 		The number of days between the two days as a String.
     */
    private void renderFreeBar (GraphicsContext gc, double xCurrent, double yCurrent,
                                double width, double height, Font font, String text) {
        gc.setGlobalAlpha(FADEOUT_ALPHA);
        gc.setFill(AppColours.information);
        gc.fillRect(xCurrent, yCurrent + yPadding, width, height);
        gc.setGlobalAlpha(DEFAULT_ALPHA);

        gc.setFill(AppColours.tasklistRowBackground);
        yCurrent = y + yPadding + (height * 0.5);
        gc.fillText ( text, xCurrent + (width * 0.5), yCurrent );
        gc.fillText ( FREE_BAR_TEXT_LINE1, xCurrent + (width * 0.5), yCurrent + font.getSize() );
        gc.fillText ( FREE_BAR_TEXT_LINE2, xCurrent + (width * 0.5), yCurrent + (font.getSize() * 2) );
    }

    /**
     * Render the bars within a single day.
     * Each TimelineBarRenderer renders one block of time used by an event.
     *
     * @param gc
     * @param xCurrent
     * @param yCurrent
     * @param width
     * 		Width of each bar.
     * @param height
     * 		Maximum height of each bar.
     * @param font
     * @param dateText
     * 		String in the form d, where d is the day in the month.
     * @param dayText
     * 		String in the form EEE, where E is the day of the week.
     * @param value
     * 		ArrayList of TimelineBarRenderer for each bar.
     */
    private void renderTimelineBar (GraphicsContext gc, double xCurrent, double yCurrent,
                                    double width, double height, Font font,
                                    String dateText, String dayText, ArrayList<TimelineBarRenderer> value) {
        gc.setTextAlign(TextAlignment.CENTER);
        gc.setFont(font);
        gc.setTextBaseline(VPos.CENTER);
        gc.setFill(AppColours.primaryColour);
        gc.fillText ( dateText, xCurrent + (width * 0.5), yCurrent );
        gc.fillText ( dayText, xCurrent + (width * 0.5), yCurrent + font.getSize() );

        yCurrent += yPadding + font.getSize();
        for (TimelineBarRenderer bar : value) {
            bar.draw(gc, AppColours.tasklistRowBackground, AppColours.primaryColour,
                        xCurrent, yCurrent + yPadding, width, height);
        }
    }

    /**
     * Render divisors used to demarcate the time of day.
     * 24 divisors are rendered for each hour of the day.
     *
     * @param gc
     * @param xCurrent
     * @param yCurrent
     * @param width
     * @param height
     * @param font
     * @param fontLarge
     */
    private void renderDivisors (GraphicsContext gc, double xCurrent, double yCurrent,
                                    double width, double height, Font font, Font fontLarge) {
        double usableWidth = width - labelWidth - (xPadding * 2);
        double usableHeight = height - labelWidth - (yPadding * 2);
        double divisorWidth = (1 / TimelineBarRenderer.MINUTES_IN_DAY) * usableHeight;

        for (int i = 0; i <= 24; i++) {
            gc.setTextAlign(TextAlignment.RIGHT);
            gc.setTextBaseline(VPos.CENTER);
            //Every (DIVISOR_LARGE_FONT_MOD)th divisor is increased in size and opacity.
            if ( i % DIVISOR_LARGE_FONT_MOD == 0 ) {
                renderDivisor(gc, xCurrent, yCurrent, usableWidth, divisorWidth,
                        fontLarge, String.valueOf((i % 12) == 0 ? 12 : i % 12), DEFAULT_ALPHA);
            } else {
                renderDivisor(gc, xCurrent, yCurrent, usableWidth, divisorWidth,
                                font, String.valueOf((i % 12) == 0 ? 12 : i % 12), FADEOUT_ALPHA);
            }
            yCurrent += (60 / TimelineBarRenderer.MINUTES_IN_DAY) * usableHeight;
        }
    }

    /**
     * Render each divisor.
     *
     * @param gc
     * @param xCurrent
     * @param yCurrent
     * @param width
     * 		Width of the divisor.
     * @param height
     * 		Height of the divisor.
     * @param font
     * @param text
     *		Time of the day in hours, as a String.
     * @param alpha
     */
    private void renderDivisor (GraphicsContext gc, double xCurrent, double yCurrent,
                                double width, double height, Font font, String text, double alpha) {
        gc.setFont(font);
        gc.setGlobalAlpha(alpha);

        gc.setFill(AppColours.tasklistRowBackground);
        gc.fillText ( text, xCurrent, yCurrent + yPadding );

        gc.setFill(AppColours.primaryColour);
        gc.fillRect(xCurrent + xPadding, yCurrent + yPadding - (height * DIVISOR_SCALE_RATIO * 0.5),
                    width, height * DIVISOR_SCALE_RATIO);
        gc.setGlobalAlpha(DEFAULT_ALPHA);
    }

    /**
     * Return number of bars in total.
     * Bars used to display free days are counted as well.
     *
     * @return
     * 		Number of bars.
     */
    private int getNumberOfBars () {
        int numberOfBars = weekDisplay.size();
        int lastDay = -1;
        //Count the number of bars to display in total, including bars used to show free days.
        for (Map.Entry<String, ArrayList<TimelineBarRenderer>> entry : weekDisplay.entrySet()) {
            String key = entry.getKey();
            String [] keyWords = key.split(" ");
            //Compare against previous day in the display.
            if ( lastDay != -1 ) {
                //Compare using the 2nd delimited chunk of the key, which is the day of the year.
                int freeDays = Integer.parseInt(keyWords[1]) - lastDay - 1;

                if ( freeDays > 0 ) {
                    numberOfBars += freeDays;
                }
            }
            lastDay = Integer.parseInt(keyWords[1]);
        }
        return numberOfBars;
    }

    /**
     * Add a date range to the weekDisplay.
     * Date ranges with the same key are stored in an ArrayList.
     * Each date range represents a bar on a single day.
     *
     * @param key
     * @param startTime
     * @param endTime
     * @param content
     * 		The index of the event to be displayed on the bar.
     */
    private void addDateRangeToDisplay (String key, double startTime, double endTime, String content) {
        if (weekDisplay.containsKey(key)) {
            weekDisplay.get(key).add(createWeekBar(startTime, endTime, content));
        } else {
            ArrayList<TimelineBarRenderer> tasksOnDay = new ArrayList<TimelineBarRenderer>();
            tasksOnDay.add(createWeekBar(startTime, endTime, content));
            this.weekDisplay.put (key, tasksOnDay);
        }
    }

    /**
     * Create the TimelineBarRenderer object
     *
     * @param startTime
     * @param endTime
     * @param content
     * @return
     * 		The TimelineBarRenderer to be added to the weekDisplay.
     */
    private TimelineBarRenderer createWeekBar (double startTime, double endTime, String content) {
        TimelineBarRenderer bar = new TimelineBarRenderer();
        bar.setParams(startTime, endTime, content);
        return bar;
    }
}


text:
<?php

declare(strict_types=1);

namespace League\Container\Test\Definition;

use League\Container\Argument\Literal;
use League\Container\Argument\ResolvableArgument;
use League\Container\Container;
use League\Container\Definition\Definition;
use League\Container\Test\Asset\{Foo, FooCallable, Bar};
use PHPUnit\Framework\TestCase;

class DefinitionTest extends TestCase
{
    public function testDefinitionResolvesClosureWithDefinedArgs(): void
    {
        $definition = new Definition('callable', function (...$args) {
            return implode(' ', $args);
        });

        $definition->addArguments(['hello', 'world']);
        $actual = $definition->resolve();
        self::assertSame('hello world', $actual);
    }

    public function testDefinitionResolvesClosureReturningRawArgument(): void
    {
        $definition = new Definition('callable', function () {
            return new Literal\StringArgument('hello world');
        });

        $actual = $definition->resolve();
        self::assertSame('hello world', $actual);
    }

    public function testDefinitionResolvesCallableClass(): void
    {
        $definition = new Definition('callable', new FooCallable());
        $definition->addArgument(new Bar());
        $actual = $definition->resolve();
        self::assertInstanceOf(Foo::class, $actual);
    }

    public function testDefinitionResolvesArrayCallable(): void
    {
        $definition = new Definition('callable', [new FooCallable(), '__invoke']);
        $definition->addArgument(new Bar());
        $actual = $definition->resolve();
        self::assertInstanceOf(Foo::class, $actual);
    }

    public function testDefinitionResolvesClassWithMethodCalls(): void
    {
        $container = $this->getMockBuilder(Container::class)->getMock();
        $bar = new Bar();

        $container->expects(self::once())->method('has')->with(self::equalTo(Bar::class))->willReturn(true);
        $container->expects(self::once())->method('get')->with(self::equalTo(Bar::class))->willReturn($bar);

        $definition = new Definition('callable', Foo::class);

        $definition->setContainer($container);
        $definition->addMethodCalls(['setBar' => [Bar::class]]);

        $actual = $definition->resolve();
        self::assertInstanceOf(Foo::class, $actual);
        self::assertInstanceOf(Bar::class, $actual->bar);
    }

    public function testDefinitionResolvesClassWithDefinedArgs(): void
    {
        $container = $this->getMockBuilder(Container::class)->getMock();
        $bar = new Bar();

        $container->expects(self::once())->method('has')->with(self::equalTo(Bar::class))->willReturn(true);
        $container->expects(self::once())->method('get')->with(self::equalTo(Bar::class))->willReturn($bar);

        $definition = new Definition('callable', Foo::class);

        $definition->setContainer($container);
        $definition->addArgument(Bar::class);

        $actual = $definition->resolve();
        self::assertInstanceOf(Foo::class, $actual);
        self::assertInstanceOf(Bar::class, $actual->bar);
    }

    public function testDefinitionResolvesSharedItemOnlyOnce(): void
    {
        $definition = new Definition('class', Foo::class);
        $definition->setShared(true);
        $actual1 = $definition->resolve();
        $actual2 = $definition->resolve();
        $actual3 = $definition->resolveNew();
        self::assertSame($actual1, $actual2);
        self::assertNotSame($actual1, $actual3);
    }

    public function testDefinitionResolvesNestedAlias(): void
    {
        $aliasDefinition = new Definition('alias', new ResolvableArgument('class'));
        $definition = new Definition('class', Foo::class);
        $container = $this->getMockBuilder(Container::class)->getMock();

        $expected = $definition->resolve();

        $container->expects(self::once())->method('has')->with(self::equalTo('class'))->willReturn(true);
        $container->expects(self::once())->method('get')->with(self::equalTo('class'))->willReturn($expected);

        $aliasDefinition->setContainer($container);
        $actual = $aliasDefinition->resolve();
        self::assertSame($expected, $actual);
    }

    public function testDefinitionCanAddTags(): void
    {
        $definition = new Definition('class', Foo::class);
        $definition->addTag('tag1')->addTag('tag2');
        self::assertTrue($definition->hasTag('tag1'));
        self::assertTrue($definition->hasTag('tag2'));
        self::assertFalse($definition->hasTag('tag3'));
    }

    public function testDefinitionCanGetConcrete(): void
    {
        $concrete = new Literal\StringArgument(Foo::class);
        $definition = new Definition('class', $concrete);
        self::assertSame($concrete, $definition->getConcrete());
    }

    public function testDefinitionCanSetConcrete(): void
    {
        $definition = new Definition('class', null);
        $concrete = new Literal\StringArgument(Foo::class);
        $definition->setConcrete($concrete);
        self::assertSame($concrete, $definition->getConcrete());
    }
}


text:
package net.anotheria.moskito.sql.stats;

import net.anotheria.moskito.core.predefined.Constants;
import net.anotheria.moskito.core.predefined.AbstractStatsFactory;
import net.anotheria.moskito.core.stats.Interval;

/**
 * On demand stats factory for QueryStats object.
 *
 * @author lrosenberg
 * @since 10.08.14 23:34
 */
public class QueryStatsFactory extends AbstractStatsFactory<QueryStats> {

	/**
	 * Default instance to spare additional object creation.
	 */
	public static final AbstractStatsFactory<QueryStats> DEFAULT_INSTANCE = new QueryStatsFactory();

	/**
	 * Creates a new factory with custom intervals.
	 * @param configuredIntervals {@link Interval} array
	 */
	public QueryStatsFactory(final Interval[] configuredIntervals){
		super(configuredIntervals == null || configuredIntervals.length <= 0 ? Constants.getDefaultIntervals() : configuredIntervals);
	}

	/**
	 * Createsa new factory with default intervals.
	 */
	public QueryStatsFactory(){
		super();
	}

	@Override public QueryStats createStatsObject(String name) {
		return new QueryStats(name, getIntervals());
	}
}


text:
#include "TiBase.h"

#ifdef __cplusplus
#define EXTERN_FUNC extern "C"
#else
#define EXTERN_FUNC extern
#endif

EXTERN_FUNC void  TiProfilerStart(NSString*, NSInteger);
EXTERN_FUNC void  TiProfilerStop();
EXTERN_FUNC void  TiProfilerDiscoveryStart(NSString*, NSArray*, void(^)(NSString *, NSInteger));
EXTERN_FUNC void  TiProfilerEnable(TiObjectRef);
EXTERN_FUNC void  TiProfilerWillExecute(TiContextRef, const char*);
EXTERN_FUNC void  TiProfilerDidExecute(TiContextRef, const char*);


text:
"""XML parser"""

import sys
from html import parser as html_parser
from html.entities import entitydefs as html_entity_defs
from io import StringIO, BytesIO
from xml import sax
from xml.dom import minidom as dom

from ..helpers import StringWithLocation
from ..runtime.exceptions import TemplateSyntaxError

impl = dom.getDOMImplementation(" ")

html_parser_extra_kw = {}
if sys.version_info >= (3, 4):
    html_parser_extra_kw["convert_charrefs"] = False

class TonnikalaXMLParser(sax.ContentHandler):
    def __init__(self, filename, source):
        super(TonnikalaXMLParser, self).__init__()
        self.filename = filename
        self.source = source
        self.doc = None
        self.elements = []
        self._characters = None

    def parse(self):
        self._parser = parser = sax.make_parser()
        parser.setFeature(sax.handler.feature_external_pes, False)
        parser.setFeature(sax.handler.feature_external_ges, False)
        parser.setFeature(sax.handler.feature_namespaces, False)
        parser.setProperty(sax.handler.property_lexical_handler, self)
        parser.setContentHandler(self)
        source = sax.xmlreader.InputSource()

        if isinstance(self.source, bytes):
            stream = BytesIO(self.source)
        else:
            stream = StringIO(self.source)

        source.setByteStream(stream)
        source.setSystemId(self.filename)
        parser.parse(source)
        return self.doc

    ## ContentHandler implementation
    def startDocument(self):
        self.doc = dom.Document()
        self.elements.append(self.doc)

    def _checkAndClearChrs(self):
        if self._characters:
            node = self.doc.createTextNode("".join(self._characters[1]))
            node.lineno = self._characters[0]
            self.elements[-1].appendChild(node)

        self._characters = None

    def startElement(self, name, attrs):
        self.flush_character_data()
        el = self.doc.createElement(name)
        el.lineno = self._parser.getLineNumber()
        for k, v in attrs.items():
            el.setAttribute(k, v)

        self.elements[-1].appendChild(el)
        self.elements.append(el)

    def endElement(self, name):
        self.flush_character_data()
        popped = self.elements.pop()
        assert name == popped.tagName

    def characters(self, content):
        if not self._characters:
            self._characters = (self._parser.getLineNumber(), [])

        self._characters[1].append(content)

    def processingInstruction(self, target, data):
        self.flush_character_data()
        node = self.doc.createProcessingInstruction(target, data)
        node.lineno = self._parser.getLineNumber()
        self.elements[-1].appendChild(node)

    def skippedEntity(self, name):
        # Encoding?
        content = html_entity_defs.get(name)
        if not content:
            raise RuntimeError("Unknown HTML entity &%s;" % name)

        return self.characters(str(content))

    def startElementNS(self, name, qname, attrs):  # pragma no cover
        raise NotImplementedError("startElementNS")

    def endElementNS(self, name, qname):  # pragma no cover
        raise NotImplementedError("startElementNS")

    def startPrefixMapping(self, prefix, uri):  # pragma no cover
        raise NotImplementedError("startPrefixMapping")

    def endPrefixMapping(self, prefix):  # pragma no cover
        raise NotImplementedError("endPrefixMapping")

    # LexicalHandler implementation
    def comment(self, text):
        self.flush_character_data()

        if not text.strip().startswith("!"):
            node = self.doc.createComment(text)
            node.lineno = self._parser.getLineNumber()
            self.elements[-1].appendChild(node)

    def startCDATA(self):
        pass

    def endCDATA(self):
        pass

    def startDTD(self, name, pubid, sysid):
        self.doc.doctype = impl.createDocumentType(name, pubid, sysid)

    def endDTD(self):
        pass

if hasattr(html_parser, "attrfind_tolerant"):  # pragma: no cover
    attrfind = html_parser.attrfind_tolerant
else:
    attrfind = html_parser.attrfind

if hasattr(html_parser, "tagfind_tolerant"):  # pragma: no cover
    tagfind = html_parser.tagfind_tolerant
else:
    tagfind = html_parser.tagfind

# object to force a new-style class!
class TonnikalaHTMLParser(html_parser.HTMLParser, object):
    void_elements = {
        "area",
        "base",
        "br",
        "col",
        "embed",
        "hr",
        "img",
        "input",
        "keygen",
        "link",
        "meta",
        "param",
        "source",
        "track",
        "wbr",
    }

    def __init__(self, filename, source):
        super(TonnikalaHTMLParser, self).__init__(**html_parser_extra_kw)
        self.filename = filename
        self.source = source
        self.doc = None
        self.elements = []
        self.characters = None
        self.characters_start = None

    def parse(self):
        self.doc = dom.Document()
        self.elements.append(self.doc)

        self.feed(self.source)
        self.close()
        self.flush_character_data()
        return self.doc

    def flush_character_data(self):
        if self.characters:
            text = "".join(self.characters)

            if isinstance(self.elements[-1], dom.Document):
                # Special case: just skip adding whitespace to document root,
                # but raise hell, if trying to add other characters
                if len(text.strip()) > 0:
                    self.syntax_error(
                        "Text data outside of root element",
                        lineno=self.characters_start[0],
                    )

                else:
                    self.characters = None
                    return

            line, offset = self.characters_start
            text = StringWithLocation(text, line, offset)
            node = self.doc.createTextNode(text)
            node.position = line, offset
            self.elements[-1].appendChild(node)

        self.characters = None

    def delta(self, row, col):
        orow, ocol = self.getpos()
        if row:
            orow += row
            ocol = col
        else:
            ocol += col

        return orow, ocol

    def find_attr_positions(self, attrs):
        if not attrs:
            return {}

        source = self.get_starttag_text()
        match = tagfind.match(source, 1)
        start = match.end()
        attr_pos = {}

        lineoffset = source[:start].count("\n")
        colpos = start - source[:start].rfind("\n") if lineoffset else start + 1

        for m in attrfind.finditer(source, start, len(source) - 1):
            if not m.group(2):
                continue

            attrstart = m.start(3)
            if source[attrstart] in ("'", '"'):
                attrstart += 1

            advance = source[start:attrstart]
            linedelta = advance.count("\n")
            if linedelta:
                colpos = len(advance) - advance.rfind("\n")
            else:
                colpos += len(advance)

            lineoffset += linedelta

            attrname = m.group(1).lower()
            attr_pos[attrname] = self.delta(lineoffset, colpos)
            start = attrstart

        return attr_pos

    def getlineno(self):
        return self.getpos()[0]

    def handle_starttag(self, name, attrs, self_closing=False):
        self.flush_character_data()

        attr_pos = self.find_attr_positions(attrs)
        el = self.doc.createElement(name)
        el.name = name
        el.position = self.getpos()

        for k, v in attrs:
            if k in attr_pos:
                l, o = attr_pos[k]
                v = StringWithLocation(v, l, o)

            el.setAttribute(k, v)

        self.elements[-1].appendChild(el)
        self.elements.append(el)

        if self_closing or name.lower() in self.void_elements:
            self.handle_endtag(name)

    def handle_endtag(self, name):
        self.flush_character_data()
        popped = self.elements.pop()

        if name.lower() != popped.name.lower():
            self.syntax_error(
                "Invalid end tag </%s> (expected </%s>)" % (name, popped.name)
            )

    def handle_startendtag(self, name, attrs):
        self.handle_starttag(name, attrs, self_closing=True)

    def handle_data(self, content):
        if not self.characters:
            self.characters = []
            self.characters_start = self.getpos()

        self.characters.append(content)

    def handle_pi(self, data):
        self.flush_character_data()

        # The HTMLParser spits processing instructions as is with type and all
        # (python 2 split does not take keyword arguments :( )
        type_, data = data.split(None, 1)

        if data.endswith("?"):
            # XML syntax parsed as SGML, remove trailing '?'
            data = data[:-1]

        node = self.doc.createProcessingInstruction(type_, data)
        node.position = self.getpos()
        self.elements[-1].appendChild(node)

    def syntax_error(self, message, lineno=None):
        raise TemplateSyntaxError(
            message,
            lineno or self.getlineno(),
            source=self.source,
            filename=self.filename,
        )

    def handle_entityref(self, name):
        # Encoding?
        try:
            content = str(html_entity_defs[name])
        except KeyError:
            self.syntax_error("Unknown HTML entity &%s;" % name)

        self.handle_data(content)

    def handle_charref(self, code):
        # Encoding?
        try:
            if code.startswith("x"):
                cp = int(code[1:], 16)
            else:
                cp = int(code, 10)

            content = chr(cp)
            return self.handle_data(content)
        except Exception as e:
            self.syntax_error("Invalid HTML charref &#%s;: %s" % (code, e))

    # LexicalHandler implementation
    def handle_comment(self, text):
        self.flush_character_data()

        if not text.strip().startswith("!"):
            node = self.doc.createComment(text)
            node.position = self.getpos()
            self.elements[-1].appendChild(node)

    def handle_decl(self, decl):
        dt = dom.parseString("<!%s><html/>" % decl).doctype
        self.elements[-1].appendChild(dt)

    def unknown_decl(self, decl):
        self.syntax_error("Unknown declaration: %s" % decl)


text:
#ifndef __COCOS2D_EXT_H__
#define __COCOS2D_EXT_H__

#include "ExtensionMacros.h"

#include "GUI/CCControlExtension/CCControlExtensions.h"
#include "GUI/CCScrollView/CCScrollView.h"
#include "GUI/CCScrollView/CCTableView.h"
#include "GUI/CCEditBox/CCEditBox.h"

// Physics integration
#include "physics-nodes/CCPhysicsDebugNode.h"
#include "physics-nodes/CCPhysicsSprite.h"

#include "assets-manager/AssetsManager.h"

#include "ext/CCSpriteWithHue.h"

#endif /* __COCOS2D_EXT_H__ */


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE targetDefinitions [
	<!ELEMENT targetDefinitions (board)>
	<!ELEMENT board (name, dbgIF+, dbgDEV, mcuId)>
	<!ELEMENT name (#PCDATA)>
	<!ELEMENT dbgIF (#PCDATA)>
	<!ELEMENT dbgDEV (#PCDATA)>
	<!ELEMENT mcuId (#PCDATA)>
	<!ATTLIST board id CDATA #REQUIRED>
]>

<targetDefinitions>
  <board id="sensor-node">
    <name>sensor-node</name>
    <dbgIF>SWD</dbgIF>
    <dbgDEV>ST-Link</dbgDEV>
    <mcuId>stm32f042k6tx</mcuId>
  </board>
</targetDefinitions>


text:
int socketConnect(uint32_t ip, uint16_t port)
{
	int descriptor = socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in address;

	if (descriptor < 0) {
		return -1;
	}

	address.sin_family = AF_INET;
	address.sin_port = htons(port);
	memcpy(&address.sin_addr, &ip, sizeof(ip));

	if (connect(descriptor, (struct sockaddr *) &address, sizeof(address)) != 0) {
		close(descriptor);
		return -1;
	} else {
		return descriptor;
	}
}

int socketBind(uint32_t ip, uint16_t port, int backlog)
{
	int descriptor = socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in address;

	if (descriptor < 0) {
		return -1;
	}

	address.sin_family = AF_INET;
	address.sin_port = htons(port);
	memcpy(&address.sin_addr, &ip, sizeof(ip));
	//address.sin_addr.s_addr = INADDR_ANY;

	if (bind(descriptor, (struct sockaddr *) &address, sizeof(address)) != 0) {
		close(descriptor);
		return -1;
	}
	if (listen(descriptor, backlog) != 0) {
		close(descriptor);
		return -1;
	}
	return descriptor;
}

int socketAccept(int descriptor)
{
	return accept(descriptor, NULL, 0);
}

uint32_t socketHostLookup(char *host, const char **error)
{
	struct addrinfo hints;
	struct addrinfo *addr;

	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = 0;
	hints.ai_protocol = 0;
	hints.ai_canonname = NULL;
	hints.ai_addr = NULL;
	hints.ai_next = NULL;

	int result = getaddrinfo(host, NULL, &hints, &addr);
	if (result == 0) {
		ASSERT(addr->ai_addr->sa_family == AF_INET);
		uint32_t ip;
		memcpy(&ip, &((struct sockaddr_in *) addr->ai_addr)->sin_addr, sizeof(ip));
		*error = NULL;
		freeaddrinfo(addr);
		return ip;
	} else {
		*error = gai_strerror(result);
		return 0;
	}
}


text:
namespace ray {

rpc::Address LocalityAwareLeasePolicy::GetBestNodeForTask(const TaskSpecification &spec) {
  if (auto node_id = GetBestNodeIdForTask(spec)) {
    if (auto addr = node_addr_factory_(node_id.value())) {
      return addr.value();
    }
  }
  return fallback_rpc_address_;
}

/// Criteria for "best" node: The node with the most object bytes (from object_ids) local.
absl::optional<NodeID> LocalityAwareLeasePolicy::GetBestNodeIdForTask(
    const TaskSpecification &spec) {
  const auto object_ids = spec.GetDependencyIds();
  // Number of object bytes (from object_ids) that a given node has local.
  absl::flat_hash_map<NodeID, uint64_t> bytes_local_table;
  uint64_t max_bytes = 0;
  absl::optional<NodeID> max_bytes_node;
  // Finds the node with the maximum number of object bytes local.
  for (const ObjectID &object_id : object_ids) {
    if (auto locality_data = locality_data_provider_->GetLocalityData(object_id)) {
      for (const NodeID &node_id : locality_data->nodes_containing_object) {
        auto &bytes = bytes_local_table[node_id];
        bytes += locality_data->object_size;
        // Update max, if needed.
        if (bytes > max_bytes) {
          max_bytes = bytes;
          max_bytes_node = node_id;
        }
      }
    } else {
      RAY_LOG(WARNING) << "No locality data available for object " << object_id
                       << ", won't be included in locality cost";
    }
  }
  return max_bytes_node;
}

rpc::Address LocalLeasePolicy::GetBestNodeForTask(const TaskSpecification &spec) {
  // Always return the local node.
  return local_node_rpc_address_;
}

}  // namespace ray


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:key="categoryWidgetList"
    app:title="@string/phone_profiles_pref_category_widget_list">

    <Preference
        app:key="applicationWidgetListNotWorkingMIUIInfo"
        app:title="@string/phone_profiles_pref_widget_not_working_miui_info"
        app:summary="@string/phone_profiles_pref_widget_not_working_miui_info_summary"
        app:widgetLayout="@layout/preference_widget_exclamation_preference"
        app:layout="@layout/mp_preference_material_widget" />
    <SwitchPreferenceCompat
        app:key="applicationWidgetListHeader"
        app:title="@string/phone_profiles_pref_applicationHeader"
        app:defaultValue="true"
        app:layout="@layout/mp_preference_material_widget" />
    <SwitchPreferenceCompat
        app:key="applicationWidgetListGridLayout"
        app:title="@string/phone_profiles_pref_applicationGridLayout"
        app:defaultValue="true"
        app:layout="@layout/mp_preference_material_widget" />
    <sk.henrichg.phoneprofilesplus.OpaquenessLightingPreferenceX
        app:title="@string/phone_profiles_pref_applicationWidgetBackground"
        app:summary="25%%"
        app:key="applicationWidgetListBackground"
        app:defaultValue="25"
        app:showLighting="false"
        app:layout="@layout/mp_preference_material_widget" />
    <SwitchPreferenceCompat
        app:key="applicationWidgetListBackgroundType"
        app:title="@string/phone_profiles_pref_applicationWidgetBackgroundType"
        app:defaultValue="false"
        app:layout="@layout/mp_preference_material_widget" />
    <sk.henrichg.phoneprofilesplus.OpaquenessLightingPreferenceX
        app:title="@string/phone_profiles_pref_applicationWidgetLightnessB"
        app:summary="0%%"
        app:key="applicationWidgetListLightnessB"
        app:defaultValue="0"
        app:showLighting="true"
        app:layout="@layout/mp_preference_material_widget" />
    <sk.henrichg.phoneprofilesplus.ColorChooserPreferenceX
        app:title="@string/phone_profiles_pref_applicationWidgetColorB"
        app:key="applicationWidgetListBackgroundColor"
        app:defaultValue="-1"
        app:layout="@layout/mp_preference_material_widget" />
    <SwitchPreferenceCompat
        app:key="applicationWidgetListShowBorder"
        app:title="@string/phone_profiles_pref_applicationWidgetShowBorder"
        app:defaultValue="false"
        app:layout="@layout/mp_preference_material_widget" />
    <sk.henrichg.phoneprofilesplus.OpaquenessLightingPreferenceX
        app:title="@string/phone_profiles_pref_applicationWidgetLightnessBorder"
        app:summary="100%%"
        app:key="applicationWidgetListLightnessBorder"
        app:defaultValue="100"
        app:showLighting="true"
        app:layout="@layout/mp_preference_material_widget" />

<!--    <SwitchPreferenceCompat-->
<!--        app:key="applicationWidgetListRoundedCorners"-->
<!--        app:title="@string/phone_profiles_pref_applicationWidgetRoundedCorners"-->
<!--        app:defaultValue="true"-->
<!--        app:layout="@layout/mp_preference_material_widget" />-->
    <sk.henrichg.phoneprofilesplus.BetterNumberPickerPreferenceX
        app:key="applicationWidgetListRoundedCornersRadius"
        app:summary="@string/phone_profiles_pref_applicationWidgetCornerRadius"
        app:title="@string/phone_profiles_pref_applicationWidgetCornerRadius"
        app:defaultValue="5"
        app:min="1"
        app:max="15"
        app:layout="@layout/mp_preference_material_widget" />

    <sk.henrichg.phoneprofilesplus.OpaquenessLightingPreferenceX
        app:title="@string/phone_profiles_pref_applicationWidgetLightnessT"
        app:summary="100%%"
        app:key="applicationWidgetListLightnessT"
        app:defaultValue="100"
        app:showLighting="true"
        app:layout="@layout/mp_preference_material_widget" />

    <ListPreference
        app:title="@string/phone_profiles_pref_applicationWidgetIconColor"
        app:summary="0"
        app:key="applicationWidgetListIconColor"
        app:defaultValue="0"
        app:entries="@array/widgetColorArray"
        app:entryValues="@array/widgetColorValues"
        app:layout="@layout/mp_preference_material_widget" />
    <sk.henrichg.phoneprofilesplus.OpaquenessLightingPreferenceX
        app:title="@string/phone_profiles_pref_applicationWidgetLightnessI"
        app:summary="100%%"
        app:key="applicationWidgetListIconLightness"
        app:defaultValue="100"
        app:showLighting="true"
        app:layout="@layout/mp_preference_material_widget" />
    <SwitchPreferenceCompat
        app:key="applicationWidgetListCustomIconLightness"
        app:title="@string/phone_profiles_pref_applicationWidgetIconCustomIconLightness"
        app:defaultValue="false"
        app:layout="@layout/mp_preference_material_widget" />

    <SwitchPreferenceCompat
        app:key="applicationWidgetListPrefIndicator"
        app:title="@string/phone_profiles_pref_applicationPrefIndicator"
        app:summary="@string/phone_profiles_pref_applicationPrefIndicatorForWidget_summary"
        app:defaultValue="true"
        app:layout="@layout/mp_preference_material_widget" />
    <sk.henrichg.phoneprofilesplus.OpaquenessLightingPreferenceX
        app:title="@string/phone_profiles_pref_notificationPrefIndicatorLightness"
        app:summary="50%%"
        app:key="applicationWidgetListPrefIndicatorLightness"
        app:defaultValue="50"
        app:showLighting="true"
        app:layout="@layout/mp_preference_material_widget" />

</androidx.preference.PreferenceScreen>


text:
// g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef G2O_FACTORY_H
#define G2O_FACTORY_H

#include "g2o/config.h"
#include <string>
#include <map>
#include <iostream>
#include "g2o/core/creators.h"
#include "g2o/core/hyper_graph.h"
#include "g2o/stuff/misc.h"

// define to get some verbose output
//#define G2O_DEBUG_FACTORY

namespace g2o {

  class AbstractHyperGraphElementCreator;

  /**
   * \brief create vertices and edges based on TAGs in, for example, a file
   */
  class  Factory
  {
    public:

      //! return the instance
      static Factory* instance();

      //! free the instance
      static void destroy();

      /**
       * register a tag for a specific creator
       */
      void registerType(const std::string& tag, AbstractHyperGraphElementCreator* c);

      /**
       * unregister a tag for a specific creator
       */
      void unregisterType(const std::string& tag);

      /**
       * construct a graph element based on its tag
       */
      HyperGraph::HyperGraphElement* construct(const std::string& tag) const;

      /**
       * construct a graph element based on its tag, but only if it's type (a bitmask) matches. A bitmask without any
       * bit set will construct any item. Otherwise a bit has to be set to allow construction of a graph element.
       */
      HyperGraph::HyperGraphElement* construct(const std::string& tag, const HyperGraph::GraphElemBitset& elemsToConstruct) const;

      /**
       * return whether the factory knows this tag or not
       */
      bool knowsTag(const std::string& tag, int* elementType = 0) const;

      //! return the TAG given a vertex
      const std::string& tag(const HyperGraph::HyperGraphElement* v) const;

      /**
       * get a list of all known types
       */
      void fillKnownTypes(std::vector<std::string>& types) const;

      /**
       * print a list of the known registered types to the given stream
       */
      void printRegisteredTypes(std::ostream& os, bool comment = false) const;

    protected:
      class CreatorInformation
      {
        public:
          AbstractHyperGraphElementCreator* creator;
          int elementTypeBit;
          CreatorInformation()
          {
            creator = 0;
            elementTypeBit = -1;
          }

          ~CreatorInformation()
          {
            std::cout << "Deleting " << (void*) creator << std::endl;

            delete creator;
          }
      };

      typedef std::map<std::string, CreatorInformation*>               CreatorMap;
      typedef std::map<std::string, std::string>                      TagLookup;
      Factory();
      ~Factory();

      CreatorMap _creator;     ///< look-up map for the existing creators
      TagLookup _tagLookup;    ///< reverse look-up, class name to tag

    private:
      static Factory* factoryInstance;
  };

  template<typename T>
  class RegisterTypeProxy
  {
    public:
      RegisterTypeProxy(const std::string& name) : _name(name)
      {
#ifdef G2O_DEBUG_FACTORY
        std::cout << __FUNCTION__ << ": Registering " << _name << " of type " << typeid(T).name() << std::endl;
#endif
        Factory::instance()->registerType(_name, new HyperGraphElementCreator<T>());
      }

      ~RegisterTypeProxy()
      {
#ifdef G2O_DEBUG_FACTORY
        std::cout << __FUNCTION__ << ": Unregistering " << _name << " of type " << typeid(T).name() << std::endl;
#endif
        Factory::instance()->unregisterType(_name);
      }

    private:
      std::string _name;
  };

#if defined _MSC_VER && defined G2O_SHARED_LIBS
#  define G2O_FACTORY_EXPORT __declspec(dllexport)
#  define G2O_FACTORY_IMPORT __declspec(dllimport)
#else
#  define G2O_FACTORY_EXPORT
#  define G2O_FACTORY_IMPORT
#endif

  // These macros are used to automate registering types and forcing linkage
#define G2O_REGISTER_TYPE(name, classname) \
    extern "C" void G2O_FACTORY_EXPORT g2o_type_##classname(void) {} \
    static g2o::RegisterTypeProxy<classname> g_type_proxy_##classname(#name);

#define G2O_USE_TYPE_BY_CLASS_NAME(classname) \
    extern "C" void G2O_FACTORY_IMPORT g2o_type_##classname(void); \
    static g2o::ForceLinker proxy_##classname(g2o_type_##classname);

#define G2O_REGISTER_TYPE_GROUP(typeGroupName) \
    extern "C" void G2O_FACTORY_EXPORT g2o_type_group_##typeGroupName(void) {}

#define G2O_USE_TYPE_GROUP(typeGroupName) \
    extern "C" void G2O_FACTORY_IMPORT g2o_type_group_##typeGroupName(void); \
    static g2o::ForceLinker g2o_force_type_link_##typeGroupName(g2o_type_group_##typeGroupName);
}

#endif


text:
package p02_KingsGambit.contracts;

public interface Killable extends Observer {

	void die();

}


text:
package com.facebook.buck.parser;

import static org.junit.Assert.assertThat;

import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventBusFactory;
import com.facebook.buck.json.BuildFileParseException;
import com.facebook.buck.json.ProjectBuildFileParser;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.Cell;
import com.facebook.buck.rules.ConstructorArgMarshaller;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory;
import com.facebook.buck.rules.coercer.TypeCoercerFactory;
import com.facebook.buck.testutil.TestConsole;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TemporaryPaths;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.concurrent.MoreExecutors;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListeningExecutorService;

import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class ParsePipelineTest {
  @Rule
  public TemporaryPaths tmp = new TemporaryPaths();

  @Rule
  public ExpectedException expectedException = ExpectedException.none();

  @Test
  public void speculativeDepsTraversal() throws Exception {
    Fixture fixture = new Fixture("pipeline_test");
    Cell cell = fixture.getCell();
    TargetNode<?> libTargetNode = fixture.getParsePipeline().getTargetNode(
        cell,
        BuildTargetFactory.newInstance(cell.getFilesystem(), "//:lib"));
    fixture.close();
    for (BuildTarget dep : libTargetNode.getDeps()) {
      assertThat(fixture.getCache().lookupTargetNode(cell, dep), Matchers.notNullValue());
    }
  }

  @Test
  public void missingTarget() throws Exception {
    try (Fixture fixture = new Fixture("parse_rule_with_bad_dependency")) {
      Cell cell = fixture.getCell();
      expectedException.expect(HumanReadableException.class);
      expectedException.expectMessage("No rule found when resolving target //:notthere");
      fixture.getParsePipeline().getTargetNode(
          cell,
          BuildTargetFactory.newInstance(cell.getFilesystem(), "//:notthere"));
    }
  }

  @Test
  public void missingBuildFile() throws Exception {
    try (Fixture fixture = new Fixture("parse_rule_with_bad_dependency")) {
      Cell cell = fixture.getCell();
      expectedException.expect(BuildFileParseException.class);
      expectedException.expectMessage(
          Matchers.stringContainsInOrder(
              "Parse error for build file",
              "No such file or directory"));
      fixture.getParsePipeline().getAllTargetNodes(
          cell,
          cell.getFilesystem().resolve("no/such/file/BUCK"));
    }
  }

  @Test
  public void missingBuildFileRaw() throws Exception {
    try (Fixture fixture = new Fixture("parse_rule_with_bad_dependency")) {
      Cell cell = fixture.getCell();
      expectedException.expect(BuildFileParseException.class);
      expectedException.expectMessage(
          Matchers.stringContainsInOrder(
              "Parse error for build file",
              "No such file or directory"));
      fixture.getParsePipeline().getRawNodes(
          cell,
          cell.getFilesystem().resolve("no/such/file/BUCK"));
    }
  }

  @Test
  public void badDependency() throws Exception {
    try (Fixture fixture = new Fixture("parse_rule_with_bad_dependency")) {
      Cell cell = fixture.getCell();
      fixture.getParsePipeline().getTargetNode(
          cell,
          BuildTargetFactory.newInstance(cell.getFilesystem(), "//:base"));
    }
  }

  private static class ParsePipelineCache implements ParsePipeline.Cache {
    private final Map<BuildTarget, TargetNode<?>> targetNodeMap = new HashMap<>();
    private final Map<Path, ImmutableList<Map<String, Object>>> rawNodeMap = new HashMap<>();

    @Override
    public synchronized Optional<TargetNode<?>> lookupTargetNode(
        Cell cell, BuildTarget target) {
      return Optional.<TargetNode<?>>fromNullable(targetNodeMap.get(target));
    }

    @Override
    public synchronized TargetNode<?> putTargetNodeIfNotPresent(
        Cell cell, BuildTarget target, TargetNode<?> targetNode) {
      if (!targetNodeMap.containsKey(target)) {
        targetNodeMap.put(target, targetNode);
      }
      return targetNodeMap.get(target);
    }

    @Override
    public synchronized Optional<ImmutableList<Map<String, Object>>> lookupRawNodes(
        Cell cell, Path buildFile) {
      return Optional.fromNullable(rawNodeMap.get(buildFile));
    }

    @Override
    public synchronized ImmutableList<Map<String, Object>> putRawNodesIfNotPresent(
        Cell cell, Path buildFile, ImmutableList<Map<String, Object>> rawNodes) {
      if (!rawNodeMap.containsKey(buildFile)) {
        rawNodeMap.put(buildFile, rawNodes);
      }
      return rawNodeMap.get(buildFile);
    }
  }

  private class Fixture implements AutoCloseable {

    private ProjectWorkspace workspace;
    private BuckEventBus eventBus;
    private TestConsole console;
    private ParsePipeline parsePipeline;
    private Cell cell;
    private ParsePipelineCache cache;
    private ListeningExecutorService executorService;

    public Fixture(String scenario) throws Exception {
      this.workspace = TestDataHelper.createProjectWorkspaceForScenario(
          this,
          scenario,
          tmp);
      this.eventBus = BuckEventBusFactory.newInstance();
      this.console = new TestConsole();
      this.workspace.setUp();

      this.cell = this.workspace.asCell();
      this.cache = new ParsePipelineCache();
      final TypeCoercerFactory coercerFactory = new DefaultTypeCoercerFactory();
      final ConstructorArgMarshaller constructorArgMarshaller =
          new ConstructorArgMarshaller(coercerFactory);

      ParserLeaseVendor<ProjectBuildFileParser> vendorForTest = new ParserLeaseVendor<>(
          4, // max parsers
          new Function<Cell, ProjectBuildFileParser>() {
            @Override
            public ProjectBuildFileParser apply(Cell input) {
              return input.createBuildFileParser(constructorArgMarshaller, console, eventBus);
            }
          }
      );
      final TargetNodeListener nodeListener = new TargetNodeListener() {
        @Override
        public void onCreate(Path buildFile, TargetNode<?> node) throws IOException {
        }
      };
      this.executorService = com.google.common.util.concurrent.MoreExecutors.listeningDecorator(
          MoreExecutors.newSingleThreadExecutor("test"));
      this.parsePipeline = new ParsePipeline(
          this.cache,
          new ParsePipeline.Delegate() {
            @Override
            public TargetNode<?> createTargetNode(
                Cell cell, Path buildFile, BuildTarget target, Map<String, Object> rawNode) {
              return DaemonicParserState.createTargetNode(
                  eventBus, cell, buildFile, target,
                  rawNode, constructorArgMarshaller, coercerFactory, nodeListener);
            }
          },
          this.executorService,
          this.eventBus,
          vendorForTest,
          true);
    }

    public ParsePipeline getParsePipeline() {
      return parsePipeline;
    }

    public Cell getCell() {
      return cell;
    }

    public ParsePipelineCache getCache() {
      return cache;
    }

    @Override
    public void close() throws Exception {
      com.google.common.util.concurrent.MoreExecutors.shutdownAndAwaitTermination(
          executorService,
          5,
          TimeUnit.SECONDS);
      parsePipeline.close();
    }
  }

}


text:
package com.github.ambry.commons;

import com.github.ambry.account.Account;
import com.github.ambry.account.Container;
import com.github.ambry.messageformat.BlobProperties;
import com.github.ambry.notification.BlobReplicaSourceType;
import com.github.ambry.notification.NotificationBlobType;
import com.github.ambry.notification.NotificationSystem;
import com.github.ambry.notification.UpdateType;
import com.github.ambry.store.MessageInfo;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Logs all events at DEBUG level.
 */
public class LoggingNotificationSystem implements NotificationSystem {
  private static final Logger logger = LoggerFactory.getLogger(LoggingNotificationSystem.class);

  @Override
  public void close() throws IOException {
    // No op
  }

  @Override
  public void onBlobCreated(String blobId, BlobProperties blobProperties, Account account, Container container,
      NotificationBlobType notificationBlobType) {
    logger.debug(
        "onBlobCreated {}, blobProperties {}, accountName {}, accountId{}, containerName {}, containerId {}, blobType {}",
        blobId, blobProperties, account == null ? null : account.getName(), account == null ? null : account.getId(),
        container == null ? null : container.getName(), container == null ? null : container.getId(),
        notificationBlobType);
  }

  @Override
  public void onBlobTtlUpdated(String blobId, String serviceId, long expiresAtMs, Account account,
      Container container) {
    logger.debug("onBlobTtlUpdated {}, serviceId {}, accountName {}, accountId{}, containerName {}, containerId {}, {}",
        blobId, serviceId, account == null ? null : account.getName(), account == null ? null : account.getId(),
        container == null ? null : container.getName(), container == null ? null : container.getId(), expiresAtMs);
  }

  @Override
  public void onBlobDeleted(String blobId, String serviceId, Account account, Container container) {
    logger.debug("onBlobDeleted {}", blobId,
        ", " + serviceId + ", accountName " + (account == null ? null : account.getName()) + ", accountId" + (
            account == null ? null : account.getId()) + ", containerName " + (container == null ? null
            : container.getName()) + ", containerId " + (container == null ? null : container.getId()));
  }

  @Override
  public void onBlobUndeleted(String blobId, String serviceId, Account account, Container container) {
    logger.debug("onBlobUndeleted {}", blobId,
        ", " + serviceId + ", accountName " + (account == null ? null : account.getName()) + ", accountId" + (
            account == null ? null : account.getId()) + ", containerName " + (container == null ? null
            : container.getName()) + ", containerId " + (container == null ? null : container.getId()));

  }

  @Override
  public void onBlobReplicaCreated(String sourceHost, int port, String blobId, BlobReplicaSourceType sourceType) {
    logger.debug("onBlobReplicaCreated {}, {}, {}, {}", sourceHost, port, blobId, sourceType);
  }

  @Override
  public void onBlobReplicaDeleted(String sourceHost, int port, String blobId, BlobReplicaSourceType sourceType) {
    logger.debug("onBlobReplicaDeleted {}, {}, {}, {}", sourceHost, port, blobId, sourceType);
  }

  @Override
  public void onBlobReplicaUpdated(String sourceHost, int port, String blobId, BlobReplicaSourceType sourceType,
      UpdateType updateType, MessageInfo info) {
    logger.debug("onBlobReplicaUpdated {}, {}, {}, {}, {}, {}", sourceHost, port, blobId, sourceType, updateType, info);
  }

  @Override
  public void onBlobReplicaUndeleted(String sourceHost, int port, String blobId, BlobReplicaSourceType sourceType) {
    logger.debug("onBlobReplicaUndeleted {}, {}, {}, {}", sourceHost, port, blobId, sourceType);
  }
}


text:
layout: homepage
home: true
backgrounds:
    - /assets/images/backgrounds/noble-view-main.jpg
---

        {% assign posts = site.posts | sort:"date" %}
        {% for post in posts %}

{{ post.title }}

        {% endfor %}


text:
from utils import weighted_random_subreddit

opts = ['ImaginaryArchers',
        'ImaginaryAssassins',
        'ImaginaryAstronauts',
        'ImaginaryBoners',
        'ImaginaryClerics',
        'ImaginaryKnights',
        'ImaginaryLovers',
        'ImaginaryMythology',
        'ImaginaryNobles',
        'ImaginaryScholars',
        'ImaginarySoldiers',
        'ImaginaryVikings',
        'ImaginaryWarriors',
        'ImaginaryWitches',
        'ImaginaryWizards',
        'ImaginaryAliens',
        'ImaginaryAngels',
        'ImaginaryAnimals',
        'ImaginaryDwarves',
        'ImaginaryElves',
        'ImaginaryFaeries',
        'ImaginaryHumans',
        'ImaginaryImmortals',
        'ImaginaryMerfolk',
        'ImaginaryOrcs',

        'ImaginaryBattlefields',
        'ImaginaryCityscapes',
        'ImaginaryHellscapes',
        'ImaginaryMindscapes',
        'ImaginaryPathways',
        'ImaginarySeascapes',
        'ImaginarySkyscapes',
        'ImaginaryStarscapes',
        'ImaginaryWeather',
        'ImaginaryWildlands',
        'ImaginaryWorlds',

        'ImaginaryArchitecture',
        'ImaginaryCastles',
        'ImaginaryDwellings',
        'ImaginaryInteriors',
        'ImaginaryLibraries',
        'ImaginaryTaverns',

        'ImaginaryBeasts',
        'ImaginaryBehemoths',
        'ImaginaryCarnage',
        'ImaginaryDemons',
        'ImaginaryDragons',
        'ImaginaryElementals',
        'ImaginaryHorrors',
        'ImaginaryHybrids',
        'ImaginaryLeviathans',
        'ImaginaryMonsterGirls',
        'ImaginaryUndead',
        'ImaginaryWorldEaters',

        'ImaginaryAirships',
        'ImaginaryAviation',
        'ImaginaryArmor',
        'ImaginaryCybernetics',
        'ImaginaryCyberpunk',
        'ImaginaryFutureWar',
        'ImaginaryFuturism',
        'ImaginaryMechs',
        'ImaginaryPortals',
        'ImaginaryRobotics',
        'ImaginaryStarships',
        'ImaginarySteampunk',
        'ImaginaryVehicles',
        'ImaginaryVessels',
        'ImaginaryWarships',
        'ImaginaryWeaponry',

        'ImaginaryAww',
        'ImaginaryBestOf',
        'ImaginaryColorscapes',
        'ImaginaryFeels',
        'ImaginaryHistory',
        'ImaginaryMaps',
        'ImaginaryPets',
        'ImaginarySliceofLife',
        'ImaginaryNetwork',
        'ImaginaryTurtleWorlds',
        'ImaginaryUnofficial',
        'ImaginaryWTF']

weight = 1. / len(opts)

# Subreddit that will be a source of content
subreddit = weighted_random_subreddit({k: weight for k in opts})

t_channel = '@r_imaginary_network'

# r_imaginary_wastelands

def send_post(submission, r2t):
    return r2t.send_simple(submission,
                           min_upvotes_limit=20,
                           text=False,
                           gif=False,
                           img=True,
                           album=False,
                           other=False
                           )