text:
"""TensorFlow-related utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import six

from tensorflow.python.eager import context
from tensorflow.python.framework import composite_tensor
from tensorflow.python.framework import ops
from tensorflow.python.framework import smart_cond as smart_module
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import variables
from tensorflow.python.util import nest

def smart_cond(pred, true_fn=None, false_fn=None, name=None):
  """Return either `true_fn()` if predicate `pred` is true else `false_fn()`.

  If `pred` is a bool or has a constant value, we return either `true_fn()`
  or `false_fn()`, otherwise we use `tf.cond` to dynamically route to both.

  Arguments:
    pred: A scalar determining whether to return the result of `true_fn` or
      `false_fn`.
    true_fn: The callable to be performed if pred is true.
    false_fn: The callable to be performed if pred is false.
    name: Optional name prefix when using `tf.cond`.

  Returns:
    Tensors returned by the call to either `true_fn` or `false_fn`.

  Raises:
    TypeError: If `true_fn` or `false_fn` is not callable.
  """
  if isinstance(pred, variables.Variable):
    return control_flow_ops.cond(
        pred, true_fn=true_fn, false_fn=false_fn, name=name)
  return smart_module.smart_cond(
      pred, true_fn=true_fn, false_fn=false_fn, name=name)

def constant_value(pred):
  """Return the bool value for `pred`, or None if `pred` had a dynamic value.

  Arguments:
    pred: A scalar, either a Python bool or a TensorFlow boolean variable
      or tensor, or the Python integer 1 or 0.

  Returns:
    True or False if `pred` has a constant boolean value, None otherwise.

  Raises:
    TypeError: If `pred` is not a Variable, Tensor or bool, or Python
      integer 1 or 0.
  """
  # Allow integer booleans.
  if isinstance(pred, int):
    if pred == 1:
      pred = True
    elif pred == 0:
      pred = False

  if isinstance(pred, variables.Variable):
    return None
  return smart_module.smart_constant_value(pred)

def is_tensor_or_tensor_list(v):
  v = nest.flatten(v)
  if v and isinstance(v[0], ops.Tensor):
    return True
  else:
    return False

def get_reachable_from_inputs(inputs, targets=None):
  """Returns the set of tensors/ops reachable from `inputs`.

  Stops if all targets have been found (target is optional).

  Only valid in Symbolic mode, not Eager mode.

  Args:
    inputs: List of tensors.
    targets: List of tensors.

  Returns:
    A set of tensors reachable from the inputs (includes the inputs themselves).
  """
  inputs = nest.flatten(inputs)
  reachable = set(inputs)
  if targets:
    targets = set(targets)
  queue = inputs[:]

  while queue:
    x = queue.pop()
    if isinstance(x, tuple(_user_convertible_tensor_types)):
      # Can't find consumers of user-specific types.
      continue

    if isinstance(x, ops.Operation):
      outputs = x.outputs[:] or []
      outputs += x._control_outputs  # pylint: disable=protected-access
    elif isinstance(x, variables.Variable):
      try:
        outputs = [x.op]
      except AttributeError:
        # Variables can be created in an Eager context.
        outputs = []
    elif tensor_util.is_tensor(x):
      outputs = x.consumers()
    else:
      raise TypeError('Expected Operation, Variable, or Tensor, got ' + str(x))

    for y in outputs:
      if y not in reachable:
        reachable.add(y)
        queue.insert(0, y)

    if targets and targets.issubset(reachable):
      return reachable
  return reachable

# This function needs access to private functions of `nest`.
#  pylint: disable=protected-access
def map_structure_with_atomic(is_atomic_fn, map_fn, nested):
  """Maps the atomic elements of a nested structure.

  Arguments:
    is_atomic_fn: A function that determines if an element of `nested` is
      atomic.
    map_fn: The function to apply to atomic elements of `nested`.
    nested: A nested structure.

  Returns:
    The nested structure, with atomic elements mapped according to `map_fn`.

  Raises:
    ValueError: If an element that is neither atomic nor a sequence is
      encountered.
  """
  if is_atomic_fn(nested):
    return map_fn(nested)

  # Recursively convert.
  if not nest.is_sequence(nested):
    raise ValueError(
        'Received non-atomic and non-sequence element: {}'.format(nested))
  if nest._is_mapping(nested):
    values = [nested[k] for k in nest._sorted(nested)]
  else:
    values = nested
  mapped_values = [
      map_structure_with_atomic(is_atomic_fn, map_fn, ele) for ele in values
  ]
  return nest._sequence_like(nested, mapped_values)

#  pylint: enable=protected-access

def convert_shapes(input_shape, to_tuples=True):
  """Converts nested shape representations  to desired format.

  Performs:

  TensorShapes -> tuples if `to_tuples=True`.
  tuples of int or None -> TensorShapes if `to_tuples=False`.

  Valid objects to be converted are:
  - TensorShapes
  - tuples with elements of type int or None.
  - ints
  - None

  Arguments:
    input_shape: A nested structure of objects to be converted to TensorShapes.
    to_tuples: If `True`, converts all TensorShape to tuples. Otherwise converts
      all tuples representing shapes to TensorShapes.

  Returns:
    Nested structure of shapes in desired format.
  """

  def _is_shape_component(element):
    value = tensor_shape.as_dimension(element).value
    return value is None or isinstance(value, int)

  def _is_atomic_shape(input_shape):
    # Ex: TensorShape or (None, 10, 32) or 5 or `None`
    if input_shape is None or isinstance(input_shape, int):
      return True
    if isinstance(input_shape, tensor_shape.TensorShape):
      return True
    if (isinstance(input_shape, tuple) and
        all(_is_shape_component(ele) for ele in input_shape)):
      return True
    return False

  def _convert_shape(input_shape):
    input_shape = tensor_shape.TensorShape(input_shape)
    if to_tuples:
      input_shape = tuple(input_shape.as_list())
    return input_shape

  return map_structure_with_atomic(_is_atomic_shape, _convert_shape,
                                   input_shape)

class ListWrapper(object):
  """A wrapper for lists to be treated as elements for `nest`."""

  def __init__(self, list_to_wrap):
    self._list = list_to_wrap

  def as_list(self):
    return self._list

def convert_inner_node_data(nested, wrap=False):
  """Either wraps or unwraps innermost node data lists in `ListWrapper` objects.

  Arguments:
    nested: A nested data structure.
    wrap: If `True`, wrap innermost lists in `ListWrapper` objects. If `False`,
      unwraps `ListWrapper` objects into lists.

  Returns:
    Strucutre of same type as nested, with lists wrapped/unwrapped.
  """

  def _is_atomic_nested(nested):
    """Returns `True` if `nested` is a list representing node data."""
    if isinstance(nested, ListWrapper):
      return True
    # Node data can be of form `[layer_name, node_id, tensor_id]` or
    # `[layer_name, node_id, tensor_id, kwargs]`.
    if (isinstance(nested, list) and (len(nested) in [3, 4]) and
        isinstance(nested[0], six.string_types)):
      return True
    return False

  def _convert_object_or_list(nested):
    """Convert b/t `ListWrapper` object and list representations."""
    if wrap:
      if isinstance(nested, ListWrapper):
        return nested
      return ListWrapper(nested)
    else:
      if isinstance(nested, ListWrapper):
        return nested.as_list()
      return nested

  return map_structure_with_atomic(_is_atomic_nested, _convert_object_or_list,
                                   nested)

def shape_type_conversion(fn):
  """Decorator that handles tuple/TensorShape conversion.

  Used in `compute_output_shape` and `build`.

  Arguments:
    fn: function to wrap.

  Returns:
    Wrapped function.
  """

  def wrapper(instance, input_shape):
    # Pass shapes as tuples to `fn`
    # This preserves compatibility with external Keras.
    if input_shape is not None:
      input_shape = convert_shapes(input_shape, to_tuples=True)
    output_shape = fn(instance, input_shape)
    # Return shapes from `fn` as TensorShapes.
    if output_shape is not None:
      output_shape = convert_shapes(output_shape, to_tuples=False)
    return output_shape

  return wrapper

def are_all_symbolic_tensors(tensors):
  return all(is_symbolic_tensor(tensor) for tensor in tensors)

_user_convertible_tensor_types = set()

def is_symbolic_tensor(tensor):
  """Returns whether a tensor is symbolic (from a TF graph) or an eager tensor.

  A Variable can be seen as either: it is considered symbolic
  when we are in a graph scope, and eager when we are in an eager scope.

  Arguments:
    tensor: A tensor instance to test.

  Returns:
    True for symbolic tensors, False for eager tensors.
  """
  if isinstance(tensor, variables.Variable):
    # Variables that are output of a Keras Layer in Functional API mode
    # should be considered symbolic.
    # TODO(omalleyt): We need a better way to check this in order to
    # enable `run_eagerly=True` for Models containing Layers that
    # return Variables as outputs.
    return (getattr(tensor, '_keras_history', False) or
            not context.executing_eagerly())
  if isinstance(tensor, composite_tensor.CompositeTensor):
    return tensor._is_graph_tensor  # pylint: disable=protected-access
  if isinstance(tensor, ops.Tensor):
    return hasattr(tensor, 'graph')
  if isinstance(tensor, tuple(_user_convertible_tensor_types)):
    return hasattr(ops.convert_to_tensor(tensor), 'graph')
  return False

def register_symbolic_tensor_type(cls):
  """Allows users to specify types regarded as symbolic `Tensor`s.

  Used in conjunction with `tf.register_tensor_conversion_function`, calling
  `tf.keras.utils.register_symbolic_tensor_type(cls)` allows non-`Tensor`
  objects to be plumbed through Keras layers.

  Example:

  ```python
  # One-time setup.
  class Foo(object):
    def __init__(self, input_):
      self._input = input_
    def value(self):
      return tf.constant(42.)

  tf.register_tensor_conversion_function(
      Foo, lambda x, *args, **kwargs: x.value())

  tf.keras.utils.register_symbolic_tensor_type(Foo)

  # User-land.
  layer = tf.keras.layers.Lambda(lambda input_: Foo(input_))
  ```

  Arguments:
    cls: A `class` type which shall be regarded as a symbolic `Tensor`.
  """
  global _user_convertible_tensor_types
  _user_convertible_tensor_types.add(cls)

def is_tensor_or_variable(x):
  return tensor_util.is_tensor(x) or isinstance(x, variables.Variable)


text:
using System;
using System.Data.Common;
using System.IO;
using System.Linq;
using Hardcore.Db.Test;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Tests
{
    [TestClass]
    public partial class TestDbSegmentBehavior
    {
        [TestMethod]
        public void ShouldProvideAccessToOwnTables()
        {
            //Arrange
            var def = new TestDbDef(DbName);
            var db = TestDb.Create(def);

            var segment = db.CreateSegment(new[]
            {
                new TableDef<SegmentTableModel>
                {
                    Items = new[]
                    {
                        new SegmentTableModel()
                    }
                }
            });

            //Act
            int count = segment.Tab<SegmentTableModel>().Count();

            //Assert
            Assert.AreEqual(1, count);
        }

        [TestMethod]
        public void ShouldProvideAccessToOtherTablesOfDb()
        {
            //Arrange
            var def = new TestDbDef(DbName)
            {
                Tables = new TableDef[]
                {
                    new TableDef<TableModel>
                    {
                        Items = new[]
                        {
                            new TableModel()
                        }
                    },
                }
            };
            var db = TestDb.Create(def);
            var segment = db.CreateSegment(new TableDef[0]);

            //Act
            int count = segment.Tab<TableModel>().Count();

            //Assert
            Assert.AreEqual(1, count);
        }

        [TestMethod]
        public void ShouldCleanupOwnTables()
        {
            //Arrange
            var def = new TestDbDef(DbName)
            {
                Tables = new TableDef[]
                {
                    new TableDef<TableModel>()
                }
            };
            var db = TestDb.Create(def);

            var segment = db.CreateSegment(new[]
            {
                new TableDef<SegmentTableModel>
                {
                    Items = new[]
                    {
                        new SegmentTableModel()
                    }
                }
            });

            //Act
            segment.Cleanup();
            var count = segment.Tab<TableModel>().Count();

            //Assert
            Assert.AreEqual(0, count);
        }

        [TestMethod]
        public void ShouldNotCleanupOtherTabesOfDb()
        {
            //Arrange
            var def = new TestDbDef(DbName)
            {
                Tables = new TableDef[]
                {
                    new TableDef<TableModel>
                    {
                        Items = new[]
                        {
                            new TableModel()
                        }
                    },
                }
            };
            var db = TestDb.Create(def);
            var segment = db.CreateSegment(new TableDef[0]);

            //Act
            segment.Cleanup();
            int count = segment.Tab<TableModel>().Count();

            //Assert
            Assert.AreEqual(1, count);
        }

        [TestMethod]
        public void ShouldDropOwnTablesWhenDispose()
        {
            //Arrange
            var def = new TestDbDef(DbName);
            var db = TestDb.Create(def);

            var segment = db.CreateSegment(new TableDef[]
            {
                new TableDef<SegmentTableModel>()
            });
            DbException exception = null;

            //Act
            segment.Dispose();

            try
            {
                segment.Tab<SegmentTableModel>().Count();
            }
            catch (DbException e)
            {
                exception = e;
            }

            //Assert
            Assert.IsNotNull(exception);
            Assert.IsTrue(exception.Message.Contains("no such table"));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*! \file heap.h
 \brief Heap management functions.
*/

#ifndef __SYS_HEAP_H__
#define __SYS_HEAP_H__

#include <ppu-types.h>

#define HEAP_PREV_USED				1
#define HEAP_MIN_BLOCK_SIZE			(sizeof(heap_block))
#define HEAP_BLOCK_HEADER_OFFSET	(sizeof(u32))
#define HEAP_BLOCK_USER_OFFSET		(sizeof(u32)*2)
#define HEAP_BLOCK_USED_OVERHEAD	(HEAP_BLOCK_USER_OFFSET - HEAP_BLOCK_HEADER_OFFSET)
#define HEAP_OVERHEAD				HEAP_BLOCK_USER_OFFSET

#ifdef __cplusplus
extern "C" {
#endif

typedef struct _heap_block_t heap_block;
struct _heap_block_t
{
	u32 prev_size;
	u32 size;
	heap_block *next;
	heap_block *prev;
};

typedef struct _heap_cntrl_t
{
	heap_block free_list;

	u32 page_size;
	u32 min_block_size;

	void *begin;
	void *end;

	heap_block *start;
	heap_block *final;

	s32 lock;
} heap_cntrl;

u32 heapInit(heap_cntrl *theheap,void *start_addr,u32 size);
void* heapAllocate(heap_cntrl *theheap,u32 size);
void* heapAllocateAligned(heap_cntrl *theheap,u32 size,u32 alignment);
bool heapFree(heap_cntrl *theheap,void *ptr);

#ifdef __cplusplus
	}
#endif

#endif


text:
package org.cache2k.pinpoint;

import java.time.Duration;
import java.util.concurrent.Semaphore;

/**
 * Collect exceptions or set final success for tasks running in concurrent threads.
 *
 * @author Jens Wilke
 */
public class TaskSuccessGuardian {

  private final Semaphore completed = new Semaphore(0);
  private final ExceptionCollector collector = new ExceptionCollector();
  private final Duration timeout;

  public TaskSuccessGuardian() {
    this(PinpointParameters.TIMEOUT);
  }

  public TaskSuccessGuardian(Duration timeout) {
    this.timeout = timeout;
  }

  public void completedWithException(Throwable t) { collector.exception(t); completed.release(); }
  public void completedWithSuccess() { completed.release(); }
  public void awaitCompletionAndAssertSuccess() {
    SupervisedExecutor.acquireOrTimeout(completed, timeout);
    collector.assertNoException();
  }
  public void executeGuarded(ExceptionalRunnable runnable) {
    try {
      runnable.run();
      completedWithSuccess();
    } catch (Throwable ex) {
      completedWithException(ex);
    }
  }

  @FunctionalInterface
  public interface ExceptionalRunnable {
    void run() throws Exception;
  }

}


text:
package uk.ac.ebi.spot.goci;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import uk.ac.ebi.spot.goci.service.DataImportExportService;
import uk.ac.ebi.spot.goci.service.FilterDataProcessingService;

import java.io.File;

/**
 * Created by dwelter on 05/04/16.
 */
@SpringBootApplication
public class AssociationFilterApplication {

    private static File outputFile;
    private static File inputFile;
    private static Boolean prune = false;
    private static Double threshold = 1e-5;

    @Autowired
    private DataImportExportService dataImportExportService;

    @Autowired
    private FilterDataProcessingService filterDataProcessingService;

    private final Logger log = LoggerFactory.getLogger(getClass());

    protected Logger getLog() {
        return log;
    }

    public static void main(String... args) {
        System.out.println("Starting Association Filter...");

        ApplicationContext ctx = SpringApplication.run(AssociationFilterApplication.class, args);
        System.out.println("Application executed successfully!");
        SpringApplication.exit(ctx);
    }

    @Bean CommandLineRunner run() {
        return strings -> {

            int parseArgs = parseArguments(strings);
            if (parseArgs == 0) {
                System.out.println("About to filter the input listagainst threshold " + threshold);
                getLog().debug("About to filter the input list against threshold " + threshold);

                this.doFiltering(inputFile, outputFile);
            }
            else {
                // could not parse arguments, exit with exit code >1 (depending on parsing problem)
                System.err.println("Failed to parse supplied arguments");
                getLog().error("Failed to parse supplied arguments");
                System.exit(1 + parseArgs);
            }
            System.out.println("Filtering complete");
            getLog().debug("Filtering complete");

        };
    }

    private static int parseArguments(String[] args) {
        CommandLineParser parser = new GnuParser();
        HelpFormatter help = new HelpFormatter();
        Options options = bindOptions();

        int parseArgs = 0;
        try {
            CommandLine cl = parser.parse(options, args, true);

            // check for mode help option
            if (cl.hasOption("")) {
                // print out mode help
                help.printHelp("filter", options, true);
                parseArgs += 1;
            }
            else {
                // find -o option (for asserted output file)
                if (cl.hasOption("o")) {
                    outputFile = new File(cl.getOptionValue("o"));

                }
                else {
                    System.err.println("-o (output file) argument is required");
                    help.printHelp("filter", options, true);
                    parseArgs += 2;
                }
                if (cl.hasOption("f")) {
                    inputFile = new File(cl.getOptionValue("f"));
                }
                else {
                    System.err.println("-f (input file) argument is required");
                    help.printHelp("filter", options, true);
                    parseArgs += 2;
                }
                if(cl.hasOption("p")) {
                    prune = true;
                }
                if(cl.hasOption("t")){
                    threshold = Double.valueOf(cl.getOptionValue("t"));
                }
            }
        }
        catch (ParseException e) {
            System.err.println("Failed to read supplied arguments");
            help.printHelp("filter", options, true);
            parseArgs += 4;
        }
        return parseArgs;
    }

    private static Options bindOptions() {
        Options options = new Options();

        // help
        Option helpOption = new Option("h", "help", false, "Print the help");
        options.addOption(helpOption);

        // add output file arguments
        Option outputFileOption = new Option("o", "output", true,
                                             "The output file to write the filtered list to");
        outputFileOption.setArgName("output");
        outputFileOption.setRequired(true);
        options.addOption(outputFileOption);

        Option inOption = new Option(
                "f",
                "file",
                true,
                "Input file - file where data to be filtered can be found");
        inOption.setArgName("file");
        inOption.setRequired(true);
        options.addOption(inOption);

        Option pruneOption = new Option(
                "p",
                "prune",
                false,
                "Prune output - removes associations with p-value < 1E-5 from the result output");
        pruneOption.setRequired(false);
        options.addOption(pruneOption);

        Option thresholdOption = new Option(
                "t",
                "threshold",
                true,
                "Filter only associations below the provided threshold. If no threshold is provided, the default of 1e-5 will be used.");
        thresholdOption.setRequired(false);
        options.addOption(thresholdOption);

        return options;
    }

    private void doFiltering(File inputFile, File outputFile) {
        try {
            getLog().info("Reading input file");
            String[][] data = dataImportExportService.readFromFile(inputFile);
            getLog().info("Input file processed, starting data transformation and filtering process");
            String[][] transformAssocations = filterDataProcessingService.filterInputData(data, threshold, prune);
            getLog().info("Exporting filtered data to file");
            dataImportExportService.writeToFile(transformAssocations, outputFile);
        }
//        catch (IOException e) {
//            e.printStackTrace();
//        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

}


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/pcl_hdl_grabber.dir/hdl_grabber_example.cpp.o"
  "../../bin/pcl_hdl_grabber.pdb"
  "../../bin/pcl_hdl_grabber"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/pcl_hdl_grabber.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
namespace openMVG {
namespace sfm {

/// Save the structure and camera positions of a SfM_Data container as 3D points in a PLY ASCII file.
static bool Save_PLY(
  const SfM_Data & data,
  const std::string & filename,
  ESfM_Data flags_part)
{
  const bool b_structure = (flags_part & STRUCTURE) == STRUCTURE;
  const bool b_extrinsics = (flags_part & EXTRINSICS) == EXTRINSICS;

  if (!(b_structure || b_extrinsics))
    return false;

  //Create the stream and check it is ok
  std::ofstream stream(filename.c_str());
  if (!stream.is_open())
    return false;

  bool bOk = false;
  {
    stream << "ply"
      << '\n' << "format ascii 1.0"
      << '\n' << "element vertex "
        << ((b_structure ? data.GetLandmarks().size() : 0) +
           (b_extrinsics ? data.GetPoses().size() : 0))
      << '\n' << "property float x"
      << '\n' << "property float y"
      << '\n' << "property float z"
      << '\n' << "property uchar red"
      << '\n' << "property uchar green"
      << '\n' << "property uchar blue"
      << '\n' << "end_header" << std::endl;

      if (b_extrinsics)
      {
        const Poses & poses = data.GetPoses();
        for (Poses::const_iterator iterPose = poses.begin();
          iterPose != poses.end(); ++iterPose)  {
            stream << iterPose->second.center().transpose()
              << " 0 255 0" << "\n";
        }
      }

      if (b_structure)
      {
        const Landmarks & landmarks = data.GetLandmarks();
        for (Landmarks::const_iterator iterLandmarks = landmarks.begin();
          iterLandmarks != landmarks.end();
          ++iterLandmarks)  {
          stream << iterLandmarks->second.X.transpose() << " 255 255 255" << "\n";
        }
      }
      stream.flush();
      bOk = stream.good();
      stream.close();
  }
  return bOk;
}

} // namespace sfm
} // namespace openMVG

#endif // OPENMVG_SFM_DATA_IO_PLY_HPP


text:
<?php
/**
	M_Instansi.php: Kelas model yang digunakan utk mengendalikan tabel master Instansi sebagai tempat kerja
	@hanson: 13/05/2016
**/
defined('BASEPATH') OR exit('No direct script access allowed');

class M_Instansi extends CI_Model {
/** @hanson: inisialisasi atribut **/
	function __construct() {
		parent::__construct();
        $this->tb = "tm_instansi";
    }

/** @hanson: mengambil semua record **/
	function select() {
        return $this->db->get($this->tb)->result();
    }

/** @hanson: mengambil semua instansi yang berada dalam satu kota tertentu **/
	function select_by_kota($kota) {
		$this->db->where("kota",$kota);
		$this->db->order_by("nama");
        return $this->db->get($this->tb)->result();
    }

/** @hanson: mengambil satu instansi berdasar id_instansi **/
	function get_by_id($id) {
		$this->db->where("id_instansi",$id);
        return $this->db->get($this->tb)->row();
    }

/** @hanson: mengambil daftar kota yang ada dalam data instansi **/
	function select_kota() {
		$this->db->select("kota");
		$this->db->distinct();
		$this->db->order_by("kota");
		return $this->db->get($this->tb)->result();
	}

/** @hanson: menyimpan data instansi baru ke basis data **/
	function insert($data) {
		$this->db->insert($this->tb, $data);
    }
}


text:
This guide is designed for developers that are familiar with CodeIgniter, but are just getting started with Bonfire.  It does not assume that you have any prior experience with Bonfire.

Bonfire is intended to provide a kickstart for new web applications built in CodeIgniter. If you don't know CodeIgniter you will need to get to speed with that first. There are a number of free tutorials out there, including:

* [CodeIgniter From Scratch Series - at NetTuts](http://net.tutsplus.com/sessions/codeigniter-from-scratch/)
* [Tutorials at the CodeIgniter Wiki](http://codeigniter.com/wiki/Category:Help::Tutorials)

## What is Bonfire?

Bonfire is a framework for your web application, built on top of the CodeIgniter PHP Framework. It is not a CMS, but a starting point for new projects that require ready-made tools like:

* Robust Role-Based-Access-Control
* Fully Modular Codebase. Built around HMVC.
* Database backup, migration, and maintenance.
* Powerful, parent/child capable theme engine.
* Simple Email queue to keep your ISP happy.
* and more...

### Bonfire Components

Bonfire ships with a number of individual components that are described below. Don't get hung up on the details of of each component for now. Many of these will be described in more detail below.

#### MY_Model

MY_Model provides a robust set of standard methods for you to derive your models from. Methods covering all standard CRUD routines, as well as simple methods that chain together. For simple models, all you have to do is extend the MY_Model class and set a couple of variables and you'll be up and running without any extra code.

#### MY_Controller

MY_Controller provides 4 different controllers that you can use to keep common functions within each 'zone' of your website: Base_Controller, Front_Controller, Authenticated_Controller and Admin_Controller. You can set different defaults in each controller for a different part of your site. For example, setting the admin theme in the Admin_Controller, or making sure the user is logged in with the Authenticated_Controller.

#### Role-Based Access Control

Bonfire's User module provides a flexible User_model, ready for your users to login with, as well as a flexible RBAC that is simple to use and flexible enough to fit most needs.

#### Database Tools

Quickly browse your database, perform backups, restore old bakups, and keep your database versioned with Migrations. Unlike CodeIgniter's built-in migrations, Bonfire extends them to allow for the core, your app, and each module to maintain their own set of migrations.

#### System Events

Very similar to CodeIgniter's Hooks, System Events allow you to hook into Bonfire's core code without modifying core files. It also provides a simple way for you to add hooks to your own code for other modules to use.

#### Activities Log

This library provides a simple way to log user activities, such as 'JohnDoe deleted the Page titled "Page 1"'. This makes it simple to keep a clear, consistent log of every important action of every user.

#### Settings

Easily store application-wide settings in the database, allowing your users to change settings simply and easily.

## Creating A New Bonfire Project

The best way to use this guide is to follow along, step-by-step, entering the code at each step. Everything you need to make this project work is included in this tutorial.

During this tutorial we will create a (simple) blog module that will have you mastering your way around Bonfire in no time.

## Navigating Bonfire

### Contexts

Once you log into the admin portion of Bonfire, you will find a menu with 4 categories across the top: Content, Reports, Settings, and Developer. These four categories are what Bonfire calls **Contexts**.

A Context is a way to group related content from different modules. It all happens automatically based upon the names of the controller and a little behind-the-scenes magic in the routes file. You don't need to understand all of the details about contexts just yet, but we will touch on how to use them in this tutorial.

You can create as many custom contexts as you want, and even remove the Content and Reports contexts, to meet the needs of your app. The Settings and Developer contexts are a central part of how Bonfire works and cannot be removed.

Contexts don't have to be visible to everyone who uses your admin area, though. They can be hidden individually per user role.

### Modules

Bonfire is primarily a collection of modules that handle all of the various parts. This makes it easy to create your own modules that can be reused and passed around with a minimum of work.

If you navigate the project, look in the main *bonfire* folder. You will find the following folder structure:

Folder      | Purpose
------------|---------------
application | Holds Bonfire's primary files and the core modules.
codeigniter | Holds the CodeIgniter system files.
modules     | Holds your own custom modules.
themes      | Holds all of your themes.

A module is a mini-application that can contain assets (like CSS or JS), config files, controllers, models, libraries, helpers, and views. This is all powered by [Modular Extensions HMVC](https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/wiki/Home) and allows for HMVC usage (which we will touch on later in the tutorial).

---

Next: [A Simple Blog Tutorial](tut_blog)


text:
package org.drools.workbench.models.testscenarios.backend.populators;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import org.drools.core.base.TypeResolver;
import org.drools.workbench.models.testscenarios.shared.FactData;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;

class ExistingFactPopulator extends FactPopulatorBase {

    public ExistingFactPopulator( Map<String, Object> populatedData,
                                  TypeResolver typeResolver,
                                  ClassLoader classLoader,
                                  FactData fact ) throws ClassNotFoundException {
        super( populatedData,
               typeResolver,
               classLoader,
               fact );
    }

    protected Object resolveFactObject() throws ClassNotFoundException {
        if ( !populatedData.containsKey( fact.getName() ) ) {
            throw new IllegalArgumentException( "Was not a previously inserted fact. [" + fact.getName() + "]" );
        }
        return populatedData.get( fact.getName() );
    }

    @Override
    public List<FieldPopulator> getFieldPopulators() throws ClassNotFoundException,
            IllegalAccessException,
            InstantiationException,
            InvocationTargetException,
            NoSuchMethodException {
        return getFieldPopulators( resolveFactObject() );
    }

    @Override
    public void populate( KieSession ksession,
                          Map<String, FactHandle> factHandles ) {
        ksession.update( factHandles.get( fact.getName() ),
                         populatedData.get( fact.getName() ) );

    }
}


text:
package org.apache.flink.table.planner.plan.nodes.exec.processor.utils;

import org.apache.flink.annotation.Internal;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.table.api.config.OptimizerConfigOptions;
import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
import org.apache.flink.table.planner.plan.nodes.exec.visitor.AbstractExecNodeExactlyOnceVisitor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Subclass of the {@link InputPriorityGraphGenerator}.
 *
 * <p>This class only calculates the input order for the given boundary nodes and will throw
 * exception when a conflict is detected.
 */
@Internal
public class InputOrderCalculator extends InputPriorityGraphGenerator {

    private final Set<ExecNode<?>> boundaries;

    /**
     * Create a {@link InputOrderCalculator} for the given {@link ExecNode} sub-graph.
     *
     * @param root the output node of the sub-graph
     * @param boundaries the first layer of nodes on the input side of the sub-graph
     * @param safeDamBehavior when checking for conflicts we'll ignore the edges with {@link
     *     ExecEdge.DamBehavior} stricter or equal than this
     */
    public InputOrderCalculator(
            ExecNode<?> root, Set<ExecNode<?>> boundaries, ExecEdge.DamBehavior safeDamBehavior) {
        super(Collections.singletonList(root), boundaries, safeDamBehavior);
        this.boundaries = boundaries;
    }

    public Map<ExecNode<?>, Integer> calculate() {
        createTopologyGraph();

        // some boundaries node may be connected from the outside of the sub-graph,
        // which we cannot deduce by the above process,
        // so we need to check each pair of boundaries and see if they're related
        dealWithPossiblyRelatedBoundaries();
        Map<ExecNode<?>, Integer> distances = graph.calculateMaximumDistance();

        // extract only the distances of the boundaries and renumbering the distances
        // so that the smallest value starts from 0
        // the smaller the distance, the higher the priority
        Set<Integer> boundaryDistanceSet = new HashSet<>();
        for (ExecNode<?> boundary : boundaries) {
            boundaryDistanceSet.add(distances.getOrDefault(boundary, 0));
        }
        List<Integer> boundaryDistanceList = new ArrayList<>(boundaryDistanceSet);
        Collections.sort(boundaryDistanceList);

        Map<ExecNode<?>, Integer> results = new HashMap<>();
        for (ExecNode<?> boundary : boundaries) {
            results.put(boundary, boundaryDistanceList.indexOf(distances.get(boundary)));
        }
        return results;
    }

    private void dealWithPossiblyRelatedBoundaries() {
        List<ExecNode<?>> boundaries = new ArrayList<>(this.boundaries);
        for (int i = 0; i < boundaries.size(); i++) {
            ExecNode<?> boundaryA = boundaries.get(i);
            for (int j = i + 1; j < boundaries.size(); j++) {
                ExecNode<?> boundaryB = boundaries.get(j);
                // if boundaries are already comparable in the topology graph
                // we do not need to check them
                if (graph.canReach(boundaryA, boundaryB) || graph.canReach(boundaryB, boundaryA)) {
                    continue;
                }
                dealWithPossiblyRelatedBoundaries(boundaryA, boundaryB);
            }
        }
    }

    private void dealWithPossiblyRelatedBoundaries(ExecNode<?> boundaryA, ExecNode<?> boundaryB) {
        Set<ExecNode<?>> ancestorsA = calculateAllAncestors(boundaryA);
        Set<ExecNode<?>> ancestorsB = calculateAllAncestors(boundaryB);
        if (checkPipelinedPath(boundaryA, ancestorsB)) {
            // boundary A and B are related, and there exists a path
            // which only goes through PIPELINED edges from their public ancestor to boundary A.
            // this means that the priority of boundary B should be at least as low as A
            graph.makeAsFarAs(boundaryB, boundaryA);
        }
        if (checkPipelinedPath(boundaryB, ancestorsA)) {
            // similar situation with above
            graph.makeAsFarAs(boundaryA, boundaryB);
        }
    }

    private static Set<ExecNode<?>> calculateAllAncestors(ExecNode<?> node) {
        Set<ExecNode<?>> ret = new HashSet<>();
        AbstractExecNodeExactlyOnceVisitor visitor =
                new AbstractExecNodeExactlyOnceVisitor() {
                    @Override
                    protected void visitNode(ExecNode<?> node) {
                        ret.add(node);
                        visitInputs(node);
                    }
                };
        node.accept(visitor);
        return ret;
    }

    @VisibleForTesting
    static boolean checkPipelinedPath(ExecNode<?> node, Set<ExecNode<?>> goals) {
        PipelinedPathChecker checker = new PipelinedPathChecker(goals);
        node.accept(checker);
        return checker.res;
    }

    private static class PipelinedPathChecker extends AbstractExecNodeExactlyOnceVisitor {
        private final Set<ExecNode<?>> goals;
        private boolean res;

        private PipelinedPathChecker(Set<ExecNode<?>> goals) {
            this.goals = goals;
            this.res = false;
        }

        @Override
        protected void visitNode(ExecNode<?> node) {
            if (goals.contains(node)) {
                res = true;
                return;
            }

            List<ExecEdge> inputEdges = node.getInputEdges();
            for (int i = 0; i < inputEdges.size(); i++) {
                if (inputEdges
                        .get(i)
                        .getDamBehavior()
                        .stricterOrEqual(ExecEdge.DamBehavior.END_INPUT)) {
                    continue;
                }
                visit(node.getInputNodes().get(i));
                if (res) {
                    return;
                }
            }
        }
    }

    @Override
    protected void resolveInputPriorityConflict(ExecNode<?> node, int higherInput, int lowerInput) {
        throw new IllegalStateException(
                "A conflict is detected. This is a bug. Please file an issue.\n"
                        + "To work around this bug, please set "
                        + OptimizerConfigOptions.TABLE_OPTIMIZER_MULTIPLE_INPUT_ENABLED.key()
                        + " to false to disable multiple input operator.");
    }
}


text:
<!DOCTYPE html>

  <title>dynamic.js</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
  <link rel="stylesheet" media="all" href="docco.css" />

          Jump To …
          +

                  dynamic.js

                  index.js

                  static.js

dynamic.js

                ¶

'use strict';

                ¶

Dependencies

const _ = require('lodash');

                ¶

Used to store dynamic routes, sorted by HTTP method,
and match based on routes

const dynamicRoutes = {
    HEAD    : {},
    GET     : {},
    POST    : {},
    PUT     : {},
    DELETE  : {},
    PATCH   : {}
};

                ¶

Parses the dynamic route in order to store it for reference later

@param   (url)       {String}    The url
@param   (method)    {String}    The HTTP method

function parseRoute (url, method) {

                ¶

Split the url into segments (based on number of items in url, and remove trailing slashes);

    const splitUrl    = _.compact(url.split('/'));
    if (!dynamicRoutes[method][splitUrl.length]) {
        dynamicRoutes[method][splitUrl.length] = [url];
    } else {
        dynamicRoutes[method][splitUrl.length].push(url);
    }
}

                ¶

Checks if a url matches a route with parameters

@param   (splitUrl)      {Array}     The url pathname turned into parts
@param   (possibleUrl)   {String}    The possible matching url
@return                  {Boolean}   Does the url match?

function urlMatchesRoute (splitUrl, possibleUrl) {
    const splitPossibleUrl = _.compact(possibleUrl.split('/'));
    for (let i=0;i<splitUrl.length;i++) {
        if (splitUrl[i] === splitPossibleUrl[i]) {
            if (i === splitUrl.length-1) {
                return true;
            }
        } else {
            if (splitPossibleUrl[i].indexOf(':') > -1) {
                if (i === splitUrl.length-1) {
                    return true;
                }
            } else {
                return false;
            }
        }
    }
}

                ¶

Checks if a dynamic route exists for the url

@param   (parsedRequest)     {Object}                The parsed request object
@return                      {String or Boolean}     Either the matching string, or false

function routeExists (parsedRequest) {
    const splitUrl    = _.compact(parsedRequest.pathname.split('/'));
    const possibleUrls = dynamicRoutes[parsedRequest.method][splitUrl.length];
    if (possibleUrls && possibleUrls.length > 0) {
        for (let i=0;i<possibleUrls.length;i++) {
            let possibleUrl = possibleUrls[i];
            if (urlMatchesRoute(splitUrl, possibleUrl)) {
                return possibleUrl;
            } else {
                if (i === possibleUrls.length -1) {
                    return false;
                }
            }
        }
    } else {
        return false;
    }
}

                ¶

Populates the req.params object with the parameters
from the parsed url

@param   (req)       {Object}    The http request object
@param   (pathname)  {String}    The pathname for the request
@param   (url)       {String}    The matched url

function populateParamsForRequest (req, pathname, url) {
    req.params = {};
    const splitPathname   = _.compact(pathname.split('/'));
    const splitUrl        = _.compact(url.split('/'));
    for (let i=0; i<splitUrl.length;i++) {
        if (splitUrl[i].indexOf(':') > -1) {
            req.params[splitUrl[i].replace(':','')] = splitPathname[i];
        }
    }
}

module.exports = {parseRoute, routeExists, populateParamsForRequest};


text:
//  Copyright 2020 Google Inc. All Rights Reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

namespace NtApiDotNet.Win32.Security.Authentication.Kerberos
{
#pragma warning disable 1591
    /// <summary>
    /// Kerberos Message Type.
    /// </summary>
    public enum KerberosMessageType
    {
        UNKNOWN = 0,
        KRB_AS_REQ  = 10,
        KRB_AS_REP  = 11,
        KRB_TGS_REQ = 12,
        KRB_TGS_REP = 13,
        KRB_AP_REQ = 14,
        KRB_AP_REP = 15,
        KRB_TGT_REQ = 16,
        KRB_TGT_REP = 17,
        KRB_SAFE = 20,
        KRB_PRIV = 21,
        KRB_CRED = 22,
        KRB_AS_REP_ENC_PART = 25,
        KRB_TGS_REP_ENC_PART = 26,
        KRB_PRIV_ENC_PART = 28,
        KRB_CRED_ENC_PART = 29,
        KRB_ERROR = 30,
    }
}


text:
@implementation PEFL10N
+ (NSString *)filesTitle
{
	return @"Files";
}
+ (NSString *)filesFooter
{
	return @"%i files";
}
+ (NSString *)bookmarksTitle
{
	return @"Bookmarks";
}
+ (NSString *)tableSelectTitle
{
	return @"Select Table";
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>

<project name="as3utils" basedir="./../" default="release">

	<property file="build/build.properties" />

	<taskdef resource="flexTasks.tasks" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" />

	<tstamp>
		<format property="BUILD.TIME" pattern="yyyy-MM-dd HH:mm:ss" />
	</tstamp>

	<target name="compile">
		<exec executable="${FLEX_HOME}/bin/acompc.bat" dir="." failonerror="true" failifexecutionfails="true">
			<arg value="-output" />
			<arg value="${release.dir}/lib/${project.name}.swc" />

			<arg value="-include-sources" />
			<arg value="${src.dir}" />

			<arg value="-metadata.creator" />
			<arg value="${user.name}" />

			<arg value="-metadata.title" />
			<arg value="as3utils" />

			<arg value="-metadata.date" />
			<arg value="${BUILD.TIME}" />

			<arg value="-compiler.optimize" />
			<arg value="-compiler.omit-trace-statements" />

			<arg value="-compiler.strict" />

			<arg value="-compiler.external-library-path" />
			<arg value="${FLEX_HOME}/frameworks/libs" />

			<arg value="-compiler.external-library-path" />
			<arg value="${FLEX_HOME}/frameworks/libs/air" />

			<arg value="-compiler.external-library-path" />
			<arg value="${FLEX_HOME}/frameworks/locale/{locale}" />
		</exec>
	</target>

	<target name="clean">
		<delete dir="${release.dir}" />
		<mkdir dir="${release.dir}" />
		<mkdir dir="${report.dir}" />
	</target>

	<target name="asdocs">
		<exec executable="${FLEX_HOME}/bin/aasdoc.bat" dir="." failonerror="true" failifexecutionfails="true">
			<arg value="-doc-sources"/>
			<arg value="${src.dir}" />

			<arg value="-package-description-file" />
			<arg value="build/packageDescription.xml" />

			<arg value="-source-path" />
			<arg value="${src.dir}" />

			<arg line="-output" />
			<arg value="${release.dir}/docs" />

			<arg line="-window-title" />
			<arg value="${project.name}" />

			<arg line="-metadata.contributor" />
			<arg value="Sandeep Gupta" />

			<arg line="-footer" />
			<arg value="© 2011-2012, Sandeep Gupta" />
		</exec>
	</target>

	<target name="compileTests">
		<mxmlc file="${test.src.dir}/${test.application.name}.mxml" output="${release.dir}/${test.application.name}.swf">
			<load-config filename="${FLEX_HOME}/frameworks/air-config.xml" />

			<source-path path-element="${src.dir}" />
			<source-path path-element="${test.src.dir}" />

			<!-- The TestRunner needs the flexunit libraries in the build/libs folder -->
			<library-path dir="${build.libs.dir}" append="true">
				<include name="*.swc" />
			</library-path>

			<!-- Sets java.awt.headless=true so font compilation works in headless environments -->
			<compiler.headless-server>true</compiler.headless-server>
		</mxmlc>
	</target>

	<target name="runTests">
		<!-- Run FlexUnit Ant Task to execute the unit tests and capture reporting data -->
		<taskdef resource="flexUnitTasks.tasks" classpath="${build.libs.dir}/flexUnitTasks-4.0.0.jar" />
		<flexunit swf="${release.dir}/${test.application.name}.swf" toDir="${report.dir}" haltonfailure="false" verbose="false" localTrusted="false" player="air" />

		<!-- Generate html JUnit-style reports based on test results -->
		<junitreport todir="${report.dir}">
			<fileset dir="${report.dir}">
				<include name="TEST-*.xml" />
			</fileset>
			<report format="frames" todir="${report.html.dir}" />
		</junitreport>
	</target>

	<target name="test" depends="compileTests, runTests" />

	<target name="build" depends="clean, test, compile, asdocs" />

	<target name="release" depends="build" description="Build and release the latest version of the library">
		<!-- clean previous library -->
		<delete file="${project.name}-${build.version}.zip" />

		<!-- clean the staging folder -->
		<delete file="${release.dir}/UnitTest.swf" />
		<delete file="${release.dir}/flexUnitDescriptor.xml" />
		<delete dir="${release.dir}/reports" />

		<!-- copy stuff to staging folder -->
		<copy todir="${release.dir}/src">
			<fileset dir="${src.dir}" />
		</copy>

		<copy todir="${release.dir}/tests">
			<fileset dir="${test.src.dir}" />
		</copy>

		<copy todir="${release.dir}">
			<fileset file="LICENSE" />
			<fileset file="README.md" />
		</copy>

		<!-- package the ZIP file -->
		<zip destfile="${project.name}-${build.version}.zip">
			<fileset dir="${release.dir}" defaultexcludes="false"/>
		</zip>
	</target>

</project>


text:
package com.spotify.helios.serviceregistration;

import static java.util.Arrays.asList;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import org.slf4j.Logger;

/**
 * Helpers for loading {@link ServiceRegistrarFactory} instances.
 */
public class ServiceRegistrarLoader {

  private static final List<Package> PROVIDED = asList(Logger.class.getPackage(),
                                                       ServiceRegistrarLoader.class.getPackage());

  private static final ClassLoader CURRENT = ServiceRegistrarLoader.class.getClassLoader();

  /**
   * Load a {@link ServiceRegistrarFactory} using the current class loader.
   *
   * @return A {@link ServiceRegistrarFactory}, null if none could be found.
   * @throws ServiceRegistrarLoadingException if loading failed.
   */
  public static ServiceRegistrarFactory load() throws ServiceRegistrarLoadingException {
    return load("classpath", CURRENT);
  }

  /**
   * Load a {@link ServiceRegistrarFactory} from a plugin jar file with a parent class loader that
   * will not load classes from the jvm classpath. Any dependencies of the plugin must be included
   * in the plugin jar.
   *
   * @param plugin The plugin jar file to load.
   * @return A {@link ServiceRegistrarFactory}, null if none could be found.
   * @throws ServiceRegistrarLoadingException if loading failed.
   */
  public static ServiceRegistrarFactory load(final Path plugin)
      throws ServiceRegistrarLoadingException {
    return load(plugin, CURRENT, extensionClassLoader(CURRENT));
  }

  /**
   * Load a {@link ServiceRegistrarFactory} from a plugin jar file with a specified parent class
   * loader and a list of exposed classes.
   *
   * @param plugin      The plugin jar file to load.
   * @param environment The class loader to use for providing plugin interface dependencies.
   * @param parent      The parent class loader to assign to the class loader of the jar.
   * @return A {@link ServiceRegistrarFactory}, null if none could be found.
   * @throws ServiceRegistrarLoadingException if loading failed.
   */
  public static ServiceRegistrarFactory load(final Path plugin,
                                             final ClassLoader environment,
                                             final ClassLoader parent)
      throws ServiceRegistrarLoadingException {
    return load("plugin jar file: " + plugin, pluginClassLoader(plugin, environment, parent));
  }

  /**
   * Load a {@link ServiceRegistrarFactory} using a class loader.
   *
   * @param source      The source of the class loader.
   * @param classLoader The class loader to load from.
   * @return A {@link ServiceRegistrarFactory}, null if none could be found.
   * @throws ServiceRegistrarLoadingException if loading failed.
   */
  public static ServiceRegistrarFactory load(final String source, final ClassLoader classLoader)
      throws ServiceRegistrarLoadingException {
    final ServiceLoader<ServiceRegistrarFactory> loader;
    try {
      loader = ServiceLoader.load(ServiceRegistrarFactory.class, classLoader);
    } catch (ServiceConfigurationError e) {
      throw new ServiceRegistrarLoadingException(
          "Failed to load service registrar from " + source, e);
    }
    final Iterator<ServiceRegistrarFactory> iterator = loader.iterator();
    if (iterator.hasNext()) {
      return iterator.next();
    } else {
      return null;
    }
  }

  /**
   * Attempt to get the extension class loader, which can only load jdk classes and classes from
   * jvm
   * extensions. Adapted from {@link ServiceLoader#loadInstalled(Class)}
   */
  private static ClassLoader extensionClassLoader(final ClassLoader environment) {
    ClassLoader cl = environment;
    ClassLoader prev = null;
    while (cl != null) {
      prev = cl;
      cl = cl.getParent();
    }
    return prev;
  }

  /**
   * Create a class loader for a plugin jar.
   */
  private static ClassLoader pluginClassLoader(final Path plugin,
                                               final ClassLoader environment,
                                               final ClassLoader parent) {
    final URL url;
    try {
      url = plugin.toFile().toURI().toURL();
    } catch (MalformedURLException e) {
      throw new RuntimeException("Failed to load plugin jar " + plugin, e);
    }
    final ClassLoader providedClassLoader = new FilteringClassLoader(PROVIDED, environment, parent);
    return new URLClassLoader(new URL[]{url}, providedClassLoader);
  }

  /**
   * A class loader that exposes a specific list of packages from another class loader.
   */
  private static class FilteringClassLoader extends ClassLoader {

    private final List<Package> packages;
    private final ClassLoader environment;

    public FilteringClassLoader(final List<Package> packages,
                                final ClassLoader environment,
                                final ClassLoader parent) {
      super(parent);
      this.packages = packages;
      this.environment = environment;
    }

    @Override
    protected Class<?> findClass(final String name) throws ClassNotFoundException {
      for (final Package pkg : packages) {
        if (name.startsWith(pkg.getName())) {
          return environment.loadClass(name);
        }
      }
      return super.findClass(name);
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace MyHealth.Client.HealthCloudAPI
{
    class HeartData : IHealthData<HeartInfo>
    {
        [JsonProperty("nextPage")]
        public string NextPage { get; set; }
        [JsonProperty("summaries")]
        public List<HeartInfo> Summaries { get; set; }
    }
}


text:
import os
import csv
import argparse
import tempfile
import time
from collections import namedtuple
import itertools
#
import numpy
#
import crosscat.utils.data_utils as du
import crosscat.utils.file_utils as fu
import crosscat.utils.hadoop_utils as hu
import crosscat.utils.xnet_utils as xu
import crosscat.LocalEngine as LE
import crosscat.HadoopEngine as HE
import crosscat.settings as S
import crosscat.cython_code.State as State
import parse_timing

def generate_hadoop_dicts(which_kernels, timing_run_parameters, args_dict):
    for which_kernel in which_kernels:
        kernel_list = (which_kernel, )
        dict_to_write = dict(timing_run_parameters)
        dict_to_write.update(args_dict)
        # must write kernel_list after update
        dict_to_write['kernel_list'] = kernel_list
        yield dict_to_write

def write_hadoop_input(input_filename, timing_run_parameters, n_steps, SEED):
    # prep settings dictionary
    time_analyze_args_dict = xu.default_analyze_args_dict
    time_analyze_args_dict['command'] = 'time_analyze'
    time_analyze_args_dict['SEED'] = SEED
    time_analyze_args_dict['n_steps'] = n_steps
    # one kernel per line
    all_kernels = State.transition_name_to_method_name_and_args.keys()
    with open(input_filename, 'a') as out_fh:
        dict_generator = generate_hadoop_dicts(all_kernels,timing_run_parameters, time_analyze_args_dict)
        for dict_to_write in dict_generator:
            xu.write_hadoop_line(out_fh, key=dict_to_write['SEED'], dict_to_write=dict_to_write)

def find_regression_coeff(filename, parameter_list, regression_file='daily_regression_coeffs.csv'):

    # Find regression coefficients from the times stored in the parsed csv files
    num_cols = 20
    # Read the csv file
    with open(filename) as fh:
        csv_reader = csv.reader(fh)
        header = csv_reader.next()[:num_cols]
        timing_rows = [row[:num_cols] for row in csv_reader]

    num_rows_list = parameter_list[0]
    num_cols_list = parameter_list[1]
    num_clusters_list = parameter_list[2]
    num_views_list = parameter_list[3]

    # Compute regression coefficients over all kernels
    all_kernels = State.transition_name_to_method_name_and_args.keys()

    with open(regression_file, 'a') as outfile:
         csvwriter=csv.writer(outfile,delimiter=',')

         for kernelindx in range(len(all_kernels)):
             curr_kernel = all_kernels[kernelindx]
             curr_timing_rows = [timing_rows[tmp] for tmp in range(len(timing_rows)) if timing_rows[tmp][5] == curr_kernel]
             # Iterate over the parameter values and finding matching indices in the timing data
             take_product_of = [num_rows_list, num_cols_list, num_clusters_list, num_views_list]
             count = -1
             a_list = []
             b_list = []
             #a_matrix = numpy.ones((len(num_rows_list)*len(num_cols_list)*len(num_clusters_list)*len(num_views_list), 5))
             #b_matrix = numpy.zeros((len(num_rows_list)*len(num_cols_list)*len(num_clusters_list)*len(num_views_list), 1))

             times_only = numpy.asarray([float(curr_timing_rows[i][4]) for i in range(len(curr_timing_rows))])

             for num_rows, num_cols, num_clusters, num_views in itertools.product(*take_product_of):
                 matchlist = [i for i in range(len(curr_timing_rows)) if curr_timing_rows[i][0] == str(num_rows) and \
                                  curr_timing_rows[i][1]== str(num_cols) and \
                                  curr_timing_rows[i][2]== str(num_clusters) and \
                                  curr_timing_rows[i][3]== str(num_views)]
                 if matchlist != []:
                     for matchindx in range(len(matchlist)):
                         a_list.append([1, num_rows, num_cols*num_clusters, num_rows*num_cols*num_clusters, num_views*num_rows*num_cols])
                         b_list.append(times_only[matchlist[matchindx]])

             a_matrix = numpy.asarray(a_list)
             b_matrix = numpy.asarray(b_list)

             x, j1, j2, j3 = numpy.linalg.lstsq(a_matrix,b_matrix)
             csvwriter.writerow([time.ctime(), curr_kernel, x[0], x[1], x[2], x[3], x[4]])

if __name__ == '__main__':
    default_num_rows_list = [100, 400, 1000, 4000, 10000]
    default_num_cols_list = [4, 8, 16, 24, 32]
    default_num_clusters_list = [10, 20, 40, 50]
    default_num_splits_list = [2, 3, 4]
    #
    parser = argparse.ArgumentParser()
    parser.add_argument('--gen_seed', type=int, default=0)
    parser.add_argument('--n_steps', type=int, default=10)
    parser.add_argument('--which_engine_binary', type=str,
            default=S.Hadoop.default_engine_binary)
    parser.add_argument('-do_local', action='store_true')
    parser.add_argument('-do_remote', action='store_true')
    parser.add_argument('--num_rows_list', type=int, nargs='*',
            default=default_num_rows_list)
    parser.add_argument('--num_cols_list', type=int, nargs='*',
            default=default_num_cols_list)
    parser.add_argument('--num_clusters_list', type=int, nargs='*',
            default=default_num_clusters_list)
    parser.add_argument('--num_splits_list', type=int, nargs='*',
            default=default_num_splits_list)
    #
    args = parser.parse_args()
    gen_seed = args.gen_seed
    n_steps = args.n_steps
    do_local = args.do_local
    do_remote = args.do_remote
    num_rows_list = args.num_rows_list
    num_cols_list = args.num_cols_list
    num_clusters_list = args.num_clusters_list
    num_splits_list = args.num_splits_list
    which_engine_binary = args.which_engine_binary
    #
    print 'using num_rows_list: %s' % num_rows_list
    print 'using num_cols_list: %s' % num_cols_list
    print 'using num_clusters_list: %s' % num_clusters_list
    print 'using num_splits_list: %s' % num_splits_list
    print 'using engine_binary: %s' % which_engine_binary
    time.sleep(2)

    script_filename = 'hadoop_line_processor.py'
    # some hadoop processing related settings
    dirname = 'runtime_analysis'
    fu.ensure_dir(dirname)
    temp_dir = tempfile.mkdtemp(prefix='runtime_analysis_',
                                dir=dirname)
    print 'using dir: %s' % temp_dir
    #
    table_data_filename = os.path.join(temp_dir, 'table_data.pkl.gz')
    input_filename = os.path.join(temp_dir, 'hadoop_input')
    output_filename = os.path.join(temp_dir, 'hadoop_output')
    output_path = os.path.join(temp_dir, 'output')
    parsed_out_file = os.path.join(temp_dir, 'parsed_output.csv')

    # Hard code the parameter values for now

    parameter_list = [num_rows_list, num_cols_list, num_clusters_list, num_splits_list]

    # Iterate over the parameter values and write each run as a line in the hadoop_input file
    take_product_of = [num_rows_list, num_cols_list, num_clusters_list, num_splits_list]
    for num_rows, num_cols, num_clusters, num_splits \
            in itertools.product(*take_product_of):
        if numpy.mod(num_rows, num_clusters) == 0 and numpy.mod(num_cols,num_splits)==0:
          timing_run_parameters = dict(num_rows=num_rows, num_cols=num_cols, num_views=num_splits, num_clusters=num_clusters)
          write_hadoop_input(input_filename, timing_run_parameters,  n_steps, SEED=gen_seed)

    n_tasks = len(num_rows_list)*len(num_cols_list)*len(num_clusters_list)*len(num_splits_list)*5
    # Create a dummy table data file
    table_data=dict(T=[],M_c=[],X_L=[],X_D=[])
    fu.pickle(table_data, table_data_filename)

    if do_local:
        xu.run_script_local(input_filename, script_filename, output_filename, table_data_filename)
        print 'Local Engine for automated timing runs has not been completely implemented/tested'
    elif do_remote:
        hadoop_engine = HE.HadoopEngine(which_engine_binary=which_engine_binary,
                output_path=output_path,
                input_filename=input_filename,
                table_data_filename=table_data_filename)
        xu.write_support_files(table_data, hadoop_engine.table_data_filename,
                              dict(command='time_analyze'), hadoop_engine.command_dict_filename)
        hadoop_engine.send_hadoop_command(n_tasks=n_tasks)
        was_successful = hadoop_engine.get_hadoop_results()
        if was_successful:
            hu.copy_hadoop_output(hadoop_engine.output_path, output_filename)
            parse_timing.parse_timing_to_csv(output_filename, outfile=parsed_out_file)
            coeff_list = find_regression_coeff(parsed_out_file, parameter_list)

        else:
            print 'remote hadoop job NOT successful'
    else:
        # print what the command would be
        hadoop_engine = HE.HadoopEngine(which_engine_binary=which_engine_binary,
                output_path=output_path,
                input_filename=input_filename,
                table_data_filename=table_data_filename)
        cmd_str = hu.create_hadoop_cmd_str(
                hadoop_engine.hdfs_uri, hadoop_engine.hdfs_dir, hadoop_engine.jobtracker_uri,
                hadoop_engine.which_engine_binary, hadoop_engine.which_hadoop_binary,
                hadoop_engine.which_hadoop_jar,
                hadoop_engine.input_filename, hadoop_engine.table_data_filename,
                hadoop_engine.command_dict_filename, hadoop_engine.output_path,
                n_tasks, hadoop_engine.one_map_task_per_line)
        print cmd_str


text: export { PressureFilled20 as default } from "../../";


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    android:id="@+id/TypCard"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:layout_marginTop="4dp"
    android:background="?android:attr/selectableItemBackground"
    android:elevation="2dp"
    android:paddingLeft="4dp"
    android:paddingRight="4dp"
    app:cardUseCompatPadding="true"
    android:foreground="?attr/selectableItemBackground"
    card_view:cardCornerRadius="2dp"
    tools:showIn="@layout/main_launcher2"
    card_view:cardElevation="2sp"
    card_view:cardPreventCornerOverlap="true"
    style="?attr/cardStyle">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="4dp">

        <View
            android:id="@+id/StaticTileLine"
            android:layout_width="fill_parent"
            android:layout_height="1dip"
            android:background="@color/std_green"/>

        <TextView
            android:id="@+id/TextViewTypicalsTitle"
            style="@style/CodeFontMain"
            android:layout_width="match_parent"
            android:layout_marginLeft="5dip"
            android:gravity="center"
            android:text="@string/position"
            android:textAllCaps="true"
            android:transitionName="ToolbarText"/>

        <RelativeLayout

            android:layout_width="wrap_content"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/card_thumbnail_image2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="8dp"
                android:paddingRight="4dp"
                android:paddingTop="4dp"
                android:transitionName="MyTransition"/>

            <RelativeLayout
                android:id="@+id/relCont"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toRightOf="@id/card_thumbnail_image2"
                android:paddingLeft="4dp"
                android:paddingRight="8dp">

                <TextView
                    android:id="@+id/TextViewInfoNodo1"
                    android:ellipsize="marquee"
                    style="@style/CodeFontMain"
                    android:textIsSelectable="false"
                    tools:text="ON"
                    android:singleLine="true"/>

                <View
                    android:id="@+id/PositionWarnLine"
                    android:layout_width="fill_parent"
                    android:layout_height="1dip"
                    android:layout_below="@id/TextViewInfoNodo1"
                    android:background="@color/std_green"/>
                <TextView
                    android:id="@+id/TextViewInfoNodo2"
                    style="@style/CodeFontMain"
                    android:layout_below="@id/TextViewInfoNodo1"
                    android:layout_marginLeft="2dp"
                    android:textIsSelectable="false"
                    tools:text="Info String, not so long"/>

            </RelativeLayout>
        </RelativeLayout>

    </LinearLayout>
</androidx.cardview.widget.CardView>


text:
"""Config flow for Airzone."""
from __future__ import annotations

from typing import Any

from aioairzone.common import ConnectionOptions
from aioairzone.exceptions import InvalidHost
from aioairzone.localapi_device import AirzoneLocalApi
from aiohttp.client_exceptions import ClientConnectorError
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import aiohttp_client

from .const import DEFAULT_LOCAL_API_PORT, DOMAIN

class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle config flow for an Airzone device."""

    async def async_step_user(
        self, user_input: dict[str, Any] | None = None
    ) -> FlowResult:
        """Handle the initial step."""
        errors = {}

        if user_input is not None:
            self._async_abort_entries_match(
                {
                    CONF_HOST: user_input[CONF_HOST],
                    CONF_PORT: user_input[CONF_PORT],
                }
            )

            airzone = AirzoneLocalApi(
                aiohttp_client.async_get_clientsession(self.hass),
                ConnectionOptions(
                    user_input[CONF_HOST],
                    user_input[CONF_PORT],
                ),
            )

            try:
                await airzone.validate_airzone()
            except (ClientConnectorError, InvalidHost):
                errors["base"] = "cannot_connect"
            else:
                title = f"Airzone {user_input[CONF_HOST]}:{user_input[CONF_PORT]}"
                return self.async_create_entry(title=title, data=user_input)

        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema(
                {
                    vol.Required(CONF_HOST): str,
                    vol.Required(CONF_PORT, default=DEFAULT_LOCAL_API_PORT): int,
                }
            ),
            errors=errors,
        )


text:
%*******************************************************
% Declaration
%*******************************************************
\refstepcounter{dummy}
%\pdfbookmark[0]{Declaration}{declaration}
\chapter*{}
\thispagestyle{empty}
D. \textbf{\myProf}, Profesor del \myDepartment de la Universidad de Granada.

\vspace{0.5cm}

\textbf{Informa:}

\vspace{0.5cm}

Que el presente trabajo, titulado \textit{\textbf{\myTitle}}, ha sido realizado bajo su supervisión por \textbf{\myName}, y autorizo la defensa de dicho trabajo ante el tribunal que corresponda.

\vspace{0.5cm}

Y para que conste, expido y firmo el presente informe en Granada a 8 de julio de 2016.

\vspace{3cm}

\begin{flushright}
    \begin{tabular}{m{5cm}}
        % TODO: poner firma real
        \centering\includegraphics[scale=1]{Graficos/firma_Pascual.png} \\
        % \\ \hline
        \centering\myProf \\
    \end{tabular}
\end{flushright}


text:
	#define dprint(expression) Serial.print("# "); Serial.print( #expression ); Serial.print( ": " ); Serial.println( expression )
	#define dshow(expression) Serial.println( expression )
#else
	#define dprint(expression)
	#define dshow(expression)
#endif

// Defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

//-----------------------------------------------------------------------------
// Global Constants
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Function Prototypes
//-----------------------------------------------------------------------------
void initPins(void);
void initADC(void);
//void initAnalogComparator(void);

void startADC( void );
void stopADC( void );
//void startAnalogComparator( void );
//void stopAnalogComparator( void );

void setADCPrescaler( uint8_t prescaler );
void setVoltageReference( uint8_t reference );
//void setTriggerEvent( uint8_t event );

void error (void);
// Fills the given buffer with bufferSize chars from a Serial object
void fillBuffer( \
	char *buffer, \
	byte bufferSize, \
  //fix//HardwareSerial::HardwareSerial* serial = &Serial );
  HardwareSerial* serial = &Serial );
void printStatus(void);

//-----------------------------------------------------------------------------
// Global Variables
//-----------------------------------------------------------------------------
extern volatile  boolean wait;
extern          uint16_t waitDuration;
extern volatile uint16_t stopIndex;
extern volatile uint16_t ADCCounter;
extern volatile  uint8_t ADCBuffer[ADCBUFFERSIZE];
extern volatile  boolean freeze;

extern           uint8_t prescaler;
//extern           uint8_t triggerEvent;
//extern           uint8_t threshold;

extern              char commandBuffer[COMBUFFERSIZE+1];


text:
package com.jetbrains.python.validation;

import com.jetbrains.python.psi.PyElementVisitor;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.psi.PsiElement;

/**
 * @author yole
 */
public abstract class PyAnnotator extends PyElementVisitor {
  private AnnotationHolder _holder;

  public AnnotationHolder getHolder() {
    return _holder;
  }

  public void setHolder(AnnotationHolder holder) {
    _holder = holder;
  }

  public synchronized void annotateElement(final PsiElement psiElement, final AnnotationHolder holder) {
    setHolder(holder);
    try {
      psiElement.accept(this);
    }
    finally {
      setHolder(null);
    }
  }

  protected void markError(PsiElement element, String message) {
    getHolder().createErrorAnnotation(element, message);
  }
}


text: int ProcessLine(char *line, char *searchPattern);


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using Autofac;
using Module = Autofac.Module;

namespace Kekiri.IoC.Autofac
{
    public class AutofacBootstrapper
    {
        public static void Initialize(Action<CustomizeBehaviorApi> customize = null)
        {
            var api = new CustomizeBehaviorApi();
            customize?.Invoke(api);

            ScenarioBase.ContainerFactory = () => new AutofacContainer(api);
        }
    }

    public class CustomizeBehaviorApi
    {
        public CustomizeBehaviorApi WithModules(params Module[] modules)
        {
            Modules.AddRange(modules);
            return this;
        }

        /// <summary>
        /// Can be used to customize container creation.  If used, <see cref="Modules"/> is ignored, the implementer can provide modules themselves.
        /// </summary>
        public Func<Assembly[], IContainer> BuildContainer;

        /// <summary>
        /// Can be used to inject modules.  Ignored if <see cref="BuildContainer"/> is used.
        /// </summary>
        public List<Module> Modules { get; } = new List<Module>();

        /// <summary>
        /// Can be used to blacklist certain assemblies (to avoid scanning them for auto-registration)
        /// </summary>
        public Func<string, bool> CheckBlacklistedAssembly;

        public bool IsBlacklistedAssembly(string assembly)
        {
            return CheckBlacklistedAssembly != null && CheckBlacklistedAssembly(assembly);
        }
    }
}


text:
/**
 * External dependencies
 */
import { parseToRgb } from 'polished';

/**
 * Internal dependencies
 */
import createSolid from './createSolid';

function createSolidFromString(str: string) {
  const rgb = parseToRgb(str);
  const { red, green, blue } = rgb;
  const alpha = 'alpha' in rgb ? rgb.alpha : undefined;
  return createSolid(red, green, blue, alpha);
}

export default createSolidFromString;


text:
/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */
package net.sourceforge.pmd.lang.rule.properties;

import java.util.Map;

import net.sourceforge.pmd.PropertyDescriptorFactory;
import net.sourceforge.pmd.lang.rule.properties.factories.BasicPropertyDescriptorFactory;

/**
 * Defines a datatype that supports single String values.
 *
 * @author Brian Remedios
 */
public class StringProperty extends AbstractProperty<String> {

	public static final PropertyDescriptorFactory FACTORY = new BasicPropertyDescriptorFactory<StringProperty>(String.class) {

		public StringProperty createWith(Map<String, String> valuesById) {
			return new StringProperty(
					nameIn(valuesById),
					descriptionIn(valuesById),
					defaultValueIn(valuesById),
					0f);
		}
	};

	/**
	 * Constructor for StringProperty.
	 * @param theName String
	 * @param theDescription String
	 * @param theDefaultValue String
	 * @param theUIOrder float
	 */
	public StringProperty(String theName, String theDescription, String theDefaultValue, float theUIOrder) {
		super(theName, theDescription, theDefaultValue, theUIOrder);
	}

    /**
     * @return String
     */
    protected String defaultAsString() {
        return defaultValue();
    }

	/**
	 *
	 * @return Class
	 * @see net.sourceforge.pmd.PropertyDescriptor#type()
	 */
	public Class<String> type() {
		return String.class;
	}

	/**
	 *
	 * @param valueString String
	 * @return Object
	 * @see net.sourceforge.pmd.PropertyDescriptor#valueFrom(String)
	 */
	public String valueFrom(String valueString) {
		return valueString;
	}
}


text:
/**
 * Author:  Kuba Weimann
 * Contact: kuba.weimann@gmail.com
 */

package pattern

import java.util
import java.util.Map.Entry

import akka.actor.{Props, Terminated, Actor, ActorRef}
import pattern.WorkDispatcher.Protocol.{RemoveWorkers, Failure, Success, AddWorkers}
import pattern.WorkDispatcher.{WorkFailure, WorkSuccess, WorkDone, WorkerTemplate}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

/**
 * Master-Worker pattern with a cache where completed jobs are stored. Its maximal size can be set using
 * cacheSize. Newly submitted jobs are stored in a hash map and a queue. If at a later time a job
 * will be submitted that has already been put into the hash map, its sender will be added to the list of
 * actors waiting for this job to complete. The amount of workers can be adjusted during runtime by sending
 * appropriate messages (see pattern.WorkDispatcher.Protocol). Finally there is a possibility to control what
 * happens after a worker dies by overriding pattern.WorkDispatcher's onWorkerTerminated() function.
 *
 * @param createWorker function to create workers. Takes work dispatcher as parameter.
 * @param initialWorkersCount how many workers will be spawned when work dispatcher is created.
 * @param cacheSize maximal size of cache.
 * @tparam A work type
 * @tparam B result type
 */
class WorkDispatcher[A,B](val createWorker: ActorRef => WorkerTemplate[A,B],
                          val initialWorkersCount: Int,
                          val cacheSize: Int) extends Actor {

  // worker -> work
  private val workers = mutable.Map[ActorRef, Option[A]]()
  // work
  private val workQ = mutable.Queue[A]()
  // work -> list of listeners
  private val workMap = mutable.HashMap[A, ListBuffer[ActorRef]]()

  private val cache = new util.LinkedHashMap[A, B](cacheSize, 0.75f, true) {
    override protected def removeEldestEntry(eldest: Entry[A, B]): Boolean = {
      size >= cacheSize
    }
  }

  private var workerId = initialWorkersCount
  private var workersToRemove = 0

  for (i <- 1 to initialWorkersCount) workers += worker(i) -> None

  def onWorkerTerminated(): Unit = {}

  final def receive: Receive = {

    case workDone: WorkDone =>
      val worker = workDone.worker

      workers.get(worker) match {
        // worker belonged to this dispatcher
        case Some(workOption) =>
          // if worker belonged to this dispatcher and sent WorkDone we can assume he had a work to do
          val work = workOption.get
          val listeners = workMap.get(work).get

          val result = workDone match {
            case WorkSuccess(_, reslt: B) =>
              cache.put(work, reslt)
              Success(work, reslt)
            case WorkFailure(_, reason) =>
              Failure(work, reason)
          }

          listeners foreach (_ ! result)
          // remove this work from submitted works
          workMap -= work
          workers.update(worker, None)

          if (workersToRemove > 0) {
            workers -= context.unwatch(worker)
            workersToRemove -= 1
          } else {
            // if there is work to do
            if (workQ.nonEmpty) {
              findWork(worker)
            }
          }

        case _ =>
      }

    case Terminated(worker) =>
      // if the worker belonged to this dispatcher
      workers.get(worker) match {
        // if he was working
        case Some(workOption) if workOption.nonEmpty =>
          val work = workOption.get
          // make sure the listeners will get the results by enqueuing the work
          workQ.enqueue(work)

        case _ =>

      }

      // remove worker from the worker list
      workers -= context.unwatch(worker)
      onWorkerTerminated()

    case AddWorkers(count) =>
      for (i <- 1 to count) {
        val newWorker = worker(workerId + i)
        workers += newWorker -> None
        if (workQ.nonEmpty) {
          findWork(newWorker)
        }
      }
      workerId += count

    case RemoveWorkers(count) =>
      val idleWorkers = workers.filter(_._2.isEmpty).take(count)
      workers --= idleWorkers.keys
      idleWorkers.foreach(worker => context.stop(context.unwatch(worker._1)))
      workersToRemove += Math.max(0, count - idleWorkers.size)

    case work: A =>
      val cached = cache.get(work)

      // check if this work has already been cached
      if (cached != null) {
        sender ! Success(work, cached)
      } else {
        // check if the same work has been submitted
        workMap.get(work) match {
          case Some(listeners) =>
            // work has already been submitted, add listener
            listeners += sender()

          case _ =>
            // it's a new work
            val listeners = ListBuffer(sender())
            workMap += work -> listeners

            if (workQ.isEmpty) {
              // if workQ is empty it's very likely that there is an idle worker
              collectFirstIdleWorker() match {
                case Some(worker) =>
                  worker ! work
                  workers.update(worker, Some(work))
                case _ =>
                  // all workers are busy - add the work to the queue
                  workQ.enqueue(work)
              }
            } else {
              // if workQ is not empty it means that all workers are busy
              // so there is no reason to look for idle one
              workQ.enqueue(work)
            }
        }
      }
  }

  private def worker(i: Int): ActorRef = context.watch(context.actorOf(Props(createWorker(self)), name="Worker-"+i))

  private def collectFirstIdleWorker(): Option[ActorRef] = workers collectFirst {
    case (worker, None) =>
      worker
  }

  private def findWork(worker: ActorRef): Unit = {
    while (workQ.nonEmpty) {
      val work = workQ.dequeue()

      val cached = cache.get(work)

      if (cached != null) {
        // if workQ contains the work it means that workMap contains it as well
        val listeners = workMap.get(work).get
        val result = Success(work, cached)

        listeners foreach (_ ! result)
      } else {
        // work hasn't been done yet. Give it to the worker
        worker ! work
        workers.update(worker, Some(work))
        return
      }
    }
  }
}

object WorkDispatcher {
  private trait WorkDone { val worker: ActorRef }
  private case class WorkSuccess[A](worker: ActorRef, result: A) extends WorkDone
  private case class WorkFailure[A](worker: ActorRef, reason: Throwable) extends WorkDone

  object Protocol {
    // to master
    case class AddWorkers(count: Int)
    case class RemoveWorkers(count: Int)

    // from master
    case class Success[A,B](work: A, result: B)
    case class Failure[A](work: A, reason: Throwable)
  }

  /**
   * Template for implementing workers.
   * @param workDispatcher reference to the work dispatcher
   * @tparam A work type
   * @tparam B result type
   */
  abstract class WorkerTemplate[A,B](val workDispatcher: ActorRef) extends Actor {
    implicit val ec = context.dispatcher

    /**
     * @param work work to do
     * @return result of given work
     */
    def doWork(work: A): B

    final def receive: Receive = {
      case work: A =>
        try {
          val result = doWork(work)
          workDispatcher ! WorkSuccess(self, result)
        } catch {
          case e: Throwable =>
            workDispatcher ! WorkFailure(self, e)
        }
    }
  }
}


text:
package com.zhangjikai.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by ZhangJikai on 2016/10/21.
 */

@RestController
public class UploadController {
    @RequestMapping(value = "/getData", method = RequestMethod.GET, produces = "application/json;charset=utf8")
    @ResponseBody
    public String getData() {
        return "success";
    }
}


text:
Spectrum

Spectrum Middle

Circles

Spins

Spirals

Spirals Inverted

Rising Sun

Risen Sun

Tornado

Bouncing Balls

Flag

Eq


text:
<?php if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' ); ?>

<?php
$catcount = 1;
$count = count( $pathway );

// Remove the link on the last pathway item
$pathway[ $count - 1 ]->link = '';

foreach( $pathway as $item ) { ?>
	<?php if( !empty( $item->link ) ) : ?>
	<a class="pathway" href="<?php echo $item->link ?>"><?php echo $item->name ?>
	<?php else: ?>
	<?php echo $item->name ?>
	<?php endif; ?>

<?php

	if( $catcount < $count || $item->link != '') {
		// This prints the separator image (uses the one from the template if available!)
		// Cat1 * Cat2 * ...
		echo vmCommonHTML::pathway_separator();

	}
	$catcount++;
}
if( isset( $return_link ) && !empty( $return_link ) ) {
    echo $return_link;
}
 ?>


text:
package org.rapidoid.cache;

import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({METHOD})
@Retention(RUNTIME)
@Authors("Nikolche Mihajlovski")
@Since("5.3.0")
@Documented
public @interface Cached {

    long ttl();

}


text:
/**
  * Capitalizes the first letter of words in a string
  *
  * @param {string} string - String to be transformed
  *
  * @returns {string} transformed string
  */
export default function capitalizeFirstLetter(string) {
  return string.replace(/\b[a-z]/g, letter => letter.toUpperCase());
}


text:
#include "gki.h"
#include "bta_gattc_co.h"
#include "bta_gattc_ci.h"

#if( defined BLE_INCLUDED ) && (BLE_INCLUDED == TRUE)
#if( defined BTA_GATT_INCLUDED ) && (BTA_GATT_INCLUDED == TRUE)

/*****************************************************************************
**  Function Declarations
*****************************************************************************/

/*******************************************************************************
**
** Function         bta_gattc_co_cache_open
**
** Description      This callout function is executed by GATTC when a GATT server
**                  cache is ready to be sent.
**
** Parameter        server_bda: server bd address of this cache belongs to
**                  evt: call in event to be passed in when cache open is done.
**                  conn_id: connection ID of this cache operation attach to.
**                  to_save: open cache to save or to load.
**
** Returns          void.
**
*******************************************************************************/
void bta_gattc_co_cache_open(BD_ADDR server_bda, UINT16 evt, UINT16 conn_id, BOOLEAN to_save)
{
    tBTA_GATT_STATUS    status = BTA_GATT_OK;

    /* open NV cache and send call in */
    bta_gattc_ci_cache_open(server_bda, evt, status, conn_id);
}

/*******************************************************************************
**
** Function         bta_gattc_co_cache_load
**
** Description      This callout function is executed by GATT when server cache
**                  is required to load.
**
** Parameter        server_bda: server bd address of this cache belongs to
**                  evt: call in event to be passed in when cache save is done.
**                  num_attr: number of attribute to be save.
**                  attr_index: starting attribute index of the save operation.
**                  conn_id: connection ID of this cache operation attach to.
** Returns
**
*******************************************************************************/
void bta_gattc_co_cache_load(BD_ADDR server_bda, UINT16 evt, UINT16 start_index, UINT16 conn_id)
{
    UINT16              num_attr = 0;
    tBTA_GATTC_NV_ATTR  attr[BTA_GATTC_NV_LOAD_MAX];
    tBTA_GATT_STATUS    status = BTA_GATT_MORE;

    bta_gattc_ci_cache_load(server_bda, evt, num_attr, attr, status, conn_id);
}
/*******************************************************************************
**
** Function         bta_gattc_co_cache_save
**
** Description      This callout function is executed by GATT when a server cache
**                  is available to save.
**
** Parameter        server_bda: server bd address of this cache belongs to
**                  evt: call in event to be passed in when cache save is done.
**                  num_attr: number of attribute to be save.
**                  p_attr: pointer to the list of attributes to save.
**                  attr_index: starting attribute index of the save operation.
**                  conn_id: connection ID of this cache operation attach to.
** Returns
**
*******************************************************************************/
void bta_gattc_co_cache_save (BD_ADDR server_bda, UINT16 evt, UINT16 num_attr,
                              tBTA_GATTC_NV_ATTR *p_attr_list, UINT16 attr_index, UINT16 conn_id)
{
    tBTA_GATT_STATUS    status = BTA_GATT_OK;

    bta_gattc_ci_cache_save(server_bda, evt, status, conn_id);
}

/*******************************************************************************
**
** Function         bta_gattc_co_cache_close
**
** Description      This callout function is executed by GATTC when a GATT server
**                  cache is written completely.
**
** Parameter        server_bda: server bd address of this cache belongs to
**                  conn_id: connection ID of this cache operation attach to.
**
** Returns          void.
**
*******************************************************************************/
void bta_gattc_co_cache_close(BD_ADDR server_bda, UINT16 conn_id)
{
    /* close NV when server cache is done saving or loading,
       does not need to do anything for now on Insight */
}

/*******************************************************************************
**
** Function         bta_gattc_co_cache_reset
**
** Description      This callout function is executed by GATTC to reset cache in
**                  application
**
** Parameter        server_bda: server bd address of this cache belongs to
**
** Returns          void.
**
*******************************************************************************/
void bta_gattc_co_cache_reset(BD_ADDR server_bda)
{
}

#endif
#endif


text:
#pragma once

#include "orbitelements.h"

class Graph{
//This class holds information on a display window for graphs, and vectors for the projection angle of these
//orbit graphs, and current scaling
friend class OrbitElements;
public:
	enum Shape
	{
		Circle,
		Rectangle
	};

	void drawvectorline(Sketchpad *sketchpad, const VECTOR3 &line);//Draws vector line at current projection & scaling
	void drawplanet(Sketchpad *sketchpad, OBJHANDLE body); //Draw circle representing planet
	void drawatmosphere(Sketchpad *sketchpad, OBJHANDLE body); //Draw circle representing atmosphere
	void setprojection(const OrbitElements &torbit);//View set from orbit's plane vector
	void setprojection(const VECTOR3 &projection);// View set from vector
	void setprojection(const VECTOR3 &txaxis, const VECTOR3 &tyaxis, const VECTOR3 &tzaxis);//Explicitly set axes
	void drawvector(Sketchpad *sketchpad,const VECTOR3 &line1);//Draw vector using current projection & scale
	void drawmarker(Sketchpad *sketchpad, const VECTOR3 location, Shape shape);	// draws a marker at the specified location
	void drawtwovector(Sketchpad *sketchpad, const VECTOR3 &line1, const VECTOR3 &line2);//Draw two vectors using current projection & scaling
	void draworbit(const class OrbitElements &element, Sketchpad *sketchpad, bool drawradius);//Calls draworbit in orbitelements
	double vectorpointdisplay(Sketchpad *sketchpad, const VECTOR3 &target, MFD2 *mfd, VESSEL *vessel, bool isposition);//Nice little pointer utility
	void setviewscale(const class OrbitElements &orbit);//Set scale of picture using orbit size
	void setviewscale(double temp);//Set scale using a number
	void setviewscalesize(double temp);//Set scale using a distance size
	void setviewwindow(DWORD xstart, DWORD ystart, DWORD xend, DWORD yend);//Set a window within MFD
	void getviewwindow(DWORD *xstart, DWORD *ystart, DWORD *xend, DWORD *yend);//Get back above info
	double getviewscale();//Get viewscale number
private:
	void drawcircle(Sketchpad *sketchpad, double size); //Draw circle representing planet
	VECTOR3 xaxis, yaxis, zaxis; // projection vectors
	DWORD ixstart, iystart, ixend, iyend, windowsize;//window parameters
	double scale;//scaling factor for diagram
};