text:
#include "compress_segmentation.h"

#include <algorithm>
#include <unordered_map>

namespace neuroglancer {
namespace compress_segmentation {

constexpr size_t kBlockHeaderSize = 2;

void WriteBlockHeader(size_t encoded_value_base_offset,
                      size_t table_base_offset, size_t encoding_bits,
                      uint32_t output[2]) {
  output[0] = table_base_offset | (encoding_bits << 24);
  output[1] = encoded_value_base_offset;
}

template <class Label>
void EncodeBlock(const Label* input, const ptrdiff_t input_strides[3],
                 const ptrdiff_t block_size[3], const ptrdiff_t actual_size[3],
                 size_t base_offset, size_t* encoded_bits_output,
                 size_t* table_offset_output, EncodedValueCache<Label>* cache,
                 std::vector<uint32_t>* output_vec) {
  if (actual_size[0] * actual_size[1] * actual_size[2] == 0) {
    *encoded_bits_output = 0;
    *table_offset_output = 0;
    return;
  }

  constexpr size_t num_32bit_words_per_label =
      (sizeof(Label) + sizeof(uint32_t) - 1) / sizeof(uint32_t);

  std::unordered_map<Label, uint32_t> seen_values;
  std::vector<Label> seen_values_inv;

  // First determine the distinct values.

  // Initialize previous_value such that it is guaranteed not to equal to the
  // first value.
  Label previous_value = input[0] + 1;
  {
    auto* input_z = input;
    for (size_t z = 0; z < actual_size[2]; ++z) {
      auto* input_y = input_z;
      for (size_t y = 0; y < actual_size[1]; ++y) {
        auto* input_x = input_y;
        for (size_t x = 0; x < actual_size[0]; ++x) {
          auto value = *input_x;
          // If this value matches the previous value, we can skip the more
          // expensive hash table lookup.
          if (value != previous_value) {
            previous_value = value;
            if (seen_values.emplace(value, 0).second) {
              seen_values_inv.push_back(value);
            }
          }

          input_x += input_strides[0];
        }
        input_y += input_strides[1];
      }
      input_z += input_strides[2];
    }
  }

  std::sort(seen_values_inv.begin(), seen_values_inv.end());
  for (size_t i = 0; i < seen_values_inv.size(); ++i) {
    seen_values[seen_values_inv[i]] = static_cast<uint32_t>(i);
  }

  // Determine number of bits with which to encode each index.
  size_t encoded_bits = 0;
  if (seen_values.size() != 1) {
    encoded_bits = 1;
    while ((1 << encoded_bits) < seen_values.size()) {
      encoded_bits *= 2;
    }
  }
  *encoded_bits_output = encoded_bits;
  const size_t encoded_size_32bits =
      (encoded_bits * block_size[0] * block_size[1] * block_size[2] + 31) / 32;

  const size_t encoded_value_base_offset = output_vec->size();
  size_t elements_to_write = encoded_size_32bits;

  bool write_table;
  {
    auto it = cache->find(seen_values_inv);
    if (it == cache->end()) {
      write_table = true;
      elements_to_write += seen_values.size() * num_32bit_words_per_label;
      *table_offset_output =
          encoded_value_base_offset + encoded_size_32bits - base_offset;
    } else {
      write_table = false;
      *table_offset_output = it->second;
    }
  }

  output_vec->resize(encoded_value_base_offset + elements_to_write);
  uint32_t* output = output_vec->data() + encoded_value_base_offset;
  // Write encoded representation.
  {
    auto* input_z = input;
    for (size_t z = 0; z < actual_size[2]; ++z) {
      auto* input_y = input_z;
      for (size_t y = 0; y < actual_size[1]; ++y) {
        auto* input_x = input_y;
        for (size_t x = 0; x < actual_size[0]; ++x) {
          auto value = *input_x;
          uint32_t index = seen_values.at(value);
          size_t output_offset = x + block_size[0] * (y + block_size[1] * z);
          output[output_offset * encoded_bits / 32] |=
              (index << (output_offset * encoded_bits % 32));

          input_x += input_strides[0];
        }
        input_y += input_strides[1];
      }
      input_z += input_strides[2];
    }
  }

  // Write table
  if (write_table) {
    output =
        output_vec->data() + encoded_value_base_offset + encoded_size_32bits;
    for (auto value : seen_values_inv) {
      for (int word_i = 0; word_i < num_32bit_words_per_label; ++word_i) {
        output[word_i] = static_cast<uint32_t>(value >> (32 * word_i));
      }
      output += num_32bit_words_per_label;
    }
    cache->emplace(seen_values_inv, *table_offset_output);
  }
}

template <class Label>
void CompressChannel(const Label* input, const ptrdiff_t input_strides[3],
                     const ptrdiff_t volume_size[3],
                     const ptrdiff_t block_size[3],
                     std::vector<uint32_t>* output) {
  EncodedValueCache<Label> cache;
  const size_t base_offset = output->size();
  ptrdiff_t grid_size[3];
  size_t block_index_size = kBlockHeaderSize;
  for (size_t i = 0; i < 3; ++i) {
    grid_size[i] = (volume_size[i] + block_size[i] - 1) / block_size[i];
    block_index_size *= grid_size[i];
  }
  output->resize(base_offset + block_index_size);
  ptrdiff_t block[3];
  for (block[2] = 0; block[2] < grid_size[2]; ++block[2]) {
    for (block[1] = 0; block[1] < grid_size[1]; ++block[1]) {
      for (block[0] = 0; block[0] < grid_size[0]; ++block[0]) {
        const size_t block_offset =
            block[0] + grid_size[0] * (block[1] + grid_size[1] * block[2]);
        ptrdiff_t actual_size[3];
        ptrdiff_t input_offset = 0;
        size_t num_values = 1;
        for (size_t i = 0; i < 3; ++i) {
          auto pos = block[i] * block_size[i];
          actual_size[i] = std::min(block_size[i], volume_size[i] - pos);
          input_offset += pos * input_strides[i];
          num_values *= actual_size[i];
        }
        const size_t encoded_value_base_offset = output->size() - base_offset;
        size_t encoded_bits, table_offset;
        EncodeBlock(input + input_offset, input_strides, block_size,
                    actual_size, base_offset, &encoded_bits, &table_offset,
                    &cache, output);
        WriteBlockHeader(
            encoded_value_base_offset, table_offset, encoded_bits,
            &(*output)[base_offset + block_offset * kBlockHeaderSize]);
      }
    }
  }
}

template <class Label>
void CompressChannels(const Label* input, const ptrdiff_t input_strides[4],
                      const ptrdiff_t volume_size[4],
                      const ptrdiff_t block_size[3],
                      std::vector<uint32_t>* output) {
  output->resize(volume_size[3]);
  for (size_t channel_i = 0; channel_i < volume_size[3]; ++channel_i) {
    (*output)[channel_i] = output->size();
    CompressChannel(input + input_strides[3] * channel_i, input_strides,
                    volume_size, block_size, output);
  }
}

#define DO_INSTANTIATE(Label)                                        \
  template void EncodeBlock<Label>(                                  \
      const Label* input, const ptrdiff_t input_strides[3],          \
      const ptrdiff_t block_size[3], const ptrdiff_t actual_size[3], \
      size_t base_offset, size_t* encoded_bits_output,               \
      size_t* table_offset_output, EncodedValueCache<Label>* cache,  \
      std::vector<uint32_t>* output_vec);                            \
  template void CompressChannel<Label>(                              \
      const Label* input, const ptrdiff_t input_strides[3],          \
      const ptrdiff_t volume_size[3], const ptrdiff_t block_size[3], \
      std::vector<uint32_t>* output);                                \
  template void CompressChannels<Label>(                             \
      const Label* input, const ptrdiff_t input_strides[4],          \
      const ptrdiff_t volume_size[4], const ptrdiff_t block_size[3], \
      std::vector<uint32_t>* output);                                \
/**/

DO_INSTANTIATE(uint32_t)
DO_INSTANTIATE(uint64_t)

#undef DO_INSTANTIATE

}  // namespace compress_segmentation
}  // namespace neuroglancer


text:
package org.smartpony.common.error

import java.io.{PrintWriter, StringWriter}

import org.slf4j.LoggerFactory

object FormattedExceptionLogger {

  val Logger = LoggerFactory.getLogger("formatted-exception-logger")

  def logException(location: ErrorCode, ex: Throwable, showStackTrace: Boolean, message: Option[String] = None): Unit = {
    val msg = message.fold("")(m => s" $m. ")
    Logger.error(s"Error occurred at ${location.identifier}: ${msg}${ex.getClass.getSimpleName} - ${ex.getMessage}")
    if (showStackTrace) logStackTrace(ex)
  }

  private def logStackTrace(ex: Throwable): Unit = {
    Logger.error(s"This is the stack trace\n\n" + stackTraceFor(ex) + "\n\nEnd Stack trace")
  }

  private def stackTraceFor(t: Throwable): String = {
    val sw = new StringWriter
    val pw = new PrintWriter(sw)
    t.printStackTrace(pw)
    pw.close()
    sw.toString
  }

}

redpajama_set_name: RedPajamaGithub


text:
#region Usings

using System;
using System.Threading.Tasks;

#endregion

namespace RabbitLink.Topology
{
    /// <summary>
    /// Topology configuration handler
    /// </summary>
    public interface ILinkTopologyHandler
    {
        /// <summary>
        /// Configure handler
        /// </summary>
        Task Configure(ILinkTopologyConfig config);

        /// <summary>
        /// Ready handler
        /// </summary>
        Task Ready();

        /// <summary>
        /// Error handler
        /// </summary>
        Task ConfigurationError(Exception ex);
    }
}


text:
package core.webui.server.handlers.internals.globalconfigs;

import java.io.IOException;
import java.util.List;

import org.apache.http.nio.protocol.HttpAsyncExchange;

import core.webui.server.handlers.renderedobjects.ObjectRenderer;

public class SetCoreConfigClientsHandler extends AbstractSetRemoteRepeatsClientsHandler {

	public SetCoreConfigClientsHandler(ObjectRenderer objectRenderer) {
		super(objectRenderer);
	}

	@Override
	public void setConfig(List<String> clientIds) {
		backEndHolder.setCoreClients(clientIds);
	}

	@Override
	public Void renderResponse(HttpAsyncExchange exchange) throws IOException {
		return renderedCoreClientsConfig(exchange);
	}
}


text:
import PushNotifications = require('node-pushnotifications');
import { supportedContentEncodings } from 'web-push';

const settings = {
    gcm: {
        id: "null"
    },
    apn: {
        token: {
            key: './certs/key.p8',
            keyId: 'ABCD',
            teamId: 'EFGH',
        }
    },
    adm: {
        client_id: "null",
        client_secret: "null"
    },
    wns: {
        client_id: "null",
        client_secret: "null",
        notificationMethod: 'sendTileSquareBlock',
    },
    web: {
        vapidDetails: {
            subject: '< \'mailto\' Address or URL >',
            publicKey: '< URL Safe Base64 Encoded Public Key >',
            privateKey: '< URL Safe Base64 Encoded Private Key >',
        },
        gcmAPIKey: 'gcmkey',
        TTL: 2419200,
        contentEncoding: supportedContentEncodings.AES_128_GCM,
        headers: {},
    }
};
const push = new PushNotifications(settings);

const registrationIds = [];
registrationIds.push('INSERT_YOUR_DEVICE_ID');
registrationIds.push('INSERT_OTHER_DEVICE_ID');
registrationIds.push({
    endpoint: 'https://fcm.googleapis.com/fcm/send/...',
    keys: {
        auth: '...',
        p256dh: '...'
    }
});

const data = {
    title: 'New push notification',
    body: 'Powered by AppFeel'
};

// You can use it in node callback style
push.send(registrationIds, data, (err, result) => {
    if (err) {
        console.log(err);
    } else {
        console.log(result);
    }
});

// Or you could use it as a promise and send only a single notifications:
push.send(registrationIds[0], data)
    .then((results) => {
        results.forEach((result) => {
            console.log(result.success);
            console.log(result.failure);
        });
        console.log(results);
    })
    .catch((err) => {
        console.log(err);
    });


text:
#pragma once
#include <aws/managedblockchain/ManagedBlockchain_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/managedblockchain/model/NodeStatus.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace ManagedBlockchain
{
namespace Model
{

  /**
   *
A summary of configuration properties for a node.

See Also:

   * AWS
   * API Reference

   */
  class AWS_MANAGEDBLOCKCHAIN_API NodeSummary
  {
  public:
    NodeSummary();
    NodeSummary(Aws::Utils::Json::JsonView jsonValue);
    NodeSummary& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The unique identifier of the node.

     */
    inline const Aws::String& GetId() const{ return m_id; }

    /**
     *
The unique identifier of the node.

     */
    inline bool IdHasBeenSet() const { return m_idHasBeenSet; }

    /**
     *
The unique identifier of the node.

     */
    inline void SetId(const Aws::String& value) { m_idHasBeenSet = true; m_id = value; }

    /**
     *
The unique identifier of the node.

     */
    inline void SetId(Aws::String&& value) { m_idHasBeenSet = true; m_id = std::move(value); }

    /**
     *
The unique identifier of the node.

     */
    inline void SetId(const char* value) { m_idHasBeenSet = true; m_id.assign(value); }

    /**
     *
The unique identifier of the node.

     */
    inline NodeSummary& WithId(const Aws::String& value) { SetId(value); return *this;}

    /**
     *
The unique identifier of the node.

     */
    inline NodeSummary& WithId(Aws::String&& value) { SetId(std::move(value)); return *this;}

    /**
     *
The unique identifier of the node.

     */
    inline NodeSummary& WithId(const char* value) { SetId(value); return *this;}

    /**
     *
The status of the node.

     */
    inline const NodeStatus& GetStatus() const{ return m_status; }

    /**
     *
The status of the node.

     */
    inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }

    /**
     *
The status of the node.

     */
    inline void SetStatus(const NodeStatus& value) { m_statusHasBeenSet = true; m_status = value; }

    /**
     *
The status of the node.

     */
    inline void SetStatus(NodeStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }

    /**
     *
The status of the node.

     */
    inline NodeSummary& WithStatus(const NodeStatus& value) { SetStatus(value); return *this;}

    /**
     *
The status of the node.

     */
    inline NodeSummary& WithStatus(NodeStatus&& value) { SetStatus(std::move(value)); return *this;}

    /**
     *
The date and time that the node was created.

     */
    inline const Aws::Utils::DateTime& GetCreationDate() const{ return m_creationDate; }

    /**
     *
The date and time that the node was created.

     */
    inline bool CreationDateHasBeenSet() const { return m_creationDateHasBeenSet; }

    /**
     *
The date and time that the node was created.

     */
    inline void SetCreationDate(const Aws::Utils::DateTime& value) { m_creationDateHasBeenSet = true; m_creationDate = value; }

    /**
     *
The date and time that the node was created.

     */
    inline void SetCreationDate(Aws::Utils::DateTime&& value) { m_creationDateHasBeenSet = true; m_creationDate = std::move(value); }

    /**
     *
The date and time that the node was created.

     */
    inline NodeSummary& WithCreationDate(const Aws::Utils::DateTime& value) { SetCreationDate(value); return *this;}

    /**
     *
The date and time that the node was created.

     */
    inline NodeSummary& WithCreationDate(Aws::Utils::DateTime&& value) { SetCreationDate(std::move(value)); return *this;}

    /**
     *
The Availability Zone in which the node exists.

     */
    inline const Aws::String& GetAvailabilityZone() const{ return m_availabilityZone; }

    /**
     *
The Availability Zone in which the node exists.

     */
    inline bool AvailabilityZoneHasBeenSet() const { return m_availabilityZoneHasBeenSet; }

    /**
     *
The Availability Zone in which the node exists.

     */
    inline void SetAvailabilityZone(const Aws::String& value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone = value; }

    /**
     *
The Availability Zone in which the node exists.

     */
    inline void SetAvailabilityZone(Aws::String&& value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone = std::move(value); }

    /**
     *
The Availability Zone in which the node exists.

     */
    inline void SetAvailabilityZone(const char* value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone.assign(value); }

    /**
     *
The Availability Zone in which the node exists.

     */
    inline NodeSummary& WithAvailabilityZone(const Aws::String& value) { SetAvailabilityZone(value); return *this;}

    /**
     *
The Availability Zone in which the node exists.

     */
    inline NodeSummary& WithAvailabilityZone(Aws::String&& value) { SetAvailabilityZone(std::move(value)); return *this;}

    /**
     *
The Availability Zone in which the node exists.

     */
    inline NodeSummary& WithAvailabilityZone(const char* value) { SetAvailabilityZone(value); return *this;}

    /**
     *
The EC2 instance type for the node.

     */
    inline const Aws::String& GetInstanceType() const{ return m_instanceType; }

    /**
     *
The EC2 instance type for the node.

     */
    inline bool InstanceTypeHasBeenSet() const { return m_instanceTypeHasBeenSet; }

    /**
     *
The EC2 instance type for the node.

     */
    inline void SetInstanceType(const Aws::String& value) { m_instanceTypeHasBeenSet = true; m_instanceType = value; }

    /**
     *
The EC2 instance type for the node.

     */
    inline void SetInstanceType(Aws::String&& value) { m_instanceTypeHasBeenSet = true; m_instanceType = std::move(value); }

    /**
     *
The EC2 instance type for the node.

     */
    inline void SetInstanceType(const char* value) { m_instanceTypeHasBeenSet = true; m_instanceType.assign(value); }

    /**
     *
The EC2 instance type for the node.

     */
    inline NodeSummary& WithInstanceType(const Aws::String& value) { SetInstanceType(value); return *this;}

    /**
     *
The EC2 instance type for the node.

     */
    inline NodeSummary& WithInstanceType(Aws::String&& value) { SetInstanceType(std::move(value)); return *this;}

    /**
     *
The EC2 instance type for the node.

     */
    inline NodeSummary& WithInstanceType(const char* value) { SetInstanceType(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the node. For more information about ARNs
     * and their format, see Amazon
     * Resource Names (ARNs) in the Amazon Web Services General
     * Reference.

     */
    inline const Aws::String& GetArn() const{ return m_arn; }

    /**
     *
The Amazon Resource Name (ARN) of the node. For more information about ARNs
     * and their format, see Amazon
     * Resource Names (ARNs) in the Amazon Web Services General
     * Reference.

     */
    inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the node. For more information about ARNs
     * and their format, see Amazon
     * Resource Names (ARNs) in the Amazon Web Services General
     * Reference.

     */
    inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }

    /**
     *
The Amazon Resource Name (ARN) of the node. For more information about ARNs
     * and their format, see Amazon
     * Resource Names (ARNs) in the Amazon Web Services General
     * Reference.

     */
    inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the node. For more information about ARNs
     * and their format, see Amazon
     * Resource Names (ARNs) in the Amazon Web Services General
     * Reference.

     */
    inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the node. For more information about ARNs
     * and their format, see Amazon
     * Resource Names (ARNs) in the Amazon Web Services General
     * Reference.

     */
    inline NodeSummary& WithArn(const Aws::String& value) { SetArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the node. For more information about ARNs
     * and their format, see Amazon
     * Resource Names (ARNs) in the Amazon Web Services General
     * Reference.

     */
    inline NodeSummary& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the node. For more information about ARNs
     * and their format, see Amazon
     * Resource Names (ARNs) in the Amazon Web Services General
     * Reference.

     */
    inline NodeSummary& WithArn(const char* value) { SetArn(value); return *this;}

  private:

    Aws::String m_id;
    bool m_idHasBeenSet = false;

    NodeStatus m_status;
    bool m_statusHasBeenSet = false;

    Aws::Utils::DateTime m_creationDate;
    bool m_creationDateHasBeenSet = false;

    Aws::String m_availabilityZone;
    bool m_availabilityZoneHasBeenSet = false;

    Aws::String m_instanceType;
    bool m_instanceTypeHasBeenSet = false;

    Aws::String m_arn;
    bool m_arnHasBeenSet = false;
  };

} // namespace Model
} // namespace ManagedBlockchain
} // namespace Aws


text:
declare namespace ಠ_ಠ.clutz.innerTypeDef {
  class Foo extends Foo_Instance {
  }
  class Foo_Instance {
    private noStructuralTyping_: any;
  }
}
declare namespace ಠ_ಠ.clutz.innerTypeDef.Foo {
  type Bar = { a : string } ;
}
declare namespace goog {
  function require(name: 'innerTypeDef.Foo'): typeof ಠ_ಠ.clutz.innerTypeDef.Foo;
}
declare module 'goog:innerTypeDef.Foo' {
  import alias = ಠ_ಠ.clutz.innerTypeDef.Foo;
  export default alias;
}


text:
using System;
using System.Linq;
using Fody;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;

public class MethodProcessor
{
    public ModuleWeaver ModuleWeaver;
    public MethodDefinition Method;
    MethodBody body;
    VariableDefinition stopwatchVar;

    public void Process()
    {
        try
        {
            InnerProcess();
        }
        catch (Exception exception)
        {
            throw new WeavingException($"An error occurred processing '{Method.FullName}'. Error: {exception.Message}");
        }
    }

    void InnerProcess()
    {
        body = Method.Body;
        body.SimplifyMacros();

        var firstInstruction = FirstInstructionSkipCtor();

        var indexOf = body.Instructions.IndexOf(firstInstruction);

        var returnInstruction = FixReturns();

        stopwatchVar = ModuleWeaver.InjectStopwatch(body, indexOf);

        var beforeReturn = Instruction.Create(OpCodes.Nop);
        body.InsertBefore(returnInstruction, beforeReturn);

        InjectIlForFinally(returnInstruction);

        var handler = new ExceptionHandler(ExceptionHandlerType.Finally)
        {
            TryStart = firstInstruction,
            TryEnd = beforeReturn,
            HandlerStart = beforeReturn,
            HandlerEnd = returnInstruction,
        };

        body.ExceptionHandlers.Add(handler);
        body.InitLocals = true;
        body.OptimizeMacros();
    }

    Instruction FirstInstructionSkipCtor()
    {
        if (Method.IsInstanceConstructor())
        {
            foreach (var instruction in body.Instructions)
            {
                if (instruction.OpCode != OpCodes.Call)
                {
                    continue;
                }
                var methodReference = instruction.Operand as MethodReference;
                if (methodReference.Name != ".ctor")
                {
                    continue;
                }
                if (methodReference.DeclaringType != Method.DeclaringType.BaseType)
                {
                    continue;
                }
                return instruction.Next;
            }
        }
        return body.Instructions.First();
    }

    Instruction FixReturns()
    {
        var instructions = body.Instructions;
        if (Method.ReturnType.FullName == ModuleWeaver.TypeSystem.VoidReference.FullName)
        {
            var lastRet = Instruction.Create(OpCodes.Ret);

            foreach (var instruction in instructions)
            {
                if (instruction.OpCode == OpCodes.Ret)
                {
                    instruction.OpCode = OpCodes.Leave;
                    instruction.Operand = lastRet;
                }
            }
            instructions.Add(lastRet);
            return lastRet;
        }
        var returnVariable = new VariableDefinition(Method.ReturnType);
        body.Variables.Add(returnVariable);
        var lastLd = Instruction.Create(OpCodes.Ldloc, returnVariable);
        for (var index = 0; index < instructions.Count; index++)
        {
            var instruction = instructions[index];
            if (instruction.OpCode == OpCodes.Ret)
            {
                instruction.OpCode = OpCodes.Stloc;
                instruction.Operand = returnVariable;
                index++;
                instructions.Insert(index, Instruction.Create(OpCodes.Leave, lastLd));
            }
        }
        instructions.Add(lastLd);
        instructions.Add(Instruction.Create(OpCodes.Ret));
        return lastLd;
    }

    void InjectIlForFinally(Instruction beforeThis)
    {
        foreach (var instruction in ModuleWeaver.GetWriteTimeInstruction(stopwatchVar, Method))
        {
            body.InsertBefore(beforeThis, instruction);
        }

        body.InsertBefore(beforeThis, Instruction.Create(OpCodes.Endfinally));
    }
}


text:
from django import http

from yawf.views import YawfMessageView, HandlerViewMixin

from yawf_sample.simple.models import Window

class ResizeView(YawfMessageView):

    workflow_type = 'simple'
    model = Window
    message_id = 'edit__resize'

    def get_success_url(self):
        return '/'

class ToMaximizedView(HandlerViewMixin, YawfMessageView):

    workflow_type = 'simple'
    states_from = 'normal', 'minimized'

    def get_message_id(self):
        return 'maximize'

    def perform(self, obj, sender):
        return 'maximized'

    def wrap_yawf_result(self, obj, hr, er):
        return http.HttpResponse('OK')

window_resize = ResizeView.as_view()
window_maximize = ToMaximizedView.as_view()


text:
package io.github.jonestimd.finance.stockquote;

import java.awt.Color;
import java.awt.Component;
import java.math.BigDecimal;

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

import io.github.jonestimd.finance.stockquote.StockQuote.QuoteStatus;

public class StockQuoteTableCellRenderer extends DefaultTableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        if (value instanceof StockQuote) {
            StockQuote quote = (StockQuote) value;
            if (quote.getStatus() == QuoteStatus.SUCCESSFUL) {
                setHorizontalAlignment(RIGHT);
                setHorizontalTextPosition(LEADING);
                String price = "$" + quote.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                if (quote.getSourceUrl() == null) setValue(price);
                else setValue(String.format("%s", quote.getSourceUrl(), price));
                setIcon(quote.getSourceIcon());
                setToolTipText(quote.getSourceMessage());
            }
            else {
                setIcon(null);
                setHorizontalAlignment(CENTER);
                setForeground(Color.gray);
                setValue(quote.getStatus().value);
            }
        }
        return this;
    }
}


text:
from django.conf import settings # noqa
from django.db import connection
from django.db.models.signals import pre_delete  # noqa

# AWX
from awx.main.models.base import (  # noqa
    BaseModel, PrimordialModel, prevent_search, accepts_json,
    CLOUD_INVENTORY_SOURCES, VERBOSITY_CHOICES
)
from awx.main.models.unified_jobs import (  # noqa
    UnifiedJob, UnifiedJobTemplate, StdoutMaxBytesExceeded
)
from awx.main.models.organization import (  # noqa
    Organization, Profile, Team, UserSessionMembership
)
from awx.main.models.credential import (  # noqa
    Credential, CredentialType, CredentialInputSource, ManagedCredentialType, build_safe_env
)
from awx.main.models.projects import Project, ProjectUpdate  # noqa
from awx.main.models.inventory import (  # noqa
    CustomInventoryScript, Group, Host, Inventory, InventorySource,
    InventoryUpdate, SmartInventoryMembership
)
from awx.main.models.jobs import (  # noqa
    Job, JobHostSummary, JobLaunchConfig, JobTemplate, SystemJob,
    SystemJobTemplate,
)
from awx.main.models.events import (  # noqa
    AdHocCommandEvent, InventoryUpdateEvent, JobEvent, ProjectUpdateEvent,
    SystemJobEvent,
)
from awx.main.models.ad_hoc_commands import AdHocCommand # noqa
from awx.main.models.schedules import Schedule # noqa
from awx.main.models.activity_stream import ActivityStream # noqa
from awx.main.models.ha import (  # noqa
    Instance, InstanceGroup, TowerScheduleState,
)
from awx.main.models.rbac import (  # noqa
    Role, batch_role_ancestor_rebuilding, get_roles_on_resource,
    role_summary_fields_generator, ROLE_SINGLETON_SYSTEM_ADMINISTRATOR,
    ROLE_SINGLETON_SYSTEM_AUDITOR,
)
from awx.main.models.mixins import (  # noqa
    CustomVirtualEnvMixin, ResourceMixin, SurveyJobMixin,
    SurveyJobTemplateMixin, TaskManagerInventoryUpdateMixin,
    TaskManagerJobMixin, TaskManagerProjectUpdateMixin,
    TaskManagerUnifiedJobMixin,
)
from awx.main.models.notifications import (  # noqa
    Notification, NotificationTemplate,
    JobNotificationMixin
)
from awx.main.models.label import Label # noqa
from awx.main.models.workflow import (  # noqa
    WorkflowJob, WorkflowJobNode, WorkflowJobOptions, WorkflowJobTemplate,
    WorkflowJobTemplateNode, WorkflowApproval, WorkflowApprovalTemplate,
)
from awx.api.versioning import reverse
from awx.main.models.oauth import ( # noqa
    OAuth2AccessToken, OAuth2Application
)
from oauth2_provider.models import Grant, RefreshToken # noqa -- needed django-oauth-toolkit model migrations

# Add custom methods to User model for permissions checks.
from django.contrib.auth.models import User  # noqa
from awx.main.access import (  # noqa
    get_user_queryset, check_user_access, check_user_access_with_errors,
    user_accessible_objects
)

User.add_to_class('get_queryset', get_user_queryset)
User.add_to_class('can_access', check_user_access)
User.add_to_class('can_access_with_errors', check_user_access_with_errors)
User.add_to_class('accessible_objects', user_accessible_objects)

def enforce_bigint_pk_migration():
    # see: https://github.com/ansible/awx/issues/6010
    # look at all the event tables and verify that they have been fully migrated
    # from the *old* int primary key table to the replacement bigint table
    # if not, attempt to migrate them in the background
    for tblname in (
        'main_jobevent', 'main_inventoryupdateevent',
        'main_projectupdateevent', 'main_adhoccommandevent',
        'main_systemjobevent'
    ):
        with connection.cursor() as cursor:
            cursor.execute(
                'SELECT 1 FROM information_schema.tables WHERE table_name=%s',
                (f'_old_{tblname}',)
            )
            if bool(cursor.rowcount):
                from awx.main.tasks import migrate_legacy_event_data
                migrate_legacy_event_data.apply_async([tblname])

def cleanup_created_modified_by(sender, **kwargs):
    # work around a bug in django-polymorphic that doesn't properly
    # handle cascades for reverse foreign keys on the polymorphic base model
    # https://github.com/django-polymorphic/django-polymorphic/issues/229
    for cls in (UnifiedJobTemplate, UnifiedJob):
        cls.objects.filter(created_by=kwargs['instance']).update(created_by=None)
        cls.objects.filter(modified_by=kwargs['instance']).update(modified_by=None)

pre_delete.connect(cleanup_created_modified_by, sender=User)

@property
def user_get_organizations(user):
    return Organization.objects.filter(member_role__members=user)

@property
def user_get_admin_of_organizations(user):
    return Organization.objects.filter(admin_role__members=user)

@property
def user_get_auditor_of_organizations(user):
    return Organization.objects.filter(auditor_role__members=user)

@property
def created(user):
    return user.date_joined

User.add_to_class('organizations', user_get_organizations)
User.add_to_class('admin_of_organizations', user_get_admin_of_organizations)
User.add_to_class('auditor_of_organizations', user_get_auditor_of_organizations)
User.add_to_class('created', created)

@property
def user_is_system_auditor(user):
    if not hasattr(user, '_is_system_auditor'):
        if user.pk:
            user._is_system_auditor = user.roles.filter(
                singleton_name='system_auditor', role_field='system_auditor').exists()
        else:
            # Odd case where user is unsaved, this should never be relied on
            return False
    return user._is_system_auditor

@user_is_system_auditor.setter
def user_is_system_auditor(user, tf):
    if not user.id:
        # If the user doesn't have a primary key yet (i.e., this is the *first*
        # time they've logged in, and we've just created the new User in this
        # request), we need one to set up the system auditor role
        user.save()
    if tf:
        role = Role.singleton('system_auditor')
        # must check if member to not duplicate activity stream
        if user not in role.members.all():
            role.members.add(user)
        user._is_system_auditor = True
    else:
        role = Role.singleton('system_auditor')
        if user in role.members.all():
            role.members.remove(user)
        user._is_system_auditor = False

User.add_to_class('is_system_auditor', user_is_system_auditor)

def user_is_in_enterprise_category(user, category):
    ret = (category,) in user.enterprise_auth.values_list('provider') and not user.has_usable_password()
    # NOTE: this if-else block ensures existing enterprise users are still able to
    # log in. Remove it in a future release
    if category == 'radius':
        ret = ret or not user.has_usable_password()
    elif category == 'saml':
        ret = ret or user.social_auth.all()
    return ret

User.add_to_class('is_in_enterprise_category', user_is_in_enterprise_category)

def o_auth2_application_get_absolute_url(self, request=None):
    return reverse('api:o_auth2_application_detail', kwargs={'pk': self.pk}, request=request)

OAuth2Application.add_to_class('get_absolute_url', o_auth2_application_get_absolute_url)

def o_auth2_token_get_absolute_url(self, request=None):
    return reverse('api:o_auth2_token_detail', kwargs={'pk': self.pk}, request=request)

OAuth2AccessToken.add_to_class('get_absolute_url', o_auth2_token_get_absolute_url)

from awx.main.registrar import activity_stream_registrar # noqa
activity_stream_registrar.connect(Organization)
activity_stream_registrar.connect(Inventory)
activity_stream_registrar.connect(Host)
activity_stream_registrar.connect(Group)
activity_stream_registrar.connect(InventorySource)
#activity_stream_registrar.connect(InventoryUpdate)
activity_stream_registrar.connect(Credential)
activity_stream_registrar.connect(CredentialType)
activity_stream_registrar.connect(Team)
activity_stream_registrar.connect(Project)
#activity_stream_registrar.connect(ProjectUpdate)
activity_stream_registrar.connect(JobTemplate)
activity_stream_registrar.connect(Job)
activity_stream_registrar.connect(AdHocCommand)
# activity_stream_registrar.connect(JobHostSummary)
# activity_stream_registrar.connect(JobEvent)
# activity_stream_registrar.connect(Profile)
activity_stream_registrar.connect(Schedule)
activity_stream_registrar.connect(CustomInventoryScript)
activity_stream_registrar.connect(NotificationTemplate)
activity_stream_registrar.connect(Notification)
activity_stream_registrar.connect(Label)
activity_stream_registrar.connect(User)
activity_stream_registrar.connect(WorkflowJobTemplate)
activity_stream_registrar.connect(WorkflowJobTemplateNode)
activity_stream_registrar.connect(WorkflowJob)
activity_stream_registrar.connect(WorkflowApproval)
activity_stream_registrar.connect(WorkflowApprovalTemplate)
activity_stream_registrar.connect(OAuth2Application)
activity_stream_registrar.connect(OAuth2AccessToken)

# prevent API filtering on certain Django-supplied sensitive fields
prevent_search(User._meta.get_field('password'))
prevent_search(OAuth2AccessToken._meta.get_field('token'))
prevent_search(RefreshToken._meta.get_field('token'))
prevent_search(OAuth2Application._meta.get_field('client_secret'))
prevent_search(OAuth2Application._meta.get_field('client_id'))
prevent_search(Grant._meta.get_field('code'))


text:
@implementation AppDelegate

UGClient * usergridClient;

// The following values must be changed to the organization, application, and notifier
// to match the names that you've created on the App Services platform. Be sure that
// the application you use allows Guest access (eg. sandbox) - or that you have the device
// log in to App Services.
// Also ensure that you update the Bundle Identifier and Provisioning Profile in the project Build Settings.
// You will need to set the "Code Signing Identity" options for "Debug" to your Provisioning Profile.

NSString * orgName = @"scottganyo";
NSString * appName = @"pushtest";
NSString * notifier = @"apple";

NSString * baseURL = @"https://api.usergrid.com";

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSLog(@"setting up app services connection");
    // connect and login to App Services
    usergridClient = [[UGClient alloc]initWithOrganizationId: orgName withApplicationID: appName baseURL: baseURL];
    [usergridClient setLogging:true]; //comment out to remove debug output from the console window

    // it's not necessary to explicitly login to App Services if the Guest role allows access
//    NSLog(@"logging in user");
//    [usergridClient logInUser: userName password: password];

    // Register for Push Notifications with Apple
    NSLog(@"registering for remove notifications");
    [application registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |
                                                     UIRemoteNotificationTypeAlert |
                                                     UIRemoteNotificationTypeSound];
    NSLog(@"done launching");
    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken
{
    // register device token with App Services (will create the Device entity if it doesn't exist)
    NSLog(@"registering token with app services");
    UGClientResponse *response = [usergridClient setDevicePushToken: newDeviceToken forNotifier: notifier];

    // you could use this if you log in as an app services user to associate the Device to your User
//    if (response.transactionState == kUGClientResponseSuccess) {
//        response = [self connectEntities: @"users" connectorID: @"me" type: @"devices" connecteeID: deviceId];
//    }

    if (response.transactionState != kUGClientResponseSuccess) {
        [self alert: response.rawResponse title: @"Error"];
    }
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    [self alert: error.localizedDescription title: @"Error"];
}

- (void)sendMyselfAPushNotification:(NSString *)message
{
    NSString *deviceId = [UGClient getUniqueDeviceID];
    NSString *thisDevice = [@"devices/" stringByAppendingString: deviceId];

    UGClientResponse *response = [usergridClient pushAlert: message
                                                 withSound: @"chime"
                                                        to: thisDevice
                                             usingNotifier: notifier];

    if (response.transactionState != kUGClientResponseSuccess) {
        [self alert: response.rawResponse title: @"Error"];
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // Received a push notification from the server
    // Only pop alert if applicationState is active (if not, the user already saw the alert)
    if (application.applicationState == UIApplicationStateActive)
    {
        NSString * message = [NSString stringWithFormat:@"Text:\n%@",
                              [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]];
        [self alert: message title: @"Remote Notification"];
    }
}

- (void)alert:(NSString *)message title:(NSString *)title
{
    NSLog(@"displaying alert. title: %@, message: %@", title, message);
    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle: title
                              message: message
                              delegate: self
                              cancelButtonTitle: @"OK"
                              otherButtonTitles: nil];
    [alertView show];
}

@end


text:
package org.libx4j.maven.plugin.rdb.jsql;

import static org.libx4j.rdb.jsql.DML.*;

import java.io.IOException;
import java.sql.SQLException;

import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.lib4j.test.MixedTest;
import org.libx4j.maven.plugin.rdb.jsql.runner.VendorSchemaRunner;
import org.libx4j.rdb.ddlx.runner.Derby;
import org.libx4j.rdb.ddlx.runner.MySQL;
import org.libx4j.rdb.ddlx.runner.Oracle;
import org.libx4j.rdb.ddlx.runner.PostgreSQL;
import org.libx4j.rdb.ddlx.runner.SQLite;
import org.libx4j.rdb.jsql.RowIterator;
import org.libx4j.rdb.jsql.classicmodels;
import org.libx4j.rdb.jsql.type;

@RunWith(VendorSchemaRunner.class)
@VendorSchemaRunner.Schema(classicmodels.class)
@VendorSchemaRunner.Test({Derby.class, SQLite.class})
@VendorSchemaRunner.Integration({MySQL.class, PostgreSQL.class, Oracle.class})
@Category(MixedTest.class)
public class LimitExpressionTest {
  @Test
  public void testLimit() throws IOException, SQLException {
    final classicmodels.Product p = new classicmodels.Product();
    try (final RowIterator<type.DECIMAL.UNSIGNED> rows =
      SELECT(p.msrp, p.price).
      FROM(p).
      ORDER_BY(p.msrp, p.price).
      LIMIT(3).
      execute()) {
      Assert.assertTrue(rows.nextRow());
      Assert.assertEquals(Double.valueOf(33.19), rows.nextEntity().get().doubleValue(), 0.0000000001);
      Assert.assertEquals(Double.valueOf(22.57), rows.nextEntity().get().doubleValue(), 0.0000000001);
      Assert.assertTrue(rows.nextRow());
      Assert.assertEquals(Double.valueOf(35.36), rows.nextEntity().get().doubleValue(), 0.0000000001);
      Assert.assertEquals(Double.valueOf(15.91), rows.nextEntity().get().doubleValue(), 0.0000000001);
      Assert.assertTrue(rows.nextRow());
      Assert.assertEquals(Double.valueOf(37.76), rows.nextEntity().get().doubleValue(), 0.0000000001);
      Assert.assertEquals(Double.valueOf(16.24), rows.nextEntity().get().doubleValue(), 0.0000000001);
    }
  }

  @Test
  public void testLimitOffset() throws IOException, SQLException {
    final classicmodels.Product p = new classicmodels.Product();
    try (final RowIterator<type.DECIMAL.UNSIGNED> rows =
      SELECT(p.msrp, p.price).
      FROM(p).
      ORDER_BY(p.msrp, p.price).
      LIMIT(2).
      OFFSET(1).
      execute()) {
      Assert.assertTrue(rows.nextRow());
      Assert.assertEquals(Double.valueOf(35.36), rows.nextEntity().get().doubleValue(), 0.0000000001);
      Assert.assertEquals(Double.valueOf(15.91), rows.nextEntity().get().doubleValue(), 0.0000000001);
      Assert.assertTrue(rows.nextRow());
      Assert.assertEquals(Double.valueOf(37.76), rows.nextEntity().get().doubleValue(), 0.0000000001);
      Assert.assertEquals(Double.valueOf(16.24), rows.nextEntity().get().doubleValue(), 0.0000000001);
    }
  }
}


text:
'use strict';

/**
 * A scheduling library to allow scheduling work with more granular priority and
 * control than requestAnimationFrame and requestIdleCallback.
 * Current TODO items:
 * X- Pull out the scheduleWork polyfill built into React
 * X- Initial test coverage
 * X- Support for multiple callbacks
 * - Support for two priorities; serial and deferred
 * - Better test coverage
 * - Better docblock
 * - Polish documentation, API
 */

// This is a built-in polyfill for requestIdleCallback. It works by scheduling
// a requestAnimationFrame, storing the time for the start of the frame, then
// scheduling a postMessage which gets scheduled after paint. Within the
// postMessage handler do as much work as possible until time + frame rate.
// By separating the idle call into a separate event tick we ensure that
// layout, paint and other browser work is counted against the available time.
// The frame rate is dynamically adjusted.

import type {Deadline} from 'react-reconciler/src/ReactFiberScheduler';
type FrameCallbackType = Deadline => void;
type CallbackConfigType = {|
  scheduledCallback: FrameCallbackType,
  timeoutTime: number,
  next: CallbackConfigType | null, // creating a linked list
  prev: CallbackConfigType | null, // creating a linked list
|};

export type CallbackIdType = CallbackConfigType;

import requestAnimationFrameForReact from 'shared/requestAnimationFrameForReact';
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';

// We capture a local reference to any global, in case it gets polyfilled after
// this module is initially evaluated.
// We want to be using a consistent implementation.
const localDate = Date;
const localSetTimeout = setTimeout;
const localClearTimeout = clearTimeout;

const hasNativePerformanceNow =
  typeof performance === 'object' && typeof performance.now === 'function';

let now;
if (hasNativePerformanceNow) {
  const Performance = performance;
  now = function() {
    return Performance.now();
  };
} else {
  now = function() {
    return localDate.now();
  };
}

let scheduleWork: (
  callback: FrameCallbackType,
  options?: {timeout: number},
) => CallbackIdType;
let cancelScheduledWork: (callbackId: CallbackIdType) => void;

if (!ExecutionEnvironment.canUseDOM) {
  const timeoutIds = new Map();

  scheduleWork = function(
    callback: FrameCallbackType,
    options?: {timeout: number},
  ): CallbackIdType {
    // keeping return type consistent
    const callbackConfig = {
      scheduledCallback: callback,
      timeoutTime: 0,
      next: null,
      prev: null,
    };
    const timeoutId = localSetTimeout(() => {
      callback({
        timeRemaining() {
          return Infinity;
        },
        didTimeout: false,
      });
    });
    timeoutIds.set(callback, timeoutId);
    return callbackConfig;
  };
  cancelScheduledWork = function(callbackId: CallbackIdType) {
    const callback = callbackId.scheduledCallback;
    const timeoutId = timeoutIds.get(callback);
    timeoutIds.delete(callbackId);
    localClearTimeout(timeoutId);
  };
} else {
  let headOfPendingCallbacksLinkedList: CallbackConfigType | null = null;
  let tailOfPendingCallbacksLinkedList: CallbackConfigType | null = null;

  // We track what the next soonest timeoutTime is, to be able to quickly tell
  // if none of the scheduled callbacks have timed out.
  let nextSoonestTimeoutTime = -1;

  let isIdleScheduled = false;
  let isAnimationFrameScheduled = false;

  let frameDeadline = 0;
  // We start out assuming that we run at 30fps but then the heuristic tracking
  // will adjust this value to a faster fps if we get more frequent animation
  // frames.
  let previousFrameTime = 33;
  let activeFrameTime = 33;

  const frameDeadlineObject: Deadline = {
    didTimeout: false,
    timeRemaining() {
      const remaining = frameDeadline - now();
      return remaining > 0 ? remaining : 0;
    },
  };

  /**
   * Handles the case where a callback errors:
   * - don't catch the error, because this changes debugging behavior
   * - do start a new postMessage callback, to call any remaining callbacks,
   * - but only if there is an error, so there is not extra overhead.
   */
  const callUnsafely = function(
    callbackConfig: CallbackConfigType,
    arg: Deadline,
  ) {
    const callback = callbackConfig.scheduledCallback;
    let finishedCalling = false;
    try {
      callback(arg);
      finishedCalling = true;
    } finally {
      // always remove it from linked list
      cancelScheduledWork(callbackConfig);

      if (!finishedCalling) {
        // an error must have been thrown
        isIdleScheduled = true;
        window.postMessage(messageKey, '*');
      }
    }
  };

  /**
   * Checks for timed out callbacks, runs them, and then checks again to see if
   * any more have timed out.
   * Keeps doing this until there are none which have currently timed out.
   */
  const callTimedOutCallbacks = function() {
    if (headOfPendingCallbacksLinkedList === null) {
      return;
    }

    const currentTime = now();
    // TODO: this would be more efficient if deferred callbacks are stored in
    // min heap.
    // Or in a linked list with links for both timeoutTime order and insertion
    // order.
    // For now an easy compromise is the current approach:
    // Keep a pointer to the soonest timeoutTime, and check that first.
    // If it has not expired, we can skip traversing the whole list.
    // If it has expired, then we step through all the callbacks.
    if (nextSoonestTimeoutTime === -1 || nextSoonestTimeoutTime > currentTime) {
      // We know that none of them have timed out yet.
      return;
    }
    // NOTE: we intentionally wait to update the nextSoonestTimeoutTime until
    // after successfully calling any timed out callbacks.
    // If a timed out callback throws an error, we could get stuck in a state
    // where the nextSoonestTimeoutTime was set wrong.
    let updatedNextSoonestTimeoutTime = -1; // we will update nextSoonestTimeoutTime below
    const timedOutCallbacks = [];

    // iterate once to find timed out callbacks and find nextSoonestTimeoutTime
    let currentCallbackConfig = headOfPendingCallbacksLinkedList;
    while (currentCallbackConfig !== null) {
      const timeoutTime = currentCallbackConfig.timeoutTime;
      if (timeoutTime !== -1 && timeoutTime <= currentTime) {
        // it has timed out!
        timedOutCallbacks.push(currentCallbackConfig);
      } else {
        if (
          timeoutTime !== -1 &&
          (updatedNextSoonestTimeoutTime === -1 ||
            timeoutTime < updatedNextSoonestTimeoutTime)
        ) {
          updatedNextSoonestTimeoutTime = timeoutTime;
        }
      }
      currentCallbackConfig = currentCallbackConfig.next;
    }

    if (timedOutCallbacks.length > 0) {
      frameDeadlineObject.didTimeout = true;
      for (let i = 0, len = timedOutCallbacks.length; i < len; i++) {
        callUnsafely(timedOutCallbacks[i], frameDeadlineObject);
      }
    }

    // NOTE: we intentionally wait to update the nextSoonestTimeoutTime until
    // after successfully calling any timed out callbacks.
    nextSoonestTimeoutTime = updatedNextSoonestTimeoutTime;
  };

  // We use the postMessage trick to defer idle work until after the repaint.
  const messageKey =
    '__reactIdleCallback$' +
    Math.random()
      .toString(36)
      .slice(2);
  const idleTick = function(event) {
    if (event.source !== window || event.data !== messageKey) {
      return;
    }
    isIdleScheduled = false;

    if (headOfPendingCallbacksLinkedList === null) {
      return;
    }

    // First call anything which has timed out, until we have caught up.
    callTimedOutCallbacks();

    let currentTime = now();
    // Next, as long as we have idle time, try calling more callbacks.
    while (
      frameDeadline - currentTime > 0 &&
      headOfPendingCallbacksLinkedList !== null
    ) {
      const latestCallbackConfig = headOfPendingCallbacksLinkedList;
      frameDeadlineObject.didTimeout = false;
      // callUnsafely will remove it from the head of the linked list
      callUnsafely(latestCallbackConfig, frameDeadlineObject);
      currentTime = now();
    }
    if (headOfPendingCallbacksLinkedList !== null) {
      if (!isAnimationFrameScheduled) {
        // Schedule another animation callback so we retry later.
        isAnimationFrameScheduled = true;
        requestAnimationFrameForReact(animationTick);
      }
    }
  };
  // Assumes that we have addEventListener in this environment. Might need
  // something better for old IE.
  window.addEventListener('message', idleTick, false);

  const animationTick = function(rafTime) {
    isAnimationFrameScheduled = false;
    let nextFrameTime = rafTime - frameDeadline + activeFrameTime;
    if (
      nextFrameTime < activeFrameTime &&
      previousFrameTime < activeFrameTime
    ) {
      if (nextFrameTime < 8) {
        // Defensive coding. We don't support higher frame rates than 120hz.
        // If we get lower than that, it is probably a bug.
        nextFrameTime = 8;
      }
      // If one frame goes long, then the next one can be short to catch up.
      // If two frames are short in a row, then that's an indication that we
      // actually have a higher frame rate than what we're currently optimizing.
      // We adjust our heuristic dynamically accordingly. For example, if we're
      // running on 120hz display or 90hz VR display.
      // Take the max of the two in case one of them was an anomaly due to
      // missed frame deadlines.
      activeFrameTime =
        nextFrameTime < previousFrameTime ? previousFrameTime : nextFrameTime;
    } else {
      previousFrameTime = nextFrameTime;
    }
    frameDeadline = rafTime + activeFrameTime;
    if (!isIdleScheduled) {
      isIdleScheduled = true;
      window.postMessage(messageKey, '*');
    }
  };

  scheduleWork = function(
    callback: FrameCallbackType,
    options?: {timeout: number},
  ): CallbackIdType /* CallbackConfigType */ {
    let timeoutTime = -1;
    if (options != null && typeof options.timeout === 'number') {
      timeoutTime = now() + options.timeout;
    }
    if (
      nextSoonestTimeoutTime === -1 ||
      (timeoutTime !== -1 && timeoutTime < nextSoonestTimeoutTime)
    ) {
      nextSoonestTimeoutTime = timeoutTime;
    }

    const scheduledCallbackConfig: CallbackConfigType = {
      scheduledCallback: callback,
      timeoutTime,
      prev: null,
      next: null,
    };
    if (headOfPendingCallbacksLinkedList === null) {
      // Make this callback the head and tail of our list
      headOfPendingCallbacksLinkedList = scheduledCallbackConfig;
      tailOfPendingCallbacksLinkedList = scheduledCallbackConfig;
    } else {
      // Add latest callback as the new tail of the list
      scheduledCallbackConfig.prev = tailOfPendingCallbacksLinkedList;
      // renaming for clarity
      const oldTailOfPendingCallbacksLinkedList = tailOfPendingCallbacksLinkedList;
      if (oldTailOfPendingCallbacksLinkedList !== null) {
        oldTailOfPendingCallbacksLinkedList.next = scheduledCallbackConfig;
      }
      tailOfPendingCallbacksLinkedList = scheduledCallbackConfig;
    }

    if (!isAnimationFrameScheduled) {
      // If rAF didn't already schedule one, we need to schedule a frame.
      // TODO: If this rAF doesn't materialize because the browser throttles, we
      // might want to still have setTimeout trigger scheduleWork as a backup to ensure
      // that we keep performing work.
      isAnimationFrameScheduled = true;
      requestAnimationFrameForReact(animationTick);
    }
    return scheduledCallbackConfig;
  };

  cancelScheduledWork = function(
    callbackConfig: CallbackIdType /* CallbackConfigType */,
  ) {
    if (
      callbackConfig.prev === null &&
      headOfPendingCallbacksLinkedList !== callbackConfig
    ) {
      // this callbackConfig has already been cancelled.
      // cancelScheduledWork should be idempotent, a no-op after first call.
      return;
    }

    /**
     * There are four possible cases:
     * - Head/nodeToRemove/Tail -> null
     *   In this case we set Head and Tail to null.
     * - Head -> ... middle nodes... -> Tail/nodeToRemove
     *   In this case we point the middle.next to null and put middle as the new
     *   Tail.
     * - Head/nodeToRemove -> ...middle nodes... -> Tail
     *   In this case we point the middle.prev at null and move the Head to
     *   middle.
     * - Head -> ... ?some nodes ... -> nodeToRemove -> ... ?some nodes ... -> Tail
     *   In this case we point the Head.next to the Tail and the Tail.prev to
     *   the Head.
     */
    const next = callbackConfig.next;
    const prev = callbackConfig.prev;
    callbackConfig.next = null;
    callbackConfig.prev = null;
    if (next !== null) {
      // we have a next

      if (prev !== null) {
        // we have a prev

        // callbackConfig is somewhere in the middle of a list of 3 or more nodes.
        prev.next = next;
        next.prev = prev;
        return;
      } else {
        // there is a next but not a previous one;
        // callbackConfig is the head of a list of 2 or more other nodes.
        next.prev = null;
        headOfPendingCallbacksLinkedList = next;
        return;
      }
    } else {
      // there is no next callback config; this must the tail of the list

      if (prev !== null) {
        // we have a prev

        // callbackConfig is the tail of a list of 2 or more other nodes.
        prev.next = null;
        tailOfPendingCallbacksLinkedList = prev;
        return;
      } else {
        // there is no previous callback config;
        // callbackConfig is the only thing in the linked list,
        // so both head and tail point to it.
        headOfPendingCallbacksLinkedList = null;
        tailOfPendingCallbacksLinkedList = null;
        return;
      }
    }
  };
}

export {now, scheduleWork, cancelScheduledWork};


text:
import os
from unittest import TestCase
from io import StringIO
import tempfile
import shutil

import deepchem as dc

class TestCSVLoader(TestCase):

  def test_load_singleton_csv(self):
    fin = tempfile.NamedTemporaryFile(mode='w', delete=False)
    fin.write("smiles,endpoint\nc1ccccc1,1")
    fin.close()
    print(fin.name)
    featurizer = dc.feat.CircularFingerprint(size=1024)
    tasks = ["endpoint"]
    loader = dc.data.CSVLoader(
        tasks=tasks, smiles_field="smiles", featurizer=featurizer)

    X = loader.create_dataset(fin.name)
    self.assertEqual(1, len(X))
    os.remove(fin.name)