text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Tutorial — AutoLogin 0.1.0 documentation</title>

    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="AutoLogin 0.1.0 documentation" href="index.html" />
    <link rel="prev" title="Introduction" href="intro.html" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">

Tutorial¶

Install¶

You shouldn’t have to do anything fancy. Just check out the code and run this
command from the project root

pip install -r requirements.txt

Running¶

From the project root, start the autologin service

python service.py

Followed by

scrapyd

Usage¶

Here is an example of AutoLogin usage

$ curl "http://localhost:5000/?seedurl=https://github.com/&username=actest1234&password=passpasspass123"

Note how we only specified the GitHub homepage. We don’t need to specify the
actual login page, or any other information on the site: autologin will crawl
from the starting URL, find the login form, and submit authentication
credentials seamlessly.

The response looks like this

{
   "redirected_to": "https://github.com/",
   "auth_headers":
   {
      "Accept-Language":
      [
         "en"
      ],

      "Accept-Encoding":
      [
         "gzip,deflate"
      ],

      "Accept":
      [
         "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
      ],

      "User-Agent":
      [
         "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:33.0) Gecko/20100101 Firefox/33.0"
      ],

      "Referer":
      [
         "https://github.com/login"
      ],

      "Cookie":
      [
         "_gh_sess=eyJsYXN0X3dyaXRlIjoxNDE2NDM3NzU1MTQ1LCJzZXNzaW9uX2lkIjoiZWI1YzJkYjE3YWFhNDQ4OWU1ZWZjN2Q5ZGFjZjRkZjIifQ%3D%3D--06456947bdba7a9b84b8a8938eb7086da99ef3f0; user_session=Xg9CSIRrxSCy2eZfv8_w4bJzd2iW9ZC5HG6oTIR8vhsSvNmNVG0f-0jGqnuQ4cgY58QGs_fnItf4Nnir; logged_in=yes; dotcom_user=actest1234"
      ]
   }
}

If you then use the returned headers in your own tool, the website will think
you’re authenticated – because you are! Enjoy!

AutoLogin

Navigation

Introduction

Tutorial

Install

Running

Usage

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

      ©2014, Alejandro Caceres, Amanda Towler, Mikhail Korobov, Tomas Fornara.

      |
      Powered by Sphinx 1.3.1
      & Alabaster 0.7.6

      |
      Page source


text:
package org.opencb.opencga.core.tools.result;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.opencb.commons.datastore.core.Event;
import org.opencb.commons.datastore.core.ObjectMap;
import org.opencb.opencga.core.exceptions.ToolException;
import org.opencb.opencga.core.tools.OpenCgaToolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class ExecutionResultManager {
    public static final String FILE_EXTENSION = ".result.json";
    public static final String SWAP_FILE_EXTENSION = ".swap" + FILE_EXTENSION;

    private final Path outDir;
    private final ObjectWriter objectWriter;
    private final ObjectReader objectReader;

    private Thread thread;
    private File file;
    private File swapFile;
    private boolean initialized;
    private boolean closed;
    private final Logger logger = LoggerFactory.getLogger(ExecutionResultManager.class);
    private int monitorThreadPeriod = 60000;

    public ExecutionResultManager(String toolId, Path outDir) throws ToolException {
        this.outDir = outDir.toAbsolutePath();
        ObjectMapper objectMapper = new ObjectMapper();
//        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectWriter = objectMapper.writerFor(ExecutionResult.class).withDefaultPrettyPrinter();
        objectReader = objectMapper.readerFor(ExecutionResult.class);
        initialized = false;
        closed = false;

        file = outDir.toFile();

        if (!file.exists()) {
            throw new ToolException("Output directory '" + outDir + "' does not exist");
        }
        if (!file.isDirectory()) {
            throw new ToolException("Output directory '" + outDir + "' does not a directory");
        }
        if (!file.canWrite()) {
            throw new ToolException("Write permission denied for output directory '" + outDir + "'");
        }
        if (!StringUtils.isAlphanumeric(toolId.replaceAll("[-_]", ""))) {
            throw new ToolException("Invalid ToolId. The tool id can only contain alphanumeric characters, ',' and '_'.");
        }

        file = outDir.resolve(toolId + FILE_EXTENSION).toFile();
        swapFile = outDir.resolve(toolId + SWAP_FILE_EXTENSION).toFile();
    }

    public synchronized ExecutionResultManager init(ObjectMap params, ObjectMap executorParams) throws ToolException {
        if (initialized) {
            throw new ToolException(getClass().getName() + " already initialized!");
        }
        initialized = true;

        Date now = now();
        ExecutionResult execution = new ExecutionResult()
                .setExecutor(new ExecutorInfo()
                        .setId(executorParams.getString(OpenCgaToolExecutor.EXECUTOR_ID))
                        .setParams(executorParams))
                .setStart(now);
        execution.getStatus()
                .setDate(now)
                .setName(Status.Type.RUNNING);

        write(execution);
        startMonitorThread();
        return this;
    }

    public ExecutionResultManager setMonitorThreadPeriod(int monitorThreadPeriod) {
        this.monitorThreadPeriod = monitorThreadPeriod;
        return this;
    }

    public void setSteps(List<String> steps) throws ToolException {
        updateResult(executionResult -> {
            executionResult.setSteps(new ArrayList<>(steps.size()));
            for (String step : steps) {
                executionResult.getSteps().add(new ToolStep(step, null, null, Status.Type.PENDING, new ObjectMap()));
            }
            return null;
        });
    }

    public boolean isClosed() {
        return closed;
    }

    public synchronized ExecutionResult close() throws ToolException {
        return close(null);
    }

    public synchronized ExecutionResult close(Exception exception) throws ToolException {
        if (closed) {
            throw new ToolException(getClass().getName() + " already closed!");
        }
        thread.interrupt();

        ExecutionResult execution = read();

        Date now = now();
        execution.setEnd(now);
        execution.getStatus()
                .setDate(now);

        ToolStep step;
        if (StringUtils.isEmpty(execution.getStatus().getStep())) {
            if (CollectionUtils.isEmpty(execution.getSteps())) {
                execution.setSteps(Collections.singletonList(new ToolStep().setId("check")));
            }
            step = execution.getSteps().get(0);
            step.setStart(execution.getStart());
        } else {
            step = getStep(execution, execution.getStatus().getStep());
        }

        Status.Type finalStatus;
        if (exception == null) {
            finalStatus = Status.Type.DONE;
            for (Event event : execution.getEvents()) {
                if (event.getType().equals(Event.Type.ERROR)) {
                    // If there is any ERROR event the final status will be ERROR
                    finalStatus = Status.Type.ERROR;
                    break;
                }
            }
        } else {
            addError(exception, execution);
            finalStatus = Status.Type.ERROR;
        }

        execution.getStatus()
                .setStep(null)
                .setName(finalStatus);

        if (Status.Type.RUNNING.equals(step.getStatus()) || Status.Type.PENDING.equals(step.getStatus())) {
            step.setStatus(finalStatus);
            step.setEnd(now);
        }

        write(execution);
        closed = true;
        return execution;
    }

    public void setExecutorInfo(ExecutorInfo executorInfo) throws ToolException {
        updateResult(result -> result.setExecutor(executorInfo));
    }

    public void addWarning(String warningMessage) throws ToolException {
        updateResult(result -> result.getEvents().add(new Event(Event.Type.WARNING, warningMessage)));
    }

    public void addError(Exception exception) throws ToolException {
        updateResult(result -> addError(exception, result));
    }

    private boolean addError(Exception exception, ExecutionResult execution) {
        return execution.getEvents().add(new Event(Event.Type.ERROR, exception.getMessage()));
    }

    public void addAttribute(String key, Object value) throws ToolException {
        updateResult(result -> result.getAttributes().put(key, value));
    }

    public void addStepAttribute(String key, Object value) throws ToolException {
        updateResult(result -> {
            ToolStep step;
            if (StringUtils.isEmpty(result.getStatus().getStep())) {
                step = result.getSteps().get(0);
            } else {
                step = getStep(result, result.getStatus().getStep());
            }
            return step.getAttributes().put(key, value);
        });
    }

    public void errorStep() throws ToolException {
        updateResult(result -> getStep(result, result.getStatus().getStep())
                .setStatus(Status.Type.ERROR).setEnd(now()));
    }

    public boolean checkStep(String stepId) throws ToolException {
        return updateResult(result -> {

            if (StringUtils.isNotEmpty(result.getStatus().getStep())) {
                // End previous step

                ToolStep step = getStep(result, result.getStatus().getStep());
                if (step.getStatus().equals(Status.Type.RUNNING)) {
                    step.setStatus(Status.Type.DONE);
                    step.setEnd(now());
                }
            }

            result.getStatus().setStep(stepId);
            ToolStep step = getStep(result, stepId);
            if (step.getStatus().equals(Status.Type.DONE)) {
                return false;
            } else {
                step.setStatus(Status.Type.RUNNING);
                step.setStart(now());
                return true;
            }
        });
    }

    private ToolStep getStep(ExecutionResult execution, String stepId) throws ToolException {
        for (ToolStep step : execution.getSteps()) {
            if (step.getId().equals(stepId)) {
                return step;
            }
        }

        List<String> steps = execution.getSteps().stream().map(ToolStep::getId).collect(Collectors.toList());

        throw new ToolException("Step '" + stepId + "' not found. Available steps: " + steps);
    }

    public void addExternalFile(URI file) throws ToolException {
        updateResult(execution -> {
            execution.getExternalFiles().add(file);
            return null;
        });
    }

    private void updateStatusDate() throws ToolException {
        updateResult(result -> result.getStatus().setDate(now()));
    }

    @FunctionalInterface
    public interface ExecutionResultFunction<R> {
        R apply(ExecutionResult execution) throws ToolException;
    }

    private synchronized <R> R updateResult(ExecutionResultFunction<R> update) throws ToolException {
        ExecutionResult execution = read();
        R apply = update.apply(execution);
        write(execution);
        return apply;
    }

    public ExecutionResult read() throws ToolException {
        try {
            return objectReader.readValue(file);
        } catch (IOException e) {
            throw new ToolException("Error reading ExecutionResult", e);
        }

    }

    private synchronized void write(ExecutionResult execution) throws ToolException {
        int maxAttempts = 3;
        int attempts = 0;
        while (attempts < maxAttempts) {
            attempts++;
            try {
                if (attempts < maxAttempts) {
                    // Perform atomic writes using an intermediate temporary swap file
                    try (OutputStream os = new BufferedOutputStream(new FileOutputStream(swapFile))) {
                        objectWriter.writeValue(os, execution);
                    }
                    Files.move(swapFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
                } else {
                    try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) {
                        objectWriter.writeValue(os, execution);
                    }
                }
            } catch (IOException e) {
                if (attempts < maxAttempts) {
                    logger.warn("Error writing ExecutionResult: " + e.toString());
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException interruption) {
                        // Ignore interruption
                        Thread.currentThread().interrupt();
                    }
                } else {
                    throw new ToolException("Error writing ExecutionResult", e);
                }
            }
        }
    }

    private Date now() {
        return Date.from(Instant.now());
    }

    private String getDateTime() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        return dtf.format(now);
    }

    private Thread startMonitorThread() {
        thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    Thread.sleep(monitorThreadPeriod);
                } catch (InterruptedException e) {
                    return;
                }

                try {
                    updateStatusDate();
                } catch (ToolException e) {
                    logger.error("Error updating status date", e);
                }
            }
        });
        thread.start();
        return thread;
    }
}

redpajama_set_name: RedPajamaGithub


text:
///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Image (gli.g-truc.net)
///
/// Copyright (c) 2008 - 2013 G-Truc Creation (www.g-truc.net)
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///
/// @ref core
/// @file gli/core/operation.hpp
/// @date 2008-12-19 / 2013-01-12
/// @author Christophe Riccio
///////////////////////////////////////////////////////////////////////////////////

#pragma once

#include "texture2d.hpp"

namespace gli
{
/*
	texture2D duplicate(texture2D const & Texture);
	texture2D flip(texture2D const & Texture);
	texture2D mirror(texture2D const & Texture);
	texture2D swizzle(
		texture2D const & Texture,
		glm::uvec4 const & Channel);
	texture2D crop(
		texture2D const & Texture,
		texture2D::dimensions_type const & Position,
		texture2D::dimensions_type const & Size);

	image2D crop(
		image2D const & Image,
		image2D::dimensions_type const & Position,
		image2D::dimensions_type const & Size);

	image2D copy(
		image2D const & SrcImage,
		image2D::dimensions_type const & SrcPosition,
		image2D::dimensions_type const & SrcSize,
		image2D & DstImage,
		image2D::dimensions_type const & DstPosition);
*/
	//image operator+(image const & MipmapA, image const & MipmapB);
	//image operator-(image const & MipmapA, image const & MipmapB);
	//image operator*(image const & MipmapA, image const & MipmapB);
	//image operator/(image const & MipmapA, image const & MipmapB);

	//namespace wip
	//{
	//	template <typename GENTYPE, template <typename> class SURFACE>
	//	GENTYPE fetch(SURFACE<GENTYPE> const & Image)
	//	{
	//		return GENTYPE();
	//	}

	//	template
	//	<
	//		typename GENTYPE,
	//		template
	//		<
	//			typename
	//		>
	//		class SURFACE,
	//		template
	//		<
	//			typename,
	//			template
	//			<
	//				typename
	//			>
	//			class
	//		>
	//		class IMAGE
	//	>
	//	GENTYPE fetch(IMAGE<GENTYPE, SURFACE> const & Image)
	//	{
	//		return GENTYPE();
	//	}
	//}//namespace wip

}//namespace gli

#include "operation.inl"


text:
using System;
using System.Collections.Generic;
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.KVDBLayer;
using BTDB.StreamLayer;

namespace BTDB.ODBLayer;

public class ODBSetFieldHandler : IFieldHandler, IFieldHandlerWithNestedFieldHandlers, IFieldHandlerWithInit
{
    readonly IObjectDB _odb;
    readonly ITypeConvertorGenerator _typeConvertGenerator;
    readonly byte[] _configuration;
    readonly IFieldHandler _keysHandler;
    int _configurationId;
    Type? _type;

    public ODBSetFieldHandler(IObjectDB odb, Type type, IFieldHandlerFactory fieldHandlerFactory)
    {
        _odb = odb;
        _typeConvertGenerator = odb.TypeConvertorGenerator;
        _type = type;
        _keysHandler = fieldHandlerFactory.CreateFromType(type.GetGenericArguments()[0],
            FieldHandlerOptions.Orderable | FieldHandlerOptions.AtEndOfStream);
        var writer = new SpanWriter();
        writer.WriteFieldHandler(_keysHandler);
        _configuration = writer.GetSpan().ToArray();
        CreateConfiguration();
    }

    public ODBSetFieldHandler(IObjectDB odb, byte[] configuration)
    {
        _odb = odb;
        var fieldHandlerFactory = odb.FieldHandlerFactory;
        _typeConvertGenerator = odb.TypeConvertorGenerator;
        _configuration = configuration;
        var reader = new SpanReader(configuration);
        _keysHandler = fieldHandlerFactory.CreateFromReader(ref reader,
            FieldHandlerOptions.Orderable | FieldHandlerOptions.AtEndOfStream);
        CreateConfiguration();
    }

    ODBSetFieldHandler(IObjectDB odb, byte[] configuration, IFieldHandler specializedKeyHandler)
    {
        _odb = odb;
        _typeConvertGenerator = odb.TypeConvertorGenerator;
        _configuration = configuration;
        _keysHandler = specializedKeyHandler;
        CreateConfiguration();
    }

    void CreateConfiguration()
    {
        HandledType();
        var keyAndValueTypes = _type!.GetGenericArguments();
        _configurationId = ODBDictionaryConfiguration.Register(_keysHandler, keyAndValueTypes[0], null, null);
        var cfg = ODBDictionaryConfiguration.Get(_configurationId);
        lock (cfg)
        {
            cfg.KeyReader ??= CreateReader(_keysHandler, keyAndValueTypes[0]);
            cfg.KeyWriter ??= CreateWriter(_keysHandler, keyAndValueTypes[0]);
        }
    }

    object CreateWriter(IFieldHandler fieldHandler, Type realType)
    {
        //Action<T, ref SpanWriter, IWriterCtx>
        var delegateType = typeof(WriterFun<>).MakeGenericType(realType);
        var dm = ILBuilder.Instance.NewMethod(fieldHandler.Name + "Writer", delegateType);
        var ilGenerator = dm.Generator;
        fieldHandler.Save(ilGenerator, il => il.Ldarg(1), il => il.Ldarg(2),
            il => il.Ldarg(0).Do(_typeConvertGenerator.GenerateConversion(realType, fieldHandler.HandledType())!));
        ilGenerator.Ret();
        return dm.Create();
    }

    object CreateReader(IFieldHandler fieldHandler, Type realType)
    {
        //Func<ref SpanReader, IReaderCtx, T>
        var delegateType = typeof(ReaderFun<>).MakeGenericType(realType);
        var dm = ILBuilder.Instance.NewMethod(fieldHandler.Name + "Reader", delegateType);
        var ilGenerator = dm.Generator;
        fieldHandler.Load(ilGenerator, il => il.Ldarg(0), il => il.Ldarg(1));
        ilGenerator
            .Do(_typeConvertGenerator.GenerateConversion(fieldHandler.HandledType(), realType)!)
            .Ret();
        return dm.Create();
    }

    public static string HandlerName => "ODBSet";

    public string Name => HandlerName;

    public byte[] Configuration => _configuration;

    public static bool IsCompatibleWithStatic(Type type, FieldHandlerOptions options)
    {
        if ((options & FieldHandlerOptions.Orderable) != 0) return false;
        return type.IsGenericType && IsCompatibleWithCore(type);
    }

    static bool IsCompatibleWithCore(Type type)
    {
        var genericTypeDefinition = type.GetGenericTypeDefinition();
        return genericTypeDefinition == typeof(IOrderedSet<>);
    }

    public bool IsCompatibleWith(Type type, FieldHandlerOptions options)
    {
        return IsCompatibleWithStatic(type, options);
    }

    public Type HandledType()
    {
        return _type ?? GenerateType(null);
    }

    public bool NeedsCtx()
    {
        return true;
    }

    public void Load(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx)
    {
        var genericArguments = _type!.GetGenericArguments();
        var instanceType = typeof(ODBSet<>).MakeGenericType(genericArguments);
        var constructorInfo = instanceType.GetConstructor(
            new[] { typeof(IInternalObjectDBTransaction), typeof(ODBDictionaryConfiguration), typeof(ulong) });
        ilGenerator
            .Do(pushCtx)
            .Castclass(typeof(IDBReaderCtx))
            .Callvirt(() => default(IDBReaderCtx).GetTransaction())
            .LdcI4(_configurationId)
            .Call(() => ODBDictionaryConfiguration.Get(0))
            .Do(pushReader)
            .Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt64))!)
            .Newobj(constructorInfo!)
            .Castclass(_type);
    }

    public bool NeedInit()
    {
        return true;
    }

    public void Init(IILGen ilGenerator, Action<IILGen> pushReaderCtx)
    {
        var genericArguments = _type!.GetGenericArguments();
        var instanceType = typeof(ODBSet<>).MakeGenericType(genericArguments);
        var constructorInfo = instanceType.GetConstructor(
            new[] { typeof(IInternalObjectDBTransaction), typeof(ODBDictionaryConfiguration) });
        ilGenerator
            .Do(pushReaderCtx)
            .Castclass(typeof(IDBReaderCtx))
            .Callvirt(() => default(IDBReaderCtx).GetTransaction())
            .LdcI4(_configurationId)
            .Call(() => ODBDictionaryConfiguration.Get(0))
            .Newobj(constructorInfo!)
            .Castclass(_type);
    }

    public void Skip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen>? pushCtx)
    {
        ilGenerator
            .Do(pushReader)
            .Call(typeof(SpanReader).GetMethod(nameof(SpanReader.SkipVUInt64))!);
    }

    public void Save(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushCtx, Action<IILGen> pushValue)
    {
        var genericArguments = _type!.GetGenericArguments();
        var instanceType = typeof(ODBSet<>).MakeGenericType(genericArguments);
        ilGenerator
            .Do(pushWriter)
            .Do(pushCtx)
            .Do(pushValue)
            .LdcI4(_configurationId)
            .Call(instanceType.GetMethod(nameof(ODBSet<int>.DoSave))!);
    }

    public IFieldHandler SpecializeLoadForType(Type type, IFieldHandler? typeHandler, IFieldHandlerLogger? logger)
    {
        if (_type != type)
            GenerateType(type);
        if (_type == type) return this;
        if (!IsCompatibleWithCore(type)) return this;
        var arguments = type.GetGenericArguments();
        var wantedKeyHandler = default(IFieldHandler);
        if (typeHandler is ODBSetFieldHandler dictTypeHandler)
        {
            wantedKeyHandler = dictTypeHandler._keysHandler;
        }

        var specializedKeyHandler = _keysHandler.SpecializeLoadForType(arguments[0], wantedKeyHandler, logger);
        if (wantedKeyHandler == specializedKeyHandler)
        {
            return typeHandler;
        }

        var res = new ODBSetFieldHandler(_odb, _configuration, specializedKeyHandler);
        res.GenerateType(type);
        return res;
    }

    Type GenerateType(Type? compatibleWith)
    {
        if (compatibleWith != null && compatibleWith.GetGenericTypeDefinition() == typeof(IOrderedSet<>))
        {
            return _type = typeof(IOrderedSet<>).MakeGenericType(_keysHandler.HandledType());
        }

        return _type = typeof(ISet<>).MakeGenericType(_keysHandler.HandledType());
    }

    public IFieldHandler SpecializeSaveForType(Type type)
    {
        if (_type != type)
            GenerateType(type);
        return this;
    }

    public IEnumerable<IFieldHandler> EnumerateNestedFieldHandlers()
    {
        yield return _keysHandler;
    }

    public NeedsFreeContent FreeContent(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx)
    {
        var fakeMethod = ILBuilder.Instance.NewMethod<Action>("Relation_fake");
        var fakeGenerator = fakeMethod.Generator;
        if (_keysHandler.FreeContent(fakeGenerator, _ => { }, _ => { }) == NeedsFreeContent.Yes)
            throw new BTDBException("Not supported 'free content' in IOrderedSet");
        ilGenerator
            .Do(pushCtx)
            .Castclass(typeof(IDBReaderCtx))
            .Do(pushReader)
            .Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt64))!)
            .Callvirt(() => default(IDBReaderCtx).RegisterDict(0ul));
        return NeedsFreeContent.Yes;
    }
}


text:
import py, os
from rpython.jit.backend import detect_cpu

cpu = detect_cpu.autodetect()
def pytest_runtest_setup(item):
    if not cpu.startswith('x86'):
        py.test.skip("x86/x86_64 tests skipped: cpu is %r" % (cpu,))
    if cpu == 'x86_64':
        if os.name == "nt":
            py.test.skip("Windows cannot allocate non-reserved memory")
        from rpython.rtyper.lltypesystem import ll2ctypes
        ll2ctypes.do_allocation_in_far_regions()


text:
package database.factory;

import database.ConnectionParam;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

/**
 * ConnectionPoolFactory Test
 * Created by Michael Wong on 2016/1/20.
 */
public class ConnectionPoolFactoryTest {

    @Test
    public void testGetConnection() throws SQLException {

        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "root";

        ConnectionParam connectionParam = new ConnectionParam.ConnectionParamBuilder(driver, url, user, password).build();
        ConnectionPoolFactory.registerConnectionPool("test", connectionParam);

        List<Connection> connectionList = new ArrayList<>();

        for(int i = 0; i < 12; i++) {
            connectionList.add(ConnectionPoolFactory.getConnection("test"));
        }

        print();

        close(connectionList);

        print();

        connectionList.clear();

        for(int i = 0; i < 12; i++) {
            connectionList.add(ConnectionPoolFactory.getConnection("test"));
        }

        print();

        close(connectionList);

        ConnectionPoolFactory.unRegisterConnectionPool("test");

    }

    @Test(expected = IllegalArgumentException.class)
    public void testException() {
        try {
            ConnectionPoolFactory.getConnection("test");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void close(List<Connection> connectionList) throws SQLException {
        for(Connection conn : connectionList) {
            if (conn != null) {
                conn.close();
            }
        }
    }

    private void print() {
        System.out.println("idle: " + ConnectionPoolFactory.getIdleConnectionQuantity("test"));
        System.out.println("busy: " + ConnectionPoolFactory.getBusyConnectionQuantity("test"));
        System.out.println("size: " + ConnectionPoolFactory.size("test"));
    }

}


text:
"""Implements experimental logic."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from copy import copy
import cPickle as pkl
import math
import os
from dl_bounds.src.data import get_data
from dl_bounds.src.exp_helpers import is_power2
from dl_bounds.src.models import ALL_MODELS
from dl_bounds.src.models import MLPCustom
import numpy as np
import tensorflow as tf

class Experiment(object):
  """Base class for all experiments, implements basic measurements."""

  def __init__(self, conf):
    self.conf = conf

    n_records = self.get_n_records()
    assert n_records > 0
    self.is_persistent_experiment = True

    # Generic parameters recorded for all types of experiments
    self.pass_numbers = np.zeros((n_records,), dtype=int)
    self.train_error = np.zeros((n_records,))
    self.train_zero_one_error = np.zeros((n_records,))
    self.train_grad_norm = np.zeros((n_records,))
    self.val_error = np.zeros((n_records,))
    self.val_zero_one_error = np.zeros((n_records,))
    self.val_grad_norm = np.zeros((n_records,))
    self.train_dataset_size = np.zeros((n_records,))

    self.soft_margin_eps_range = [0.001, 0.01, 0.1]
    self.soft_margins = np.zeros((n_records, len(self.soft_margin_eps_range)))

    self.weight_variance = np.zeros((n_records,))
    self.weight_entropy = np.zeros((n_records,))

    self.init_weights = None

  def get_n_records(self):
    if self.conf.log2_snapshots:
      if not is_power2(self.conf.passes):
        raise ValueError("Number of passes must be power of 2.")

      return int(math.log(self.conf.passes, 2)) + 2
    else:
      return int(self.conf.passes / self.conf.snapshot_every_n_passes) + 1

  def measure_on_train_val(self, train_dataset, val_dataset,
                           pass_index, pass_number, model):
    """Performs and memorizes generic measurements on the dataset.

    Args:
      train_dataset: Data provider for the training set.
      val_dataset: Data provider for the validations set.
      pass_index: Index of epoch.
      pass_number: Number of epoch (can differ from index,
                 e.g. pass_number is 2**pass_index).
      model: Model to evaluate on the provided data.
    """
    self.pass_numbers[pass_index] = pass_number
    self.val_error[pass_index] = model.mean_loss_on_dataset(val_dataset)
    self.val_zero_one_error[pass_index] = 1.0 - model.accuracy_on_dataset(
        val_dataset)
    self.val_grad_norm[pass_index] = np.linalg.norm(
        model.compute_gradient_on_dataset(val_dataset))

    self.train_error[pass_index] = model.mean_loss_on_dataset(train_dataset)
    self.train_zero_one_error[pass_index] = (
        1.0 - model.accuracy_on_dataset(train_dataset))
    self.train_grad_norm[pass_index] = np.linalg.norm(
        model.compute_gradient_on_dataset(train_dataset))

    self.train_dataset_size[pass_index] = train_dataset.size

    if self.conf.pflug_diagnostic:
      self.pflug_diagnostic_track = model.pflug_diagnostic_track
      self.pflug_cos_diagnostic_track = model.pflug_cos_diagnostic_track

    self.soft_margins[pass_index, :] = model.eps_margin(
        train_dataset, self.soft_margin_eps_range)

    self.weight_variance[pass_index] = model.weight_variance()
    self.weight_entropy[pass_index] = model.weight_entropy()

  def report_train_val(self, pass_index):
    """Reports various generic measurements on training and validation sets.

    Args:
      pass_index: Index of epoch.
    """
    tf.logging.info("Passes: %s", ", ".join(
        [str(x) for x in self.pass_numbers[:pass_index + 1]]
    ))
    tf.logging.info("Train error: %s", ", ".join(
        ["%.2f" % x for x in self.train_error[:pass_index + 1]]
    ))
    tf.logging.info("Train 0/1 error: %s", ", ".join(
        ["%.2f" % x for x in self.train_zero_one_error[:pass_index + 1]]
    ))
    tf.logging.info("||E^train nabla f(w_T)||: %s", ", ".join(
        ["%.2f" % x for x in self.train_grad_norm[:pass_index + 1]]
    ))

    tf.logging.info("Val error: %s", ", ".join(
        ["%.2f" % x for x in self.val_error[:pass_index + 1]]
    ))
    tf.logging.info("Val 0/1 error: %s", ", ".join(
	       ["%.2f" % x for x in self.val_zero_one_error[:pass_index + 1]]
    ))
    tf.logging.info("||E^val nabla f(w_T)||: %s", ", ".join(
        ["%.2f" % x for x in self.val_grad_norm[:pass_index + 1]]
    ))

    tf.logging.info("Weight var.: %s", ", ".join(
        ["%.2f" % x for x in self.weight_variance[:pass_index + 1]]
    ))
    tf.logging.info("Weight entropy: %s", ", ".join(
        ["%.2f" % x for x in self.weight_entropy[:pass_index + 1]]
    ))

  def get_train_val_measurements(self):
    """Returns a dict with basic measurements registered so far."""
    measurements = dict(
        pass_numbers=self.pass_numbers,
        val_error=self.val_error,
        val_zero_one_error=self.val_zero_one_error,
        val_grad_norm=self.val_grad_norm,
        train_error=self.train_error,
        train_zero_one_error=self.train_zero_one_error,
        train_grad_norm=self.train_grad_norm,
        train_dataset_size=self.train_dataset_size,
        soft_margin_eps_range=self.soft_margin_eps_range,
        soft_margins=self.soft_margins,
        weight_variance=self.weight_variance,
        weight_entropy=self.weight_entropy)

    if self.conf.pflug_diagnostic:
      measurements["pflug_diagnostic"] = np.array(self.pflug_diagnostic_track)
      measurements["pflug_cos_diagnostic"] = np.array(
          self.pflug_cos_diagnostic_track)

    return measurements

  def create_model(self,
                   input_size=None,
                   output_size=None,
                   dataset_size=-1):
    """Creates model and initializes optimizer.

    Args:
      input_size: Input dimension.
      output_size: Output dimension.
      dataset_size: Expected size of the training set (if exp decay is used).

    Returns:
      initialized model (as defined in models.py)
    """
    tf.logging.info("Creating network \"%s\" with seed %d...",
                    self.conf.network, self.conf.network_seed)

    if (self.conf.network.startswith("mlp_")
        and (self.conf.dataset, self.conf.network) not in ALL_MODELS):
      hidden_layer_sizes = map(int, self.conf.network[4:].split("-"))
      model = MLPCustom(input_size, output_size, hidden_layer_sizes)
    else:
      model = ALL_MODELS[(self.conf.dataset, self.conf.network)]()

    if self.conf.exp_decay:
      if self.conf.split_n == -1:
        pass_length = self.conf.batch_size
      else:
        pass_length = self.conf.split_n

      global_step = tf.contrib.framework.get_or_create_global_step()

      num_batches_per_epoch = dataset_size / float(pass_length)
      decay_steps = int(num_batches_per_epoch * self.conf.num_passes_per_decay)
      learning_rate = tf.train.exponential_decay(
          self.conf.learning_rate,
          global_step,
          decay_steps,
          self.conf.learning_rate_decay_factor,
          staircase=True)

      tf.logging.info("""
Using exponential learning rate decay schedule:
initial learning rate = %s
number of passes per decay = %s
learning rate decay factor = %s
      """, self.conf.learning_rate, self.conf.num_passes_per_decay,
                      self.conf.learning_rate_decay_factor)

    else:
      learning_rate = self.conf.learning_rate

    model.initialize(
        init_stddev=self.conf.init_stddev,
        learning_rate=learning_rate,
        seed=self.conf.network_seed,
        optimizer=self.conf.optimizer,
        pflug_diagnostic=self.conf.pflug_diagnostic,
        momentum=self.conf.momentum,
        weight_decay=self.conf.weight_decay,
        init_weights=self.init_weights)

    tf.logging.info("Done.")

    return model

  def train(self, train_dataset, post_create_model_hook=None):
    """Trains a model given a dataset provider.

    Args:
      train_dataset: Dataset provider.
      post_create_model_hook: Callback called after model creation,
        but before training.

    Yields:
      Epoch index and model tuple at the end of every pass.
    """
    g = tf.Graph()
    with g.as_default():
      session = tf.Session(graph=g)
      with session.as_default():
        model = self.create_model(
            input_size=train_dataset.get_input_dim(),
            output_size=train_dataset.get_output_dim(),
            dataset_size=train_dataset.size)

        if post_create_model_hook:
          post_create_model_hook(model)

        tf.logging.info("Initializing global variables...")
        session.run(tf.global_variables_initializer())
        tf.logging.info("Done.")

        tf.logging.info("Snapshot before training.")
        yield 0, model

        for p in range(1, self.conf.passes + 1):

          train_dataset.reset_and_reshuffle(p)
          model.do_pass(train_dataset, self.conf.batch_size)

          do_snapshot = False
          if self.conf.log2_snapshots:
            do_snapshot = is_power2(p)
          else:
            do_snapshot = (p % self.conf.snapshot_every_n_passes) == 0

          if do_snapshot:
            tf.logging.info("Snapshot after pass = %d", p)
            yield p, model

    tf.reset_default_graph()

  def get_filename_path(self):
    """Returns results filename path."""
    path = os.path.join(self.conf.result_path,
                        self.conf.result_filename % self.conf.__dict__)
    return path

  def exists(self):
    if self.is_persistent_experiment:
      path = self.get_filename_path()
      file_exists = tf.gfile.Exists(path)
      if not file_exists:
        tf.logging.info("Will save results to \"%s\".", path)
      return file_exists

  def save(self, rec):
    if self.is_persistent_experiment:
      path = self.get_filename_path()
      extended_rec = copy(rec)

      for (k, v) in self.conf.__dict__.items():
        if k not in extended_rec:
          extended_rec[k] = v

      tf.logging.info("Saving result to \"%s\"...", path)

      with tf.gfile.Open(path, "w") as gf:
        pkl.dump(extended_rec, gf)

      tf.logging.info("Done.")

  def load(self):
    path = self.get_filename_path()
    tf.logging.info("Loading result at \"%s\"...", path)
    with tf.gfile.Open(path, "r") as gf:
      return pkl.load(gf)

  def get_data(self):
    """Retrieves and returns the whole dataset according to experiment spec.

    Returns:
      Dataset provider.
    """
    tf.logging.info(
        "Retrieving data for the \"%s\", split = %d, split size = %d",
        self.conf.dataset, self.conf.split_i, self.conf.split_n)
    data = get_data(
        self.conf.dataset,
        self.conf.data_path,
        self.conf.split_i,
        self.conf.split_n,
        flip_label_ratio=self.conf.flip_labels)
    tf.logging.info("Done.")
    return data


text:
package org.apache.bcel.util;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import org.apache.bcel.classfile.JavaClass;

import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * This repository is used in situations where a Class is created outside the realm of a ClassLoader. Classes are loaded from the file systems using the paths
 * specified in the given class path. By default, this is the value returned by ClassPath.getClassPath(). This repository holds onto classes with
 * SoftReferences, and will reload as needed, in cases where memory sizes are important.
 *
 * @see org.apache.bcel.Repository
 */
public class MemorySensitiveClassPathRepository extends AbstractClassPathRepository {

    private final Map<String, SoftReference<JavaClass>> loadedClasses = new HashMap<>(); // CLASSNAME X JAVACLASS

    public MemorySensitiveClassPathRepository(final ClassPath path) {
        super(path);
    }

    /**
     * Store a new JavaClass instance into this Repository.
     */
    @Override
    public void storeClass(final JavaClass clazz) {
        // Not calling super.storeClass because this subclass maintains the mapping.
        loadedClasses.put(clazz.getClassName(), new SoftReference<>(clazz));
        clazz.setRepository(this);
    }

    /**
     * Remove class from repository
     */
    @Override
    public void removeClass(final JavaClass clazz) {
        loadedClasses.remove(clazz.getClassName());
    }

    /**
     * Find an already defined (cached) JavaClass object by name.
     */
    @Override
    public @Nullable JavaClass findClass(final String className) {
        final SoftReference<JavaClass> ref = loadedClasses.get(className);
        if (ref == null) {
            return null;
        }
        return ref.get();
    }

    /**
     * Clear all entries from cache.
     */
    @Override
    public void clear() {
        loadedClasses.clear();
    }
}


text:
class Observer {
public:
        virtual ~Observer() {};
        virtual void Update() {}
protected:
        Observer() {};
};

#endif


text:
from inspect import getargspec
from functools import wraps

from unuk.contrib.tasks import Task, PeriodicTask, registry

def task(*args, **options):
    """Decorator to create a task class out of any callable,

    Examples:

    .. code-block:: python

        @task()
        def refresh_feed(url):
            return Feed.objects.get(url=url).refresh()

    With setting extra options and using retry.

    .. code-block:: python

        @task(exchange="feeds")
        def refresh_feed(url, **kwargs):
            try:
                return Feed.objects.get(url=url).refresh()
            except socket.error, exc:
                refresh_feed.retry(args=[url], kwargs=kwargs, exc=exc)

    Calling the resulting task:

        >>> refresh_feed("http://example.com/rss") # Regular
        <Feed: http://example.com/rss>
        >>> refresh_feed.delay("http://example.com/rss") # Async
        <AsyncResult: 8998d0f4-da0b-4669-ba03-d5ab5ac6ad5d>

    """

    def inner_create_task_cls(**options):

        def _create_task_cls(fun):
            base = options.pop("base", Task)

            @wraps(fun, assigned=("__module__", "__name__"))
            def run(self, *args, **kwargs):
                return fun(*args, **kwargs)

            # Save the argspec for this task so we can recognize
            # which default task kwargs we're going to pass to it later.
            # (this happens in celery.utils.fun_takes_kwargs)
            run.argspec = getargspec(fun)

            cls_dict = dict(options, run=run,
                            __module__=fun.__module__,
                            __doc__=fun.__doc__)
            T = type(fun.__name__, (base, ), cls_dict)()
            return registry.tasks[T.name] # global instance.

        return _create_task_cls

    if len(args) == 1 and callable(args[0]):
        return inner_create_task_cls()(*args)
    return inner_create_task_cls(**options)

def periodic_task(**options):
    """Task decorator to create a periodic task.

    Example task, scheduling a task once every day:

    .. code-block:: python

        from datetime import timedelta

        @periodic_task(run_every=timedelta(days=1))
        def cronjob(**kwargs):
            logger = cronjob.get_logger(**kwargs)
            logger.warn("Task running...")

    """
    return task(**dict({"base": PeriodicTask}, **options))


text:
<!DOCTYPE html>

    <title>DiscordVoiceError Enumeration Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset="utf-8">

          SwiftDiscord Docs

         (100% documented)

        <form role="search" action="../search.json">
          <input type="text" placeholder="Search documentation" data-typeahead>
        </form>

      SwiftDiscord Reference

      DiscordVoiceError Enumeration Reference

            Guides

                Getting Started

                Installing SwiftDiscord for iOS

            Classes

                DiscordAuditLog

                DiscordBufferedVoiceDataSource

                DiscordClient

                DiscordEncoderMiddleware

                DiscordEngine

                DiscordGuild

                DiscordLazyValue

                DiscordOpusDecoder

                DiscordOpusEncoder

                DiscordRateLimiter

                DiscordShardManager

                DiscordSilenceVoiceDataSource

                DiscordVoiceEngine

                DiscordVoiceFileDataSource

                DiscordVoiceManager

                DiscordVoiceSessionDecoder

            Enumerations

                DiscordActivityType

                DiscordAuditLogActionType

                DiscordChannelType

                DiscordClientOption

                DiscordDispatchEvent

                DiscordEndpoint

                – EndpointRequest

                – Options

                DiscordGatewayCloseReason

                DiscordGatewayCode

                DiscordGatewayPayloadData

                DiscordHeader

                DiscordLogLevel

                DiscordNormalGatewayCode

                DiscordOAuthEndpoint

                DiscordPermissionOverwriteType

                DiscordPresenceStatus

                DiscordVoiceDataSourceStatus

                DiscordVoiceError

                DiscordVoiceGatewayCode

                HTTPContent

            Protocols

                DiscordChannel

                DiscordClientDelegate

                DiscordClientHolder

                DiscordClientSpec

                DiscordDispatchEventHandler

                DiscordEndpointConsumer

                DiscordEngineHeartbeatable

                DiscordEngineSpec

                DiscordGatewayable

                DiscordGuildChannel

                DiscordLogger

                DiscordOpusCodeable

                DiscordRateLimiterSpec

                DiscordShard

                DiscordShardDelegate

                DiscordShardManagerDelegate

                DiscordTextChannel

                DiscordTokenBearer

                DiscordUserActor

                DiscordVoiceDataSource

                DiscordVoiceEngineDelegate

                DiscordVoiceEngineSpec

                DiscordVoiceManagerDelegate

                DiscordWebSocketable

            Structures

                DiscordActivity

                DiscordActivityAssets

                DiscordActivityTimestamps

                DiscordAttachment

                DiscordAuditLogChange

                DiscordAuditLogEntry

                DiscordBan

                DiscordDMChannel

                DiscordEmbed

                – Author

                – Field

                – Footer

                – Image

                – Provider

                – Thumbnail

                – Video

                DiscordEmoji

                DiscordFileUpload

                DiscordGatewayPayload

                DiscordGroupDMChannel

                DiscordGuildChannelCategory

                DiscordGuildMember

                DiscordGuildTextChannel

                DiscordGuildVoiceChannel

                DiscordInvite

                DiscordInviteChannel

                DiscordInviteGuild

                DiscordLazyDictionary

                DiscordLazyDictionaryIndex

                DiscordMessage

                – MessageType

                – MessageActivity

                – MessageApplication

                DiscordOpusVoiceData

                DiscordParty

                DiscordPermission

                DiscordPermissionOverwrite

                DiscordPresence

                DiscordPresenceUpdate

                DiscordRateLimitKey

                – DiscordRateLimitURLParts

                DiscordRawVoiceData

                DiscordReaction

                DiscordRole

                DiscordShardInformation

                – ShardingError

                DiscordToken

                DiscordUser

                DiscordUserGuild

                DiscordVoiceEngineConfiguration

                DiscordVoiceServerInformation

                DiscordVoiceState

                DiscordWebhook

                Snowflake

            Type Aliases

                AttachmentID

                ChannelID

                EmojiID

                GuildID

                IntegrationID

                MessageID

                OverwriteID

                RoleID

                UserID

                WebhookID

DiscordVoiceError

public enum DiscordVoiceError : Error

Represents an error that can occur during voice operations.

                    creationFail

Thrown when a failure occurs creating an encoder.

Declaration

Swift

case creationFail

                    encodeFail

Thrown when a failure occurs encoding.

Declaration

Swift

case encodeFail

                    decodeFail

Thrown when a decode failure occurs.

Declaration

Swift

case decodeFail

                    initialPacket

Thrown when the first packet is received.

Declaration

Swift

case initialPacket

© 2018 . All rights reserved. (Last updated: 2018-06-21)

Generated by jazzy ♪♫ v0.9.1, a Realm project.


text:
The Twitter client is an object centralizing all operations that can be performed via Tweetinvi.

A Twitter client is associated with a specific set of credentials which you provide when creating the client.\
All operations performed by the client will use the associated credentials.

A Twitter client can be used and act as an application or as a user.

``` c#
// Application client
var appClient = new TwitterClient("CONSUMER_KEY", "CONSUMER_SECRET");

// User client
var userClient = new TwitterClient("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");
```

The clients' credentials are available under `userClient.Credentials`.\
These credentials can be changed but my suggestion is that for each new set of credentials you create a new client.

<div class="note">

Note that the credentials information are copied. If you passed a credentials object, changing properties of that object, will not change the properties of the `client.Credentials`
</div>

## Config

The Twitter client uses a default configuration that can be changed to match your needs.

### Proxy

Configure a proxy for your application to connect to the internet.

``` c#
client.Config.ProxyConfig = new ProxyConfig("my-proxy-url")
{
    Credentials = new NetworkCredential("username", "password")
};
```

### HttpRequest Timeout

You can specify the maximum duration of some operations.

``` c#
client.Config.HttpRequestTimeout = TimeSpan.FromSeconds(20);
```

### TweetMode

Older aplications need to use the old format of tweet objects. You can do so by specifying the `TweetMode` at a client level or per request.

``` c#
// will add tweet_mode=compat for any tweet request
client.Config.TweetMode = TweetMode.Compat;

// https://api.twitter.com/1.1/statuses/update.json?status=hello&tweet_mode=compat
await userClient.Tweets.PublishTweetAsync("hello");
```

Configuring the `TweetMode` of a request parameters will take priority over the `TweetMode` value set in the client config.

``` c#
client.Config.TweetMode = TweetMode.Compat;

// https://api.twitter.com/1.1/statuses/update.json?status=hello&tweet_mode=extended
await userClient.Tweets.PublishTweetAsync(new PublishTweetParameters("hello")
{
    TweetMode = TweetMode.Extended
});
```

You can use `TweetMode.None` in a request parameters if you want to remove the compatibility for 1 specific rwequest.

### GetUtcDate

Requests sent to Twitter require a signature with the current utc date included.\
Signing a request with an invalid utc date will result in Twitter rejecting the request.\
By default Tweetinvi will use `Date.UtcNow`.

Some machines are not configured with the correct time and will result in an invalid value of `Date.UtcNow`.\
If the machine is intentionally misconfigured, you can override how tweetinvi gets the utc date time.

``` c#
client.Config.GetUtcDateTime = () =>
{
    // your custom logic to retrieve a utc date time
    return new DateTime();
};
```

### RateLimitTrackerMode

`RateLimitTrackerMode` gives you pre configured solution for managing rate limits in your applications.

To learn more about this config please [read more here](../credentials/rate-limits-handlers).

### RateLimitWaitFudge

When `RateLimitTrackerMode` is enabled, this sets an additional duration to wait after the reset has completed.\
Waiting for an additional duration help make sure that the reset has properly happened on the Twitter side.

``` c#
client.Config.RateLimitWaitFudge = TimeSpan.FromSeconds(2);
```

### Twitter Limits

TwitterLimits are used by the request validators to verify if a request you are attempting to perform is matching the limits imposed by Twitter.\
This can involve the number of items, the size of text or specific values for numbers.

Tweetinvi limits are set as per the documentation and these values might change in the future.\
If these values do change you have the ability to change the TwitterLimits.

``` c#
client.Config.Limits.MESSAGES_GET_MAX_PAGE_SIZE = 100;

try
{
    client.Messages.ParametersValidator.Validate(new GetMessagesParameters
    {
        PageSize = 101
    });
}
catch (TwitterArgumentLimitException e)
{
    // Argument parameters.PageSize was over the limit of 100 page size
    Console.WriteLine(e);
}
```


text:
package com.jlfex.hermes.repository;

import java.util.Date;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.jlfex.hermes.model.Transaction;
import com.jlfex.hermes.model.UserAccount;

/**
 * 交易流水信息仓库
 */
@Repository
public interface TransactionRepository extends JpaRepository<Transaction, String>, JpaSpecificationExecutor<Transaction> {

	/**
	 * 通过来源账户和类型列表以及日期范围查询交易
	 *
	 * @param userAccount
	 * @param types
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	@Query("from Transaction tx where tx.sourceUserAccount = ?1 and type in (?2) and datetime between ?3 and ?4 order by datetime desc")
	public List<Transaction> findBySourceUserAccountAndTypeInAndDatetimeBetween(UserAccount userAccount, List<String> types, Date beginDate, Date endDate);

	/**
	 * 通过来源账户和类型列表以及日期范围分页查询交易
	 *
	 * @param userAccount
	 * @param types
	 * @param beginDate
	 * @param endDate
	 * @param pageable
	 * @return
	 */
	public Page<Transaction> findBySourceUserAccountAndTypeInAndDatetimeBetween(UserAccount userAccount, List<String> types, Date beginDate, Date endDate, Pageable pageable);

	/**
	 * 通过账户查询风险金的所有转入转出
	 */
	@Query("from Transaction tx where tx.sourceUserAccount = ?1 or targetUserAccount = ?2 and type in (?3) ")
	public List<Transaction> findByUserAccountAndTypeIn(UserAccount sourceuserAccount, UserAccount targetuserAccount, List<String> types);

	public Page<Transaction> findBySourceUserAccountAndTypeIn(UserAccount sourceuserAccount, List<String> types, Pageable pageable);

	@Query("from Transaction tx where tx.sourceUserAccount = ?1 and type in (?2) ")
	public List<Transaction> findBySourceUserAccountAndTypeIn(UserAccount sourceuserAccount, List<String> types);

	public Transaction findOneByReferenceAndType(String reference,String type);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.apps.unisabanetaapp.ActividadPrincipal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="Programa"
            android:textSize="16sp"
            android:textStyle="bold" />

        <Spinner
            android:id="@+id/spinnerPrograma"
            style="@style/Platform.Widget.AppCompat.Spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:backgroundTint="@color/colorPrimary"
            android:popupBackground="@color/white"
            android:textSize="12dp" />
    </LinearLayout>

    <android.support.v7.widget.RecyclerView

        android:id="@+id/recicladorHorario"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>


text:
package org.gradle.internal.buildtree;

import com.google.common.base.Joiner;
import org.gradle.api.internal.StartParameterInternal;
import org.gradle.internal.Describables;
import org.gradle.internal.DisplayName;
import org.gradle.internal.hash.Hasher;

public class RunTasksRequirements implements BuildActionModelRequirements {
    private final StartParameterInternal startParameter;

    public RunTasksRequirements(StartParameterInternal startParameter) {
        this.startParameter = startParameter;
    }

    @Override
    public boolean isRunsTasks() {
        return true;
    }

    @Override
    public boolean isCreatesModel() {
        return false;
    }

    @Override
    public StartParameterInternal getStartParameter() {
        return startParameter;
    }

    @Override
    public DisplayName getActionDisplayName() {
        return Describables.of("calculating task graph");
    }

    @Override
    public DisplayName getConfigurationCacheKeyDisplayName() {
        return Describables.of("tasks:", Joiner.on(" ").join(startParameter.getTaskNames()));
    }

    @Override
    public void appendKeyTo(Hasher hasher) {
        // Identify the type of action
        hasher.putByte((byte) 1);
    }
}


text:
from datetime import datetime, timedelta
from bson import ObjectId
import re
import random
import string
import logging
from libs.sms_client import SmsClient

class SmsService(object):
  def __init__(self, db, access_key, private_key):
    self.log = logging.getLogger(__name__)
    self.db = db
    self.smsClient = SmsClient(access_key, private_key)
    self.sms_store = db.sms_collection
    self.otp_store = db.sms_otp_collection

  def send_otp(self, number, otp, message):
    self.log.info("Sending OTP SMS [%s] -> [%s](Count:%d)" % (number, message, len(message)))
    if self.check_otp(number, otp):
      self.log.warn("Trying to send duplicate OTP message %s" % (number))
      return 'SENT'
    aws_msg_id = self.smsClient.send(number, message)
    item = dict(number=number, message=message, char_count=len(message), created_at=datetime.now(),
                status='SENT', otp=otp, details="", aws_msg_id=aws_msg_id)
    _id = self.otp_store.save(item)
    return 'SENT'

  def generate_otp(self):
    unique = False
    count = 1
    otp = ""
    while not unique or count > 10:
      digits_f = "".join([random.choice(string.digits) for i in range(3)])
      digits_l = "".join([random.choice(string.digits) for i in range(3)])
      otp = digits_f + '' + digits_l
      unique = self.otp_store.find({'otp': otp}).count() == 0
      count =  count + 1
    if count > 10:
      raise Exception("Unable to generate OTP after 10 iteration!!")
    self.log.info("GENERATED OTP %s" % (otp))
    return otp

  def update_otp(self, number, otp):
    n = datetime.now() - timedelta(minutes=4)
    query = self.otp_store.find({'number':number,'created_at': {"$gt":n}}).sort('created_at', -1)
    if query.count() == 0: return False
    item = query[0]
    if item['otp'] != otp: return False
    item['status'] = 'VERIFIED'
    item['verified_at'] = datetime.now()
    self.otp_store.save(item)
    return True

  def verified_number(self, number):
    return self.otp_store.find({'number': number, 'status': 'VERIFIED'}).count() > 0

  def check_otp(self, number, otp):
    query = self.otp_store.find({'number': number, 'otp': otp})
    if query.count() == 1:
      return False
    n = datetime.now() - timedelta(minutes=2)
    query = self.otp_store.find({'number': number, 'created_at': {"$gt":n}})
    return query.count() != 0

  def send(self, number, message, sms_type='CONFIRMED'):
    self.log.info("Sending SMS [%s] -> [%s](Count:%d)" % (number, message, len(message)))
    if self.has_duplicate_message(number, message):
      self.log.warn("Trying to send duplicate message %s" % (number))
      return 'SENT'
    aws_msg_id = self.smsClient.send(number, message)
    item = dict(number=number, message=message, char_count=len(message), created_at=datetime.now(),
      status='I', details="", aws_msg_id=aws_msg_id, type=sms_type)
    _id = self.sms_store.save(item)
    return 'SENT'

  def has_duplicate_message(self,number, message):
    query = self.sms_store.find({'number':number,'message':message})
    return query.count() > 1

  def get_order_count(self, number, email, minutes=15):
    n = datetime.now() - timedelta(minutes=minutes)
    query = { '$or': [{'email': email}, {'number': number}], 'created_at': { '$gt': n } }
    items = self.sms_store.find(query)
    return items.count()

  def search(self, tenant_id, page_no=1,page_size=50,is_otp=False):
    query = self.sms_store
    if is_otp: query = self.otp_store
    offset = (page_no - 1) * page_size
    if offset < 0: offset = 0
    lst = query.find().skip(offset).limit(page_size).sort("created_at", -1)
    return [x for x in lst], query.count()

  def delete(self, tenant_id, _id, is_otp=False):
    if is_otp:
      return self.otp_store.remove({"_id":ObjectId(_id)})
    return self.sms_store.remove({"_id":ObjectId(_id)})


text:
package com.quiptiq.wurmrest.rmi;

import javax.annotation.concurrent.ThreadSafe;
import java.util.Map;

import com.quiptiq.wurmrest.Result;
import com.quiptiq.wurmrest.api.Balance;
import com.wurmonline.server.webinterface.WebInterface;

/**
 * Provides access to the wurm service, encapsulating the calls to the game servers.
 */
@ThreadSafe
public class RmiGameService {
    /**
     * Calls the web interface, wrapping each call in checks for null and attempts to get a
     * "refreshed" version from the provider if a call fails.
     */
    private final Invoker webInterfaceInvoker = new Invoker();

    /**
     * For a map returned by a web interface, the existence of this key should indicate that an
     * error occurred and the value at this key contains the message.
     */
    protected static final String ERROR_KEY = "error";

    /**
     * For a map returned by a web interface, the existence of this key should indicate that the
     * method executed successfully and the value at this key contains the message.
     */
    protected static final String SUCCESS_KEY = "ok";

    /**
     * Provides thread-safe access to the web interface stub
     */
    private final RmiProvider rmiProvider;

    /**
     * Password to the web interface.
     */
    private final String password;

    /**
     * None of the expected values from a web interface call were returned.
     */
    protected static final String ERROR_NO_EXPECTED_VALUES = "No expected values were returned";

    /**
     * Constructs the RmiGameService using rmiProvider to provide a WebInterface. The WebInterface
     * is retrieved immediately so that a malformed URL may be discovered on the start of the
     * service.
     *
     * @param rmiProvider Provides the WebInterface for RMI invocation
     */
    public RmiGameService(RmiProvider rmiProvider) {
        this.rmiProvider = rmiProvider;
        this.password = rmiProvider.getPassword();
        rmiProvider.getOrRefreshWebInterface();
    }

    /**
     * @return Password for the RMI service.
     */
    protected String getPassword() {
        return password;
    }

    /**
     * Convenience method for invoking a method on the web interface.
     * @param methodName Name of the method, for logging
     * @param invocation Invocation to execute
     * @param <R> Result return type
     * @return Result wrapping the given return type.
     */
    protected <R> Result<R> invoke(String methodName, Invoker.Invocation<R> invocation) {
        return webInterfaceInvoker.invoke(rmiProvider, methodName, invocation);
    }

    /**
     * Whether or not the service is currently running.
     * @return Success result with true if the game is running, false if it is not and an
     * error result if the service could not be contacted.
     */
    public Result<Boolean> isRunning() {
        return invoke("isRunning",
                (WebInterface webinterface) -> Result.success(webinterface.isRunning(password)));
    }
}


text:
using System;

namespace LinqToDB.SchemaProvider
{
	public class ForeingKeyInfo
	{
		public string Name;
		public string ThisTableID;
		public string ThisColumn;
		public string OtherTableID;
		public string OtherColumn;
		public int    Ordinal;
	}
}


text:
<?php

namespace Matryoshka\Model\Object\ActiveRecord;

use Matryoshka\Model\Object\IdentityAwareInterface;

/**
 * Interface ActiveRecordInterface
 */
interface ActiveRecordInterface extends IdentityAwareInterface
{
    /**
     * Save
     */
    public function save();

    /**
     * Delete
     */
    public function delete();
}


text: Crystallographic calculations provided as a library (intended for use in DAWN)


text:
%% This style is provided for the ICSE 2015 main conference,
%% ICSE 2015 co-located events, and ICSE 2015 workshops.

%% bare_conf_ICSE15.tex
%% V1.4
%% 2014/05/22

%% This is a skeleton file demonstrating the use of IEEEtran.cls
%% (requires IEEEtran.cls version 1.7 or later) with an IEEE conference paper.
%%
%% Support sites:
%% http://www.michaelshell.org/tex/ieeetran/
%% http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/
%% and
%% http://www.ieee.org/

%%*************************************************************************
%% Legal Notice:
%% This code is offered as-is without any warranty either expressed or
%% implied; without even the implied warranty of MERCHANTABILITY or
%% FITNESS FOR A PARTICULAR PURPOSE!
%% User assumes all risk.
%% In no event shall IEEE or any contributor to this code be liable for
%% any damages or losses, including, but not limited to, incidental,
%% consequential, or any other damages, resulting from the use or misuse
%% of any information contained here.
%%
%% All comments are the opinions of their respective authors and are not
%% necessarily endorsed by the IEEE.
%%
%% This work is distributed under the LaTeX Project Public License (LPPL)
%% ( http://www.latex-project.org/ ) version 1.3, and may be freely used,
%% distributed and modified. A copy of the LPPL, version 1.3, is included
%% in the base LaTeX documentation of all distributions of LaTeX released
%% 2003/12/01 or later.
%% Retain all contribution notices and credits.
%% ** Modified files should be clearly indicated as such, including  **
%% ** renaming them and changing author support contact information. **
%%
%% File list of work: IEEEtran.cls, IEEEtran_HOWTO.pdf, bare_adv.tex,
%%                    bare_conf.tex, bare_jrnl.tex, bare_jrnl_compsoc.tex
%%*************************************************************************

% *** Authors should verify (and, if needed, correct) their LaTeX system  ***
% *** with the testflow diagnostic prior to trusting their LaTeX platform ***
% *** with production work. IEEE's font choices can trigger bugs that do  ***
% *** not appear when using other class files.                            ***
% The testflow support page is at:
% http://www.michaelshell.org/tex/testflow/

% Note that the a4paper option is mainly intended so that authors in
% countries using A4 can easily print to A4 and see how their papers will
% look in print - the typesetting of the document will not typically be
% affected with changes in paper size (but the bottom and side margins will).
% Use the testflow package mentioned above to verify correct handling of
% both paper sizes by the user's LaTeX system.
%
% Also note that the "draftcls" or "draftclsnofoot", not "draft", option
% should be used if it is desired that the figures are to be displayed in
% draft mode.
%
\documentclass[conference]{IEEEtran}
%
% If IEEEtran.cls has not been installed into the LaTeX system files,
% manually specify the path to it like:
% \documentclass[conference]{../sty/IEEEtran}

% Some very useful LaTeX packages include:
% (uncomment the ones you want to load)

% *** MISC UTILITY PACKAGES ***
%
%\usepackage{ifpdf}
% Heiko Oberdiek's ifpdf.sty is very useful if you need conditional
% compilation based on whether the output is pdf or dvi.
% usage:
% \ifpdf
%   % pdf code
% \else
%   % dvi code
% \fi
% The latest version of ifpdf.sty can be obtained from:
% http://www.ctan.org/tex-archive/macros/latex/contrib/oberdiek/
% Also, note that IEEEtran.cls V1.7 and later provides a builtin
% \ifCLASSINFOpdf conditional that works the same way.
% When switching from latex to pdflatex and vice-versa, the compiler may
% have to be run twice to clear warning/error messages.

% *** CITATION PACKAGES ***
%
%\usepackage{cite}
% cite.sty was written by Donald Arseneau
% V1.6 and later of IEEEtran pre-defines the format of the cite.sty package
% \cite{} output to follow that of IEEE. Loading the cite package will
% result in citation numbers being automatically sorted and properly
% "compressed/ranged". e.g., [1], [9], [2], [7], [5], [6] without using
% cite.sty will become [1], [2], [5]--[7], [9] using cite.sty. cite.sty's
% \cite will automatically add leading space, if needed. Use cite.sty's
% noadjust option (cite.sty V3.8 and later) if you want to turn this off.
% cite.sty is already installed on most LaTeX systems. Be sure and use
% version 4.0 (2003-05-27) and later if using hyperref.sty. cite.sty does
% not currently provide for hyperlinked citations.
% The latest version can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/cite/
% The documentation is contained in the cite.sty file itself.

% *** GRAPHICS RELATED PACKAGES ***
%
\ifCLASSINFOpdf
  % \usepackage[pdftex]{graphicx}
  % declare the path(s) where your graphic files are
  % \graphicspath{{../pdf/}{../jpeg/}}
  % and their extensions so you won't have to specify these with
  % every instance of \includegraphics
  % \DeclareGraphicsExtensions{.pdf,.jpeg,.png}
\else
  % or other class option (dvipsone, dvipdf, if not using dvips). graphicx
  % will default to the driver specified in the system graphics.cfg if no
  % driver is specified.
  % \usepackage[dvips]{graphicx}
  % declare the path(s) where your graphic files are
  % \graphicspath{{../eps/}}
  % and their extensions so you won't have to specify these with
  % every instance of \includegraphics
  % \DeclareGraphicsExtensions{.eps}
\fi
% graphicx was written by David Carlisle and Sebastian Rahtz. It is
% required if you want graphics, photos, etc. graphicx.sty is already
% installed on most LaTeX systems. The latest version and documentation can
% be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/required/graphics/
% Another good source of documentation is "Using Imported Graphics in
% LaTeX2e" by Keith Reckdahl which can be found as epslatex.ps or
% epslatex.pdf at: http://www.ctan.org/tex-archive/info/
%
% latex, and pdflatex in dvi mode, support graphics in encapsulated
% postscript (.eps) format. pdflatex in pdf mode supports graphics
% in .pdf, .jpeg, .png and .mps (metapost) formats. Users should ensure
% that all non-photo figures use a vector format (.eps, .pdf, .mps) and
% not a bitmapped formats (.jpeg, .png). IEEE frowns on bitmapped formats
% which can result in "jaggedy"/blurry rendering of lines and letters as
% well as large increases in file sizes.
%
% You can find documentation about the pdfTeX application at:
% http://www.tug.org/applications/pdftex

% *** MATH PACKAGES ***
%
%\usepackage[cmex10]{amsmath}
% A popular package from the American Mathematical Society that provides
% many useful and powerful commands for dealing with mathematics. If using
% it, be sure to load this package with the cmex10 option to ensure that
% only type 1 fonts will utilized at all point sizes. Without this option,
% it is possible that some math symbols, particularly those within
% footnotes, will be rendered in bitmap form which will result in a
% document that can not be IEEE Xplore compliant!
%
% Also, note that the amsmath package sets \interdisplaylinepenalty to 10000
% thus preventing page breaks from occurring within multiline equations. Use:
%\interdisplaylinepenalty=2500
% after loading amsmath to restore such page breaks as IEEEtran.cls normally
% does. amsmath.sty is already installed on most LaTeX systems. The latest
% version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/required/amslatex/math/

% *** SPECIALIZED LIST PACKAGES ***
%
%\usepackage{algorithmic}
% algorithmic.sty was written by Peter Williams and Rogerio Brito.
% This package provides an algorithmic environment fo describing algorithms.
% You can use the algorithmic environment in-text or within a figure
% environment to provide for a floating algorithm. Do NOT use the algorithm
% floating environment provided by algorithm.sty (by the same authors) or
% algorithm2e.sty (by Christophe Fiorio) as IEEE does not use dedicated
% algorithm float types and packages that provide these will not provide
% correct IEEE style captions. The latest version and documentation of
% algorithmic.sty can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/algorithms/
% There is also a support site at:
% http://algorithms.berlios.de/index.html
% Also of interest may be the (relatively newer and more customizable)
% algorithmicx.sty package by Szasz Janos:
% http://www.ctan.org/tex-archive/macros/latex/contrib/algorithmicx/

% *** ALIGNMENT PACKAGES ***
%
%\usepackage{array}
% Frank Mittelbach's and David Carlisle's array.sty patches and improves
% the standard LaTeX2e array and tabular environments to provide better
% appearance and additional user controls. As the default LaTeX2e table
% generation code is lacking to the point of almost being broken with
% respect to the quality of the end results, all users are strongly
% advised to use an enhanced (at the very least that provided by array.sty)
% set of table tools. array.sty is already installed on most systems. The
% latest version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/required/tools/

%\usepackage{mdwmath}
%\usepackage{mdwtab}
% Also highly recommended is Mark Wooding's extremely powerful MDW tools,
% especially mdwmath.sty and mdwtab.sty which are used to format equations
% and tables, respectively. The MDWtools set is already installed on most
% LaTeX systems. The lastest version and documentation is available at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/mdwtools/

% IEEEtran contains the IEEEeqnarray family of commands that can be used to
% generate multiline equations as well as matrices, tables, etc., of high
% quality.

%\usepackage{eqparbox}
% Also of notable interest is Scott Pakin's eqparbox package for creating
% (automatically sized) equal width boxes - aka "natural width parboxes".
% Available at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/eqparbox/

% *** SUBFIGURE PACKAGES ***
%\usepackage[tight,footnotesize]{subfigure}
% subfigure.sty was written by Steven Douglas Cochran. This package makes it
% easy to put subfigures in your figures. e.g., "Figure 1a and 1b". For IEEE
% work, it is a good idea to load it with the tight package option to reduce
% the amount of white space around the subfigures. subfigure.sty is already
% installed on most LaTeX systems. The latest version and documentation can
% be obtained at:
% http://www.ctan.org/tex-archive/obsolete/macros/latex/contrib/subfigure/
% subfigure.sty has been superceeded by subfig.sty.

%\usepackage[caption=false]{caption}
%\usepackage[font=footnotesize]{subfig}
% subfig.sty, also written by Steven Douglas Cochran, is the modern
% replacement for subfigure.sty. However, subfig.sty requires and
% automatically loads Axel Sommerfeldt's caption.sty which will override
% IEEEtran.cls handling of captions and this will result in nonIEEE style
% figure/table captions. To prevent this problem, be sure and preload
% caption.sty with its "caption=false" package option. This is will preserve
% IEEEtran.cls handing of captions. Version 1.3 (2005/06/28) and later
% (recommended due to many improvements over 1.2) of subfig.sty supports
% the caption=false option directly:
%\usepackage[caption=false,font=footnotesize]{subfig}
%
% The latest version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/subfig/
% The latest version and documentation of caption.sty can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/caption/

% *** FLOAT PACKAGES ***
%
%\usepackage{fixltx2e}
% fixltx2e, the successor to the earlier fix2col.sty, was written by
% Frank Mittelbach and David Carlisle. This package corrects a few problems
% in the LaTeX2e kernel, the most notable of which is that in current
% LaTeX2e releases, the ordering of single and double column floats is not
% guaranteed to be preserved. Thus, an unpatched LaTeX2e can allow a
% single column figure to be placed prior to an earlier double column
% figure. The latest version and documentation can be found at:
% http://www.ctan.org/tex-archive/macros/latex/base/

%\usepackage{stfloats}
% stfloats.sty was written by Sigitas Tolusis. This package gives LaTeX2e
% the ability to do double column floats at the bottom of the page as well
% as the top. (e.g., "\begin{figure*}[!b]" is not normally possible in
% LaTeX2e). It also provides a command:
%\fnbelowfloat
% to enable the placement of footnotes below bottom floats (the standard
% LaTeX2e kernel puts them above bottom floats). This is an invasive package
% which rewrites many portions of the LaTeX2e float routines. It may not work
% with other packages that modify the LaTeX2e float routines. The latest
% version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/sttools/
% Documentation is contained in the stfloats.sty comments as well as in the
% presfull.pdf file. Do not use the stfloats baselinefloat ability as IEEE
% does not allow \baselineskip to stretch. Authors submitting work to the
% IEEE should note that IEEE rarely uses double column equations and
% that authors should try to avoid such use. Do not be tempted to use the
% cuted.sty or midfloat.sty packages (also by Sigitas Tolusis) as IEEE does
% not format its papers in such ways.

% *** PDF, URL AND HYPERLINK PACKAGES ***
%
%\usepackage{url}
% url.sty was written by Donald Arseneau. It provides better support for
% handling and breaking URLs. url.sty is already installed on most LaTeX
% systems. The latest version can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/misc/
% Read the url.sty source comments for usage information. Basically,
% \url{my_url_here}.

% *** Do not adjust lengths that control margins, column widths, etc. ***
% *** Do not use packages that alter fonts (such as pslatex).         ***
% There should be no need to do such things with IEEEtran.cls V1.6 and later.
% (Unless specifically asked to do so by the journal or conference you plan
% to submit to, of course. )

% correct bad hyphenation here
\hyphenation{op-tical net-works semi-conduc-tor}

\begin{document}
%
% paper title
% can use linebreaks \\ within to get better formatting as desired
\title{Bare Demo of IEEEtran.cls for ICSE'15 and Workshops}

% author names and affiliations
% use a multiple column layout for up to three different
% affiliations
%\author{\IEEEauthorblockN{Michael Shell}
%\IEEEauthorblockA{School of Electrical and\\Computer Engineering\\
%Georgia Institute of Technology\\
%Atlanta, Georgia 30332--0250\\
%Email: http://www.michaelshell.org/contact.html}
%\and
%\IEEEauthorblockN{Homer Simpson}
%\IEEEauthorblockA{Twentieth Century Fox\\
%Springfield, USA\\
%Email: homer@thesimpsons.com}
%\and
%\IEEEauthorblockN{James Kirk\\ and Montgomery Scott}
%\IEEEauthorblockA{Starfleet Academy\\
%San Francisco, California 96678-2391\\
%Telephone: (800) 555--1212\\
%Fax: (888) 555--1212}}

% conference papers do not typically use \thanks and this command
% is locked out in conference mode. If really needed, such as for
% the acknowledgment of grants, issue a \IEEEoverridecommandlockouts
% after \documentclass

% for over three affiliations, or if they all won't fit within the width
% of the page, use this alternative format:
%
\author{\IEEEauthorblockN{Michael Shell\IEEEauthorrefmark{1},
Homer Simpson\IEEEauthorrefmark{2},
James Kirk\IEEEauthorrefmark{3},
Montgomery Scott\IEEEauthorrefmark{3} and
Eldon Tyrell\IEEEauthorrefmark{4}}
\IEEEauthorblockA{\IEEEauthorrefmark{1}School of Electrical and Computer Engineering\\
Georgia Institute of Technology,
Atlanta, Georgia 30332--0250\\ Email: see http://www.michaelshell.org/contact.html}
\IEEEauthorblockA{\IEEEauthorrefmark{2}Twentieth Century Fox, Springfield, USA\\
Email: homer@thesimpsons.com}
\IEEEauthorblockA{\IEEEauthorrefmark{3}Starfleet Academy, San Francisco, California 96678-2391\\
Telephone: (800) 555--1212, Fax: (888) 555--1212}
\IEEEauthorblockA{\IEEEauthorrefmark{4}Tyrell Inc., 123 Replicant Street, Los Angeles, California 90210--4321}}

% use for special paper notices
%\IEEEspecialpapernotice{(Invited Paper)}

% make the title area
\maketitle

\begin{abstract}
%\boldmath
The abstract goes here.
\end{abstract}
% IEEEtran.cls defaults to using nonbold math in the Abstract.
% This preserves the distinction between vectors and scalars. However,
% if the conference you are submitting to favors bold math in the abstract,
% then you can use LaTeX's standard command \boldmath at the very start
% of the abstract to achieve this. Many IEEE journals/conferences frown on
% math in the abstract anyway.

% no keywords

% For peer review papers, you can put extra information on the cover
% page as needed:
% \ifCLASSOPTIONpeerreview
% \begin{center} \bfseries EDICS Category: 3-BBND \end{center}
% \fi
%
% For peerreview papers, this IEEEtran command inserts a page break and
% creates the second title. It will be ignored for other modes.
\IEEEpeerreviewmaketitle

\section{Introduction}
% no \IEEEPARstart
This demo file is intended to serve as a ``starter file''
for IEEE conference papers produced under \LaTeX\ using
IEEEtran.cls version 1.7 and later.
% You must have at least 2 lines in the paragraph with the drop letter
% (should never be an issue)
I wish you the best of success.

\hfill mds

\hfill January 11, 2007

\subsection{Subsection Heading Here}
Subsection text here.

\subsubsection{Subsubsection Heading Here}
Subsubsection text here.

% An example of a floating figure using the graphicx package.
% Note that \label must occur AFTER (or within) \caption.
% For figures, \caption should occur after the \includegraphics.
% Note that IEEEtran v1.7 and later has special internal code that
% is designed to preserve the operation of \label within \caption
% even when the captionsoff option is in effect. However, because
% of issues like this, it may be the safest practice to put all your
% \label just after \caption rather than within \caption{}.
%
% Reminder: the "draftcls" or "draftclsnofoot", not "draft", class
% option should be used if it is desired that the figures are to be
% displayed while in draft mode.
%
%\begin{figure}[!t]
%\centering
%\includegraphics[width=2.5in]{myfigure}
% where an .eps filename suffix will be assumed under latex,
% and a .pdf suffix will be assumed for pdflatex; or what has been declared
% via \DeclareGraphicsExtensions.
%\caption{Simulation Results}
%\label{fig_sim}
%\end{figure}

% Note that IEEE typically puts floats only at the top, even when this
% results in a large percentage of a column being occupied by floats.

% An example of a double column floating figure using two subfigures.
% (The subfig.sty package must be loaded for this to work.)
% The subfigure \label commands are set within each subfloat command, the
% \label for the overall figure must come after \caption.
% \hfil must be used as a separator to get equal spacing.
% The subfigure.sty package works much the same way, except \subfigure is
% used instead of \subfloat.
%
%\begin{figure*}[!t]
%\centerline{\subfloat[Case I]\includegraphics[width=2.5in]{subfigcase1}%
%\label{fig_first_case}}
%\hfil
%\subfloat[Case II]{\includegraphics[width=2.5in]{subfigcase2}%
%\label{fig_second_case}}}
%\caption{Simulation results}
%\label{fig_sim}
%\end{figure*}
%
% Note that often IEEE papers with subfigures do not employ subfigure
% captions (using the optional argument to \subfloat), but instead will
% reference/describe all of them (a), (b), etc., within the main caption.

% An example of a floating table. Note that, for IEEE style tables, the
% \caption command should come BEFORE the table. Table text will default to
% \footnotesize as IEEE normally uses this smaller font for tables.
% The \label must come after \caption as always.
%
%\begin{table}[!t]
%% increase table row spacing, adjust to taste
%\renewcommand{\arraystretch}{1.3}
% if using array.sty, it might be a good idea to tweak the value of
% \extrarowheight as needed to properly center the text within the cells
%\caption{An Example of a Table}
%\label{table_example}
%\centering
%% Some packages, such as MDW tools, offer better commands for making tables
%% than the plain LaTeX2e tabular which is used here.
%\begin{tabular}{|c||c|}
%\hline
%One & Two\\
%\hline
%Three & Four\\
%\hline
%\end{tabular}
%\end{table}

% Note that IEEE does not put floats in the very first column - or typically
% anywhere on the first page for that matter. Also, in-text middle ("here")
% positioning is not used. Most IEEE journals/conferences use top floats
% exclusively. Note that, LaTeX2e, unlike IEEE journals/conferences, places
% footnotes above bottom floats. This can be corrected via the \fnbelowfloat
% command of the stfloats package.

\section{Conclusion}
The conclusion goes here.

% conference papers do not normally have an appendix

% use section* for acknowledgement
\section*{Acknowledgment}

The authors would like to thank...

% trigger a \newpage just before the given reference
% number - used to balance the columns on the last page
% adjust value as needed - may need to be readjusted if
% the document is modified later
%\IEEEtriggeratref{8}
% The "triggered" command can be changed if desired:
%\IEEEtriggercmd{\enlargethispage{-5in}}

% references section

% can use a bibliography generated by BibTeX as a .bbl file
% BibTeX documentation can be easily obtained at:
% http://www.ctan.org/tex-archive/biblio/bibtex/contrib/doc/
% The IEEEtran BibTeX style support page is at:
% http://www.michaelshell.org/tex/ieeetran/bibtex/
%\bibliographystyle{IEEEtran}
% argument is your BibTeX string definitions and bibliography database(s)
%\bibliography{IEEEabrv,../bib/paper}
%
% <OR> manually copy in the resultant .bbl file
% set second argument of \begin to the number of references
% (used to reserve space for the reference number labels box)
\begin{thebibliography}{1}

\bibitem{IEEEhowto:kopka}
H.~Kopka and P.~W. Daly, \emph{A Guide to \LaTeX}, 3rd~ed.\hskip 1em plus
  0.5em minus 0.4em\relax Harlow, England: Addison-Wesley, 1999.

\end{thebibliography}

% that's all folks
\end{document}


text:
class AddAccessTokenToUsers < ActiveRecord::Migration
  def change
    add_column :users, :access_token, :string, null: true
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="myFirstSpringBook" class="com.djs.learn.mvc.dto.Book">
		<property name="isbn">
			<value>1</value>
		</property>
		<property name="author">
			<value>${myFirstSpringBook.author}</value>
		</property>
		<property name="title">
			<ref bean="bookTitle" />
		</property>
		<property name="chapters">
			<list>
				<ref bean="chapter1" />
				<ref bean="chapter2" />
				<ref bean="chapter3" />
			</list>
		</property>
	</bean>

</beans>


text:
require "json"

module RailsI18n
  module Spec
    module RubyContent
      def content
        @content ||= eval(IO.read(@filepath), TOPLEVEL_BINDING)
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Comments for page "Tiny Bee Rifle"</title>
		<link>http://bvs.wikidot.com/forum/t-222707/tiny-bee-rifle</link>
		<description>Posts in the discussion thread "Tiny Bee Rifle"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 03:47:45 +0000</lastBuildDate>

				</channel>
</rss>