text:
"""A script to parse and pre-process the Parent Company Info for Facilities tracked by EPA."""

import os.path
import pathlib
import sys

import csv
import difflib
import json
import pandas as pd
import re

from absl import app
from absl import flags

# Allows the following module imports to work when running as a script
_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(_SCRIPT_PATH, "../.."))
from us_epa.util import facilities_helper as fh
from us_epa.parent_company import static_corrections as sc

flags.DEFINE_string("input_download_path", "tmp_data", "Input directory")
flags.DEFINE_string("existing_facilities_file", "existing_facilities",
                    "Filename for existing facilities ids")
flags.DEFINE_string("output_base_path", "output",
                    "Output directory for processed data.")

FLAGS = flags.FLAGS

# V_PARENT_COMPANY_INFO table
_TABLE_PREFIX = "D_GHG_B"
_TABLE = "V_PARENT_COMPANY_INFO"

_EPA_FACILITY_GHG_ID = "epaGhgrpFacilityId"

# Mapping which contains the company id duplicates.
_DUPLICATE_MAPPING = {}

def _str(v):
    if not v:
        return ''
    return '"' + v + '"'

def _str_matching_replace(s):
    s = s.replace('LLC', '')
    s = s.replace('Corp', '')
    s = s.replace('Inc', '')
    s = s.replace('LP', '')

    # Ends with "Co"
    s = re.sub('Co$', '', s)
    return s

def _add_to_duplicate_mapping(company_id_1, company_id_2, company_id_count):

    # If (company_id_1, company_id_2) exist already (in either direction),
    # then no point continuing.
    if ((company_id_1 in _DUPLICATE_MAPPING and
         company_id_2 == _DUPLICATE_MAPPING[company_id_1]) or
        (company_id_2 in _DUPLICATE_MAPPING and
         company_id_1 == _DUPLICATE_MAPPING[company_id_2])):

        return

    # Determine whether company_id_1 should point to company_id_2 or the other
    # way round.
    # The primary criteria is:
    #   1. The id with appears fewer times should be replaced.
    #   2. If they are tied on the occurences, then replace the shorter id.
    key = company_id_1
    val = company_id_2
    comp_count = company_id_count[company_id_2]

    if ((company_id_count[company_id_1] > comp_count) or
        ((company_id_count[company_id_1] == comp_count) and
         (len(company_id_1) >= len(company_id_2)))):
        key = company_id_2
        val = company_id_1
        comp_count = company_id_count[company_id_1]

    # A previous mapping might already exist for 'key'. If so, only update the
    # mapping if the company_id being pointed to occurs less frequently than the
    # the 'value'.
    existing_company = val
    existing_count = comp_count
    if key in _DUPLICATE_MAPPING:
        existing_company = _DUPLICATE_MAPPING[key]
        existing_count = company_id_count[existing_company]

    # Only update if the company_id being mapped to has a greater count than
    # the existing_count (for a different company id).
    if ((comp_count >= existing_count) or
        ((comp_count == existing_count) and
         (len(val) >= len(existing_company)))):
        _DUPLICATE_MAPPING[key] = val

def _add_static_duplicates(static_mappings, company_id_count):
    for k, v in static_mappings.items():
        if k not in company_id_count:
            company_id_count[k] = 0
        if v not in company_id_count:
            company_id_count[v] = 1

        _add_to_duplicate_mapping(k, v, company_id_count)

def _insert_overlaps(loc_map, company_id_count):
    count_dupe_loc = 0
    loc_id_contained_count = 0
    for a, v in loc_map.items():
        v = list(v)
        if len(v) > 1:
            count_dupe_loc += 1
            id_match_found = False

            id_pairs = {}
            for i in range(len(v)):
                for j in range(i + 1, len(v)):
                    # Determine the SequenceMatcher ratio between the two ids.
                    v_i = v[i]
                    v_j = v[j]
                    m1 = v_i.lower()
                    m2 = v_j.lower()
                    seq1 = difflib.SequenceMatcher(a=_str_matching_replace(m1),
                                                   b=_str_matching_replace(m2))
                    seq2 = difflib.SequenceMatcher(a=m1, b=m2)

                    diff_score = max(seq1.ratio(), seq2.ratio())
                    id_pairs.update({(v_i, v_j): diff_score})

                    # If the score is > 80%, then add the duplicate relationship
                    if (diff_score > 0.8):
                        id_match_found = True
                        _add_to_duplicate_mapping(v_i, v_j, company_id_count)

            if id_match_found:
                loc_id_contained_count += 1

    return (count_dupe_loc, loc_id_contained_count)

def _resolve_multiple_indirections():
    # For multiple re-directions, map the final replacement ID for each of the
    # IDs being replaced.
    for k, v in _DUPLICATE_MAPPING.items():
        v_loc = v
        while (1):
            if v_loc in _DUPLICATE_MAPPING.keys():
                v_loc = _DUPLICATE_MAPPING[v_loc]
            else:
                _DUPLICATE_MAPPING[k] = v_loc
                break

def preprocess(input_table_path, existing_facilities_file):
    # Get the existing facility ids in a set.
    existing_facilities_path = os.path.join(input_table_path,
                                            existing_facilities_file + ".csv")

    relevant_facility_ids = set(
        pd.read_csv(existing_facilities_path)[_EPA_FACILITY_GHG_ID].values)
    input_table = os.path.join(input_table_path, _TABLE + ".csv")

    unique_company_names = set()
    address_map = {}
    facility_map = {}

    unique_company_ids = set()
    company_id_count = {}
    num_rows_written = 0

    # Enter all static mappings.
    print("First inserting static mappings...")
    _add_static_duplicates(sc.company_id_mappings, company_id_count)

    print("Reading Table Info data...")
    with open(input_table, "r") as rfp:
        cr = csv.DictReader(rfp)
        for in_row in cr:
            facility_id = fh.v(_TABLE,
                               in_row,
                               "FACILITY_ID",
                               table_prefix=_TABLE_PREFIX)
            ghg_id = _EPA_FACILITY_GHG_ID + "/" + facility_id

            # Only proceed if the facility_id exists in Data Commons.
            if ghg_id not in relevant_facility_ids:
                continue

            company_name = fh.get_name(_TABLE,
                                       in_row,
                                       "PARENT_COMPANY_NAME",
                                       table_prefix=_TABLE_PREFIX)
            company_name = company_name.replace("\"", "").replace("'", "")
            if not company_name:
                continue
            unique_company_names.add(company_name)
            company_id = fh.name_to_id(company_name)

            address = _str(
                fh.get_address(_TABLE, in_row, table_prefix=_TABLE_PREFIX))

            # Populate the address_map and facility_map.
            if address not in address_map:
                address_map[address] = set()

            existing_ids = address_map[address]
            existing_ids.add(company_id)
            address_map.update({address: existing_ids})

            if facility_id not in facility_map:
                facility_map[facility_id] = set()
            existing_ids = facility_map[facility_id]
            existing_ids.add(company_id)
            facility_map.update({facility_id: existing_ids})

            unique_company_ids.add(company_id)

            # Count the number of occurences of the company_id.
            if company_id not in company_id_count:
                company_id_count[company_id] = 0
            company_id_count[company_id] += 1

    print("Determining Address duplicates...")
    (count_dupe_addr,
     address_id_contained_count) = _insert_overlaps(address_map,
                                                    company_id_count)
    print("Determining Facility duplicates...")
    (count_dupe_facility,
     facility_id_contained_count) = _insert_overlaps(facility_map,
                                                     company_id_count)

    print("Resolving duplicate indirections..")
    _resolve_multiple_indirections()

    # Write.
    print("Writing to file...")
    output_path = os.path.join(input_table_path, "DuplicateIdMappings.csv")
    with open(output_path, "w") as opth:
        writer = csv.DictWriter(opth, ["Id", "MappedTo", "Occurences"],
                                doublequote=False,
                                escapechar="\\")
        writer.writeheader()

        for k, v in dict(sorted(_DUPLICATE_MAPPING.items())).items():
            d = {"Id": k, "MappedTo": v, "Occurences": company_id_count[v]}
            writer.writerow(d)
            num_rows_written += 1

    # Print some statistics.
    print("****************")
    print("Num Rows Written = ", num_rows_written)
    print("Number records: ", len(pd.read_csv(existing_facilities_path)))
    print("Unique Facilities: ", len(relevant_facility_ids))
    print("Unique Company Names: ", len(unique_company_names))

    print("Duplicate Keys: ", len(_DUPLICATE_MAPPING))
    print("Unique (before) Company Ids: ", len(unique_company_ids))
    print("Unique (after) Company Ids: ",
          len(unique_company_ids) - len(_DUPLICATE_MAPPING))
    print("****************")
    print("duplicate address = ", count_dupe_addr)
    print("duplicate address, id match found = ", address_id_contained_count)
    print("duplicate facility = ", count_dupe_facility)
    print("duplicate facility, id match found = ", facility_id_contained_count)

def main(_):
    # Validate inputs.
    assert FLAGS.input_download_path
    assert FLAGS.existing_facilities_file
    assert os.path.exists(
        os.path.join(FLAGS.input_download_path,
                     FLAGS.existing_facilities_file + ".csv"))
    assert os.path.exists(
        os.path.join(FLAGS.input_download_path, _TABLE + ".csv"))

    preprocess(FLAGS.input_download_path, FLAGS.existing_facilities_file)

if __name__ == "__main__":
    app.run(main)


text:
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;

namespace Com.Aspose.Tasks.Model {
  public class ResourceItems {
    public List<ResourceItem> List { get; set; }

    public Link link { get; set; }

    public override string ToString()  {
      var sb = new StringBuilder();
      sb.Append("class ResourceItems {\n");
      sb.Append("  List: ").Append(List).Append("\n");
      sb.Append("  link: ").Append(link).Append("\n");
      sb.Append("}\n");
      return sb.ToString();
    }
  }
  }

redpajama_set_name: RedPajamaGithub


text:
from shorttext.utils import textpreprocessing as textpreprocess
from shorttext.generators import LatentTopicModeler, GensimTopicModeler, AutoencodingTopicModeler
from shorttext.generators import load_autoencoder_topicmodel, load_gensimtopicmodel

class TopicVecCosineDistanceClassifier:
    """
    This is a class that implements a classifier that perform classification based on
    the cosine similarity between the topic vectors of the user-input short texts and various classes.
    The topic vectors are calculated using :class:`LatentTopicModeler`.
    """
    def __init__(self, topicmodeler):
        """ Initialize the classifier.

        :param topicmodeler: topic modeler
        :type topicmodeler: LatentTopicModeler
        """
        self.topicmodeler = topicmodeler

    def score(self, shorttext):
        """ Calculate the score, which is the cosine similarity with the topic vector of the model,
        of the short text against each class labels.

        :param shorttext: short text
        :return: dictionary of scores of the text to all classes
        :type shorttext: str
        :rtype: dict
        """
        # scoredict = defaultdict(lambda : 0.0)
        # similarities = self.topicmodeler.matsim[self.topicmodeler.retrieve_corpus_topicdist(shorttext)]
        # for label, similarity in zip(self.topicmodeler.classlabels, similarities):
        #     scoredict[label] = similarity
        # return dict(scoredict)
        return self.topicmodeler.get_batch_cos_similarities(shorttext)

    def loadmodel(self, nameprefix):
        """ Load the topic model with the given prefix of the file paths.

        Given the prefix of the file paths, load the corresponding topic model. The files
        include a JSON (.json) file that specifies various parameters, a gensim dictionary (.gensimdict),
        and a topic model (.gensimmodel). If weighing is applied, load also the tf-idf model (.gensimtfidf).

        This is essentialing loading the topic modeler :class:`LatentTopicModeler`.

        :param nameprefix: prefix of the file paths
        :return: None
        :type nameprefix: str
        """
        self.topicmodeler.loadmodel(nameprefix)

    def savemodel(self, nameprefix):
        """ Save the model with names according to the prefix.

        Given the prefix of the file paths, save the corresponding topic model. The files
        include a JSON (.json) file that specifies various parameters, a gensim dictionary (.gensimdict),
        and a topic model (.gensimmodel). If weighing is applied, load also the tf-idf model (.gensimtfidf).

        If neither :func:`~train` nor :func:`~loadmodel` was run, it will raise `ModelNotTrainedException`.

        This is essentialing saving the topic modeler :class:`LatentTopicModeler`.

        :param nameprefix: prefix of the file paths
        :return: None
        :raise: ModelNotTrainedException
        :type nameprefix: str
        """
        self.topicmodeler.savemodel(nameprefix)

    def load_compact_model(self, name):
        self.topicmodeler.load_compact_model(name)

    def save_compact_model(self, name):
        self.topicmodeler.save_compact_model(name)

def train_gensimtopicvec_cosineClassifier(classdict,
                                          nb_topics,
                                          preprocessor=textpreprocess.standard_text_preprocessor_1(),
                                          algorithm='lda',
                                          toweigh=True,
                                          normalize=True,
                                          *args, **kwargs):
    """ Return a cosine distance classifier, i.e., :class:`TopicVecCosineDistanceClassifier`, while
    training a gensim topic model in between.

    :param classdict: training data
    :param nb_topics: number of latent topics
    :param preprocessor: function that preprocesses the text. (Default: `utils.textpreprocess.standard_text_preprocessor_1`)
    :param algorithm: algorithm for topic modeling. Options: lda, lsi, rp. (Default: lda)
    :param toweigh: whether to weigh the words using tf-idf. (Default: True)
    :param normalize: whether the retrieved topic vectors are normalized. (Default: True)
    :param args: arguments to pass to the `train` method for gensim topic models
    :param kwargs: arguments to pass to the `train` method for gensim topic models
    :return: a classifier that scores the short text based on the topic model
    :type classdict: dict
    :type nb_topics: int
    :type preprocessor: function
    :type algorithm: str
    :type toweigh: bool
    :type normalize: bool
    :rtype: TopicVecCosineDistanceClassifier
    """
    # train topic model
    topicmodeler = GensimTopicModeler(preprocessor=preprocessor,
                                      algorithm=algorithm,
                                      toweigh=toweigh,
                                      normalize=normalize)
    topicmodeler.train(classdict, nb_topics, *args, **kwargs)

    # cosine distance classifier
    return TopicVecCosineDistanceClassifier(topicmodeler)

def load_gensimtopicvec_cosineClassifier(name,
                                         preprocessor=textpreprocess.standard_text_preprocessor_1(),
                                         compact=True):
    """ Load a gensim topic model from files and return a cosine distance classifier.

    Given the prefix of the files of the topic model, return a cosine distance classifier
    based on this model, i.e., :class:`TopicVecCosineDistanceClassifier`.

    The files include a JSON (.json) file that specifies various parameters, a gensim dictionary (.gensimdict),
    and a topic model (.gensimmodel). If weighing is applied, load also the tf-idf model (.gensimtfidf).

    :param name: name (if compact=True) or prefix (if compact=False) of the file paths
    :param preprocessor: function that preprocesses the text. (Default: `utils.textpreprocess.standard_text_preprocessor_1`)
    :param compact: whether model file is compact (Default: True)
    :return: a classifier that scores the short text based on the topic model
    :type name: str
    :type preprocessor: function
    :type compact: bool
    :rtype: TopicVecCosineDistanceClassifier
    """
    topicmodeler = load_gensimtopicmodel(name, preprocessor=preprocessor, compact=compact)
    return TopicVecCosineDistanceClassifier(topicmodeler)

def train_autoencoder_cosineClassifier(classdict,
                                       nb_topics,
                                       preprocessor=textpreprocess.standard_text_preprocessor_1(),
                                       normalize=True,
                                       *args, **kwargs):
    """ Return a cosine distance classifier, i.e., :class:`TopicVecCosineDistanceClassifier`, while
    training an autoencoder as a topic model in between.

    :param classdict: training data
    :param nb_topics: number of topics, i.e., number of encoding dimensions
    :param preprocessor: function that preprocesses the text. (Default: `utils.textpreprocess.standard_text_preprocessor_1`)
    :param normalize: whether the retrieved topic vectors are normalized. (Default: True)
    :param args: arguments to be passed to keras model fitting
    :param kwargs: arguments to be passed to keras model fitting
    :return: a classifier that scores the short text based on the autoencoder
    :type classdict: dict
    :type nb_topics: int
    :type preprocessor: function
    :type normalize: bool
    :rtype: TopicVecCosineDistanceClassifier
    """
    # train the autoencoder
    autoencoder = AutoencodingTopicModeler(preprocessor=preprocessor, normalize=normalize)
    autoencoder.train(classdict, nb_topics, *args, **kwargs)

    # cosine distance classifier
    return TopicVecCosineDistanceClassifier(autoencoder)

def load_autoencoder_cosineClassifier(name,
                                      preprocessor=textpreprocess.standard_text_preprocessor_1(),
                                      compact=True):
    """ Load an autoencoder from files for topic modeling, and return a cosine classifier.

    Given the prefix of the file paths, load the model into files, with name given by the prefix.
    There are files with names ending with "_encoder.json" and "_encoder.h5", which are
    the JSON and HDF5 files for the encoder respectively.
    They also include a gensim dictionary (.gensimdict).

    :param name: name (if compact=True) or prefix (if compact=False) of the file paths
    :param preprocessor: function that preprocesses the text. (Default: `utils.textpreprocess.standard_text_preprocessor_1`)
    :param compact: whether model file is compact (Default: True)
    :return: a classifier that scores the short text based on the autoencoder
    :type name: str
    :type preprocessor: function
    :type compact: bool
    :rtype: TopicVecCosineDistanceClassifier
    """
    autoencoder = load_autoencoder_topicmodel(name, preprocessor=preprocessor, compact=compact)
    return TopicVecCosineDistanceClassifier(autoencoder)


text:
package com.tw.go.plugin.material.artifactrepository.deb;

import com.thoughtworks.go.plugin.api.annotation.Extension;
import com.thoughtworks.go.plugin.api.material.packagerepository.PackageMaterialProvider;
import com.tw.go.plugin.material.artifactrepository.deb.config.DebRepositoryConfiguration;
import com.tw.go.plugin.material.artifactrepository.deb.poller.DebRepositoryPoller;

public class DebArtifactRepositoryMaterial implements PackageMaterialProvider {

    public DebRepositoryConfiguration getConfig() {
        return new DebRepositoryConfiguration();
    }

    public DebRepositoryPoller getPoller() {
        return new DebRepositoryPoller();
    }
}


text:
package com.sandwish.site.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sandwish.site.dao.user.UserDao;
import com.sandwish.site.entity.User;
import com.sandwish.site.service.dao.UserService;

@Transactional
@Service("UserService")
public class UserServiceImpl implements UserService{
	@Autowired
	private UserDao userMapper;

	public User getUser(String userID) {
		return userMapper.getUser(userID);
	}
}


text:
export * from "./page.decorator";
export * from "./element.decorator";


text:
<?php

// Cache the view for 60 seconds
return view('file_name', $data, ['cache' => 60]);


text:
"""This module provides classes and convenience functions for compressing and
decompressing data using Huffman compression algorithm.

The interface provided by this module is very similar to that of the :mod:`bz2` module
Note that `HuffmanCompressor`, `HuffmanDecompressor`, and `HuffmanFile` are *not*
thread-safe, so if you need to use a single instance of these classes from multiple
threads, it is necessary to protect it with a lock.
"""

__all__ = [
    "HuffmanError",
    "HuffmanFile",
    "HuffmanCompressor",
    "HuffmanDecompressor",
    "compress",
    "decompress",
]

import io
import os
from builtins import open as builtin_open

from ._C import ffi, lib

DEFAULT_BLOCK_SIZE = 131072
DEFAULT_MEM_LIMIT = 262144

class HuffmanError(Exception):
    """The exception is raised when error occurs during compression or decompression."""

def unwrap_exc(err, message):
    if err != lib.HUF_ERROR_SUCCESS:
        err_str = ffi.string(lib.huf_error_string(err))
        raise HuffmanError(f"{err_str.decode('utf-8')}. {message}")

_MODE_CLOSED = 0
_MODE_READ = 1
_MODE_WRITE = 2

class HuffmanFile(io.BufferedIOBase):
    """A file object providing transparent Huffman (de)compression.

    A HuffmanFile can act as a wrapper for an existing file object, or refer
    directly to a named file on disk.

    Note that HuffmanFile provides a *binary* file interface - data read is
    returned as bytes, and data to be written should be given as bytes.
    """

    def __init__(self, filename, mode="w", blocksize=DEFAULT_BLOCK_SIZE,
                 memlimit=DEFAULT_MEM_LIMIT):
        """Open a Huffman-compressed file.
        """
        self._fp = None
        self._mode = _MODE_CLOSED
        self._closefp = False

        if mode in ("", "r", "rb"):
            mode = "rb"
            mode_code = _MODE_READ
            self._decompressor = HuffmanDecompressor(memlimit)
        elif mode in ("w", "wb"):
            mode = "wb"
            mode_code = _MODE_WRITE
            self._compressor = HuffmanCompressor(blocksize)
        elif mode in ("x", "xb"):
            mode = "xb"
            mode_code = _MODE_WRITE
            self._compressor = HuffmanCompressor(blocksize)
        elif mode in ("a", "ab"):
            mode = "ab"
            mode_code = _MODE_WRITE
            self._compressor = HuffmanCompressor(blocksize)
        else:
            raise ValueError("Invalid mode: %r" % (mode,))

        if isinstance(filename, (str, bytes, os.PathLike)):
            self._fp = builtin_open(filename, mode)
            self._closefp = True
            self._mode = mode_code
        elif hasattr(filename, "read") or hasattr(filename, "write"):
            self._fp = filename
            self._mode = mode_code
        else:
            raise TypeError("filename must be a str, bytes, file or PathLike object")

    def close(self):
        """Flush and close the file.

        May be called more than once without error. Once the file is closed,
        any other operation on it will raise a ValueError.
        """
        if self._mode == _MODE_CLOSED:
            return
        try:
            if self._mode == _MODE_READ:
                self._decompressor.close()
                self._decompressor = None
            elif self._mode == _MODE_WRITE:
                self._fp.write(self._compressor.flush())
                self._compressor = None
        finally:
            try:
                if self._closefp:
                    self._fp.close()
            finally:
                self._fp = None
                self._closefp = False
                self._mode = _MODE_CLOSED

    @property
    def closed(self):
        """True if this file is closed."""
        return self._mode == _MODE_CLOSED

    def _check_not_closed(self):
        if self.closed:
            raise ValueError("I/O operation on closed file")

    def fileno(self):
        """Return the file descriptor for the underlying file."""
        self._check_not_closed()
        return self._fp.fileno()

    def seekable(self):
        """Return whether the file supports seeking."""
        return False

    def readable(self):
        """Return whether the file was opened for reading."""
        self._check_not_closed()
        return self._mode == _MODE_READ

    def _check_can_read(self):
        if not self.readable():
            raise io.UnsupportedOperation("File not open for reading")

    def writable(self):
        """Return whether the file was opened for writing."""
        self._check_not_closed()
        return self._mode == _MODE_WRITE

    def _check_can_write(self):
        if not self.writable():
            raise io.UnsupportedOperation("File not open for writing")

    def read(self, size=-1):
        """Read up to size uncompressed bytes from the file.

        If size is negative or omitted, read until EOF is reached.
        Returns b"" if the file is already at EOF.
        """
        self._check_can_read()
        if size < 0:
            size = io.DEFAULT_BUFFER_SIZE
        data = self._fp.read(size)
        return self._decompressor.decompress(data)

    def write(self, data):
        """Write a byte string to the file.

        Returns the number of uncompressed bytes written, which is always the
        length of data in bytes. Note that due to buffering, the file on disk
        may not reflect the data written until close() is called.
        """
        self._check_can_write()
        if isinstance(data, (bytes, bytearray)):
            length = len(data)
        else:
            # Accept any data that supports the buffer protocol.
            data = memoryview(data)
            length = data.nbytes

        compressed = self._compressor.compress(data)
        self._fp.write(compressed)
        return length

def open(filename, mode="rb", encoding=None, errors=None, newline=None):
    """Open a bzip2-compressed file in binary or text mode.

    The filename argument can be an actual filename (a str, bytes, or PathLike object),
    or an existing file object to read from or write to.

    The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or "ab" for binary
    mode, or "rt", "wt", "xt" or "at" for text mode. The default mode is "rb".

    For binary mode, this function is equivalent to the HuffmanFile constructor:
    HuffmanFile(filename, mode). In this case, the encoding, errors and newline
    arguments must not be provided.

    For text mode, a HuffmanFile object is created, and wrapped in an io.TextIOWrapper
    instance with the specified encoding, error handling behavior, and line ending(s).
    """
    if "t" in mode and "b" in mode:
        raise ValueError("Invalid mode: %r" % (mode,))
    else:
        if encoding is not None:
            raise ValueError("Argument 'encoding' not supported in binary mode")
        if errors is not None:
            raise ValueError("Argument 'errors' not supported in binary mode")
        if newline is not None:
            raise ValueError("Argument 'newline' not supported in binary mode")

    file_mode = mode.replace("t", "")
    binary_file = HuffmanFile(filename, file_mode)

    if "t" in mode:
        return io.TextIOWrapper(binary_file, encoding, errors, newline)
    else:
        return binary_file

class MemStream:

    __slots__ = ["_len_ptr", "_buf_ptr", "_ptr"]

    def __init__(self, capacity):
        self._len_ptr = ffi.new("size_t *")

        # Create pointer for membuf backend memory, it's much easier to
        # access data through these pointers rather than copying content.
        #
        # Open memory buffers for reading and writing.
        self._buf_ptr = ffi.new("void **")
        self._ptr = ffi.new("huf_read_writer_t **")

        err = lib.huf_memopen(self._ptr, self._buf_ptr, capacity)
        unwrap_exc(err, f"Failed to allocate memory stream of {capacity} bytes long")

    @property
    def this(self):
        return self._ptr[0]

    def close(self):
        err = lib.huf_memclose(self._ptr)
        unwrap_exc(err, "Failed to close memory stream")

    def getvalue(self):
        buf = ffi.cast("char *", self._buf_ptr[0])
        return ffi.buffer(buf, len(self))[:]

    def write(self, data):
        err = self.this.write(self.this.stream, data, len(data))
        unwrap_exc(err, "Failed to write data to the memory stream")

    def seek(self, offset, whence=io.SEEK_SET):
        if whence != io.SEEK_SET:
            raise ValueError(
                "Seek on in-memory stream allows only io.SEEK_SET; got "
                f"{whence}, which is not supported"
            )
        if offset != 0:
            raise ValueError(
                "Seek on in-memory stream allows only rewinds; got "
                f"offset = {offset} which is not supported"
            )
        err = lib.huf_memrewind(self.this)
        unwrap_exc(err, "Failed to rewind memory stream")

    def __len__(self):
        err = lib.huf_memlen(self.this, self._len_ptr)
        unwrap_exc(err, "Failed to retrieve length of the memory stream")
        return self._len_ptr[0]

class HuffmanCompressor:
    """Create a new compressor object.

    This object may be used to compress data incrementally.
    """

    def __init__(self, blocksize=DEFAULT_BLOCK_SIZE):
        self._blocksize = blocksize
        self._flushed = False

        self.istream = MemStream(blocksize)
        self.ostream = MemStream(blocksize)

        # Initialize the encoding configuration, it's the same for the whole
        # encoding process.
        self._config = ffi.new("huf_config_t *")
        self._config.blocksize = blocksize
        self._config.reader_buffer_size = 0
        self._config.writer_buffer_size = 0
        self._config.reader = self.istream.this
        self._config.writer = self.ostream.this

    def compress(self, data):
        """Provide data to the compressor object.

        Returns a block of compressed data if possible, or an empty byte string
        otherwise.

        When you have finished providing data to the compressor, call the `flush()`
        method to finish the compression process.
        """
        encoding = bytes()
        if self._flushed:
            return encoding()

        buf_bytes = len(self.istream)

        # Calculate the amount of bytes ready for encoding considering the content
        # of the buffer in the input stream. If at least one block is available for
        # encoding, run the encoder, put remaining bytes to the buffer, until the
        # next `compress` or `flush` call.
        all_bytes = buf_bytes + len(data)
        num_blocks = all_bytes // self._blocksize
        num_bytes = num_blocks * self._blocksize

        # Calculate how much data is required to take from the input bytes and what
        # to write the input stream until the next call.
        max_bytes = num_bytes - buf_bytes
        rem_bytes = len(data) - max_bytes

        if num_blocks > 0:
            self.istream.write(data[:max_bytes])

            self._config.length = num_bytes
            err = lib.huf_encode(self._config)
            unwrap_exc(err, "Failed to encode the data")

            encoding = self.ostream.getvalue()

            # Reset input stream, to write next time a new portion of data. Reset
            # output stream to discard content in the buffer.
            self.istream.seek(0)
            self.ostream.seek(0)

        # Write the remaining bytes to the input buffer, so the encoding could
        # continue. The istream can grow as large as necessary to fit all the
        # remaining bytes.
        if rem_bytes > 0:
            self.istream.write(data[max_bytes:max_bytes+rem_bytes])

        return encoding

    def flush(self):
        """Finish the compression process.

        Returns the compressed data left in internal buffers. The compressor object
        may not be used after this method is called.
        """
        encoding = bytes()

        if self._flushed:
            return encoding

        self._config.length = len(self.istream)

        if self._config.length > 0:
            err = lib.huf_encode(self._config)
            unwrap_exc(err, "Failed to encode the data")
            encoding = self.ostream.getvalue()

        self.istream.close()
        self.ostream.close()
        self._flushed = True

        return encoding

class HuffmanDecompressor:
    """Create a new decompressor object.

    This object may be used to decompress data incrementally.
    """

    def __init__(self, memlimit=DEFAULT_MEM_LIMIT):
        self.istream = MemStream(memlimit)
        self.ostream = MemStream(memlimit)

        self._config = ffi.new("huf_config_t *")
        self._config.reader_buffer_size = 0
        self._config.writer_buffer_size = 0
        self._config.reader = self.istream.this
        self._config.writer = self.ostream.this

    def decompress(self, data):
        """Decompress data (a `bytes` object), returning uncompressed data as `bytes`.

        If data is the concatenation of multiple distinct compressed blocks, decompress
        all of these blocks, and return the concatenation of the results.
        """
        self.istream.write(data)
        self._config.length = len(self.istream)

        err = lib.huf_decode(self._config)
        unwrap_exc(err, "Failed to decode the data")

        decoding = self.ostream.getvalue()
        self.ostream.seek(0)

        return decoding

    def close(self):
        """Release the decompressor resources."""
        self._closed = True
        self.istream.close()
        self.ostream.close()

def compress(data, blocksize=DEFAULT_BLOCK_SIZE):
    """Compress *data*, returning the compressed data as a `bytes` object.

    See `HuffmanCompressor` above for a description of the *blocksize* argument.

    For incremental compression, use `HuffmanCompressor` instead.
    """
    comp = HuffmanCompressor(blocksize)
    return comp.compress(data) + comp.flush()

def decompress(data, memlimit=DEFAULT_MEM_LIMIT):
    """Decompress *data*, returning the uncompressed data as a `bytes` object.

    If *data* is the concatenation of multiple distinct compressed blocks,
    decompress all of these blocks, and return the concatenation of the results.

    See `HuffmanDecompressor` above for a description of the *memlimit*
    argument.
    """
    decomp = HuffmanDecompressor(memlimit)
    data_out = decomp.decompress(data)
    decomp.close()
    return data_out


text:
package edu.utah.further.fqe.impl.domain;

import static junit.framework.Assert.assertEquals;
import static org.slf4j.LoggerFactory.getLogger;

import java.io.IOException;
import java.util.Map;

import javax.xml.bind.JAXBException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import edu.utah.further.core.api.xml.XmlService;
import edu.utah.further.core.test.annotation.UnitTest;
import edu.utah.further.core.xml.jaxb.JaxbConfig;
import edu.utah.further.fqe.ds.api.domain.Data;
import edu.utah.further.fqe.ds.api.domain.DsMetaData;
import edu.utah.further.fqe.ds.api.domain.DsState;
import edu.utah.further.fqe.impl.fixture.FqeImplUtestFixture;

/**
 * Test [un-]marshalling composite {@link Data} entities and their sub-classes with JAXB
 * polymorphism syntax.
 *

 * -----------------------------------------------------------------------------------

 * (c) 2008-2013 FURTHeR Project, Health Sciences IT, University of Utah

 * Contact: {@code <further@utah.edu>}

 * Biomedical Informatics, 26 South 2000 East

 * Room 5775 HSEB, Salt Lake City, UT 84112

 * Day Phone: 1-801-581-4080

 * -----------------------------------------------------------------------------------
 *
 * @author Oren E. Livne {@code <oren.livne@utah.edu>}
 * @version May 29, 2009
 */
@UnitTest
public final class UTestJaxbData extends FqeImplUtestFixture
{
	// ========================= CONSTANTS =================================

	/**
	 * A logger that helps identify this class' printouts.
	 */
	private static final Logger log = getLogger(UTestJaxbData.class);

	/**
	 * Test input for marshalling tests.
	 */
	private static final String RAW_CHILDREN_FILE = "dataset-raw.xml";

	/**
	 * Test input for marshalling tests.
	 */
	private static final String RAW_XSI_FILE = "dataset-ds-xsi-type.xml";

	/**
	 * Test input for marshalling tests.
	 */
	private static final String RAW_SHORT_FILE = "dataset-ds-short.xml";

	/**
	 * Test input for marshalling tests.
	 */
	private static final String FQE_FILE = "dataset-ds-fqe.xml";

	// ========================= DEPENDENCIES ==============================

	/**
	 * JAXB utilities.
	 */
	@Autowired
	private XmlService xmlService;

	/**
	 * For setup/tear-down.
	 */
	private Map<String, Object> jaxbConfig;

	// ========================= FIELDS ====================================

	/**
	 * Set up default JAXB configuration.
	 */
	@Before
	public void setUpXmlService()
	{
		jaxbConfig = xmlService.getDefaultJaxbConfig();
		xmlService.setDefaultJaxbConfig(JaxbConfig.FURTHER.getJaxbConfig());
	}

	/**
	 * Restore original default JAXB configuration.
	 */
	@After
	public void restoreXmlService()
	{
		xmlService.setDefaultJaxbConfig(jaxbConfig);
	}

	// ========================= TESTING METHODS ===========================

	/**
	 * Marshal a Data set with raw {@link Data} children.
	 */
	@Test
	public void marshalDataSetRawChildren() throws Exception
	{
		// Raw parent
		final Data set = new Data();

		// Raw child
		final Data metaData = new Data("name", "description");
		set.addChild(metaData);

		assertEquals(1, set.getNumChildren());

		final String s = xmlService.marshal(set);
		if (log.isDebugEnabled())
		{
			log.debug("Entity    = " + set);
			log.debug("Marshaled = " + s);
		}
	}

	/**
	 * Marshal a Data set with {@link DsMetaData} children.
	 */
	@Test
	public void marshalDataSetDsChildren() throws Exception
	{
		// Raw parent
		final Data set = new Data();

		// Specific child
		final DsMetaData metaData = new DsMetaData("name", "description");
		metaData.setState(DsState.ACTIVE);
		set.addChild(metaData);

		assertEquals(1, set.getNumChildren());

		final String s = xmlService.marshal(set);
		if (log.isDebugEnabled())
		{
			log.debug("Entity    = " + set);
			log.debug("Marshaled = " + s);
		}
	}

	/**
	 * Unmarshal a Data set with raw {@link Data} children.
	 */
	@Test
	public void unmarshalDataSetRawChildren() throws Exception
	{
		final Data result = xmlService.unmarshalResource(RAW_CHILDREN_FILE, Data.class);
		assertEquals(2, result.getNumChildren());
	}

	/**
	 * Unmarshal a Data set with {@link DsMetaData} children.
	 */
	@Test
	public void unmarshalDataSetDsChildrenXsiType() throws Exception
	{
		testDataSet(RAW_XSI_FILE, 2);
	}

	/**
	 * Unmarshal a Data set with {@link DsMetaData} children. Shortened XML namespace
	 * format.
	 */
	@Test
	public void unmarshalDataSetDsChildrenShortFormat() throws Exception
	{
		testDataSet(RAW_SHORT_FILE, 2);
	}

	/**
	 * Unmarshal a Data set with {@link DsMetaData} children from FQE-processed XML before
	 * it is massaged by some translators.
	 */
	@Test
	public void unmarshalDataSetDsChildrenRawFqeProcessingFormat() throws Exception
	{
		testDataSet(FQE_FILE, 2);
	}

	// ========================= PRIVATE METHODS ===========================

	/**
	 * @param resourceName
	 * @param expectedNumChildren
	 * @throws JAXBException
	 * @throws IOException
	 */
	private void testDataSet(final String resourceName, final int expectedNumChildren)
			throws JAXBException, IOException
	{
		final Data result = xmlService.unmarshalResource(resourceName, xmlService
				.options()
				.addClass(DsMetaData.class));

		assertEquals(expectedNumChildren, result.getNumChildren());
		if (expectedNumChildren > 0)
		{
			final DsMetaData md1 = (DsMetaData) result.getChildren().get(0);
			assertEquals(DsState.ACTIVE, md1.getState());
		}
		if (expectedNumChildren > 1)
		{
			final DsMetaData md2 = (DsMetaData) result.getChildren().get(1);
			assertEquals(DsState.INACTIVE, md2.getState());
		}
	}
}


text: Message $var['msgnum'] ($var['msize'] bytes) .


text:
// Write a script that converts a number in the range [0...999] to a text corresponding to its English pronunciation.

window.onload = function () {
    document.getElementById("number-input").focus();
};

function englishNumbers() {
    var numberByDigits = jsConsole.readInteger("input"),
        units = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"],
        tens = ["twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"],
        teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"],
        numberByWords,
        numberHundreds,
        numberTens,
        numberUnits;
    numberHundreds = numberTens = numberUnits = null;
    if ((!numberByDigits && numberByDigits !== 0) || numberByDigits > 999 || numberByDigits < 0) {
        jsConsole.writeLine("The entered number is not valid.");
    } else {
        if (Math.floor(numberByDigits / 100) > 0) {
            numberHundreds = units[Math.floor(numberByDigits / 100)] + " hundred";  //return the hundreds
            numberByDigits %= 100;
        }
        if (Math.floor(numberByDigits / 10) > 1) {
            numberTens = tens[Math.floor(numberByDigits / 10) - 2];             //returns the tens if they are >= 20
            if (numberByDigits % 10 !== 0) {
                numberUnits = units[numberByDigits % 10];           //returns the units when tens are not null
            }
        } else if (Math.floor(numberByDigits / 10) === 1) {
            numberUnits = teens[numberByDigits % 10];                   //returns numbers from 10 to 19
        } else if (numberHundreds !== null && numberByDigits % 10 === 0) {
            numberUnits = null;                                     //return numbers like 100, 200, 300
        } else {
            numberUnits = units[numberByDigits % 10];       //returns units when tens are null
        }
                                                            //formats the spaces and "and" for the output string
        if (numberHundreds !== null) {
            if (numberTens !== null) {
                numberByWords = numberHundreds + " " + numberTens + " " + numberUnits;
            } else {
                if (numberUnits !== null) {
                    numberByWords = numberHundreds + " and " + numberUnits;
                } else {
                    numberByWords = numberHundreds;
                }
            }
        } else {
            if (numberTens !== null) {
                numberByWords = numberTens + " " + numberUnits;
            } else {
                numberByWords = numberUnits;
            }
        }
        numberByWords = numberByWords.charAt(0).toUpperCase() + numberByWords.slice(1); // Makes first letter uppercase
        jsConsole.writeLine(numberByWords);
    }
}

function onEnterKeyPressed(event) {
    if (event.keyCode === 13) {
        englishNumbers();
    }
}


text:
cask 'kitty' do
  version '0.17.2'
  sha256 'e5fe49584b4327402a49d7465b426b1626d147a474a7a0d8e355697e65df4db2'

  url "https://github.com/kovidgoyal/kitty/releases/download/v#{version}/kitty-#{version}.dmg"
  appcast 'https://github.com/kovidgoyal/kitty/releases.atom'
  name 'kitty'
  homepage 'https://github.com/kovidgoyal/kitty'

  depends_on macos: '>= :sierra'

  app 'kitty.app'
  binary "#{appdir}/kitty.app/Contents/MacOS/kitty"

  zap trash: [
               '~/.config/kitty',
               '~/Library/Preferences/kitty',
               '~/Library/Saved Application State/net.kovidgoyal.kitty.savedState',
             ]
end


text:
title: Mind
description: That which enables thoughts.
keywords: mind, philosophy
---

I think. Therefore I am.


text:
class RemoveColumnFromWorkers < ActiveRecord::Migration[5.0]
  def change
    remove_column :workers, :supported_sourcetype, :integer
  end
end


text:
package coeur;

import stockage.Composant;

/**
 * Classe EtatMenu
 * @author TheoDaix, AllanDubrulle, VictorVerhoye
 * @version 1.0
 */
public class EtatMenu extends ControleurEtat
{
	private static EtatMenu instance;
	public static EtatMenu getInstance()
	{
		if (instance ==null)
		{
			instance = new EtatMenu();
		}
		return (EtatMenu) instance;
	}

	public void choixBillet()
	{
		Controleur.getInstance().modifEtat(EtatChoixBillet.getInstance());
	}

	public void choixRenouvAbo()
	{
		Controleur.getInstance().modifEtat(EtatChoixRenouvAbo.getInstance());
	}

	public void choixAchatAbo()
	{
		Controleur.getInstance().modifEtat(EtatChoixAchatAbo.getInstance());
	}

	public void choixPass()
	{
		Controleur.getInstance().modifEtat(EtatChoixPass.getInstance());
	}

	public void choixHoraire()
	{
		Controleur.getInstance().modifEtat(EtatChoixHoraire.getInstance());
	}

	public void entree()
	{
		boolean moyenDePayer = (Controleur.getInstance().getCoeurAStockage().estEnMarche(Composant.FENTEBILLET) || Controleur.getInstance().getCoeurAStockage().estEnMarche(Composant.FENTEPIECE) || Controleur.getInstance().getCoeurAStockage().estEnMarche(Composant.LECTEURCARTE));
		Controleur.getInstance().getCoeurAGraphique().afficherMenu(Controleur.getInstance().getCoeurAStockage().estEnMarche(Composant.IMPRIMANTE), moyenDePayer);
		Controleur.getInstance().getEtatsPrecedents().clear();
		Controleur.getInstance().reinitialisationCommande();
	}
}


text:
<!DOCTYPE html>

    <title>{% block title %}Blight Blog{% endblock %}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link href="{{ STATIC_URL }}css/bootstrap.min.css" rel="stylesheet" media="screen">
	<link href="{{ STATIC_URL }}css/more_style.css" rel="stylesheet" media="screen">
	{% block javascript %}{% endblock %}
	{% block gwt_config_variables %}{% endblock %}

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

          </button>
          Blight Blog

About

		{% block body_content %}

		{% block side_panel_content %}

This is Cotham:
			 Cotham, Bristol
			 51.4638,
			 -2.5995

			<form id="add_new_post" style="display:none;">
				<input type="text" id="latitude" name="latitude" value="unknown" />
				<input type="text" id="longitude" name="longitude" value="unknown"/>
			</form>

			<button id="add_blog_post">Fire!</button>
		{% endblock %}

map here

   		{% endblock %}

©Progressive Logic


text:
"""
Usage: %s FILE [FILE ...]

Checks MC Configuration file cross sections with the central database.
If there are mismatches, a new suggested configuration file is generated.
This file has the same name as the original file with the suffix '.new' appended.

Author: Daniel Abercrombie <dabercro@mit.edu>
"""

import sys

from CrossSecDB.reader import get_xsec

if __name__ == '__main__':

    if len(sys.argv) == 1:
        print __doc__
        exit(0)

    for file_name in sys.argv[1:]:
        print '\nChecking %s\n' % file_name

        suggest_new = False

        with open(file_name, 'r') as config_file:
            lines = list(config_file)

        line_nums = []
        samples = []
        xs = []
        for num, line in enumerate(lines):
            split = line.split()
            if len(split) < 5:
                continue

            line_nums.append(num)
            samples.append(split[1].split('.')[0].split('/')[-1])
            xs.append(float(split[2]))

        stored = get_xsec(samples)

        for index, stored_xs in enumerate(stored):
            if stored_xs != xs[index]:
                suggest_new = True

                print '%s cross section does not match: %s ----> %s' % \
                    (samples[index], xs[index], stored_xs)

                lines[line_nums[index]] = lines[line_nums[index]].replace(str(xs[index]), str(stored_xs))

        if suggest_new:
            print '\nWriting suggested config: %s.new\n' % file_name

            with open('%s.new' % file_name, 'w') as output_file:
                output_file.write(''.join(lines))

        else:
            print 'All good!\n'


text:
'use strict';

describe('Controller: LoginCtrl', function () {

  // load the controller's module
  beforeEach(module('BackendApis.App'));

  var LoginCtrl, scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    LoginCtrl = $controller('LoginCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of user attributes to the scope', function () {
    expect(scope.username).toBeDefined();
    expect(scope.password).toBeDefined();
    expect(scope.loginFailed).toBeDefined();
  });
});


text:
namespace seqan {

// ============================================================================
// Forwards
// ============================================================================

// ============================================================================
// Typedes, Classes, Enums
// ============================================================================

struct TimelineEntry_
{
    unsigned entryType;
    bool isBegin;
    double timestamp;

    TimelineEntry_() :
        entryType(0), isBegin(false), timestamp(-1) {}

    TimelineEntry_(bool isBegin_, unsigned entryType_, double timestamp_) :
        entryType(entryType_), isBegin(isBegin_), timestamp(timestamp_) {}
};

class Timeline
{
public:
    enum
    {
        INITIAL_SIZE = 1024
    };

    double initTimestamp;
    String<Pair<CharString, CharString> > _taskTypeNames;  // (short name, long name)
    String<String<TimelineEntry_> > _entries;

    // TODO(holtgrew): Move to global function?
    static Timeline & instance()
    {
        static Timeline tl;
        return tl;
    }

private:
    // Can only construct in instance()!
    Timeline() :
        initTimestamp(sysTime()) {}

    // No copy-construction, no assignment, we are a Singleton!
    Timeline(Timeline const &);
    void operator=(Timeline const &);
};

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

inline
unsigned
timelineAddTaskType(CharString const & shortName, CharString const & longName)
{
    appendValue(Timeline::instance()._taskTypeNames, Pair<CharString, CharString>(shortName, longName));
    return length(Timeline::instance()._taskTypeNames) - 1;
}

inline
unsigned
timelineAddTaskType(CharString const & shortName)
{
    return timelineAddTaskType(shortName, shortName);
}

inline
void
initTimeline(int threadCount)
{
    resize(Timeline::instance()._entries, threadCount);
    for (int i = 0; i < threadCount; ++i)
        reserve(Timeline::instance()._entries[i], static_cast<int>(Timeline::INITIAL_SIZE), Generous());
    timelineAddTaskType("WAIT");
}

inline
void
initTimeline()
{
    initTimeline(omp_get_max_threads());
}

inline
double
timelineBeginTask(unsigned taskTypeNo)
{
    SEQAN_ASSERT_LT_MSG(taskTypeNo, length(Timeline::instance()._taskTypeNames), "Too large task type no!");
    double timestamp = sysTime();
    appendValue(Timeline::instance()._entries[omp_get_thread_num()], TimelineEntry_(true, taskTypeNo, timestamp));
    return timestamp;
}

inline
double
timelineEndTask(unsigned taskTypeNo)
{
    SEQAN_ASSERT_LT_MSG(taskTypeNo, length(Timeline::instance()._taskTypeNames), "Too large task type no!");
    double timestamp = sysTime();
    appendValue(Timeline::instance()._entries[omp_get_thread_num()], TimelineEntry_(false, taskTypeNo, timestamp));
    return timestamp;
}

inline
void
dumpTimeline(char const * path, bool appendPid)
{
    const double gapIgnore = 0.0001;
    char * pathBuffer = new char[strlen(path) + 30];
    strcpy(pathBuffer, path);
    if (appendPid)
    {
#ifdef STDLIB_VS
        int pid = _getpid();
#else // #ifdef STDLIB_VS
        int pid = getpid();
#endif // #ifdef STDLIB_VS
        char buffer[30];
        snprintf(buffer, 30, "%d", pid);
        strcat(pathBuffer, ".");
        strcat(pathBuffer, buffer);
    }
    Timeline const & timeline = Timeline::instance();
    FILE * fp = fopen(pathBuffer, "w");
    fprintf(fp, "@SQN:PROFILE\n");
    fprintf(fp, "@TIME\t%f\t%f\n", timeline.initTimestamp, sysTime());

    // Dump event types;
    for (unsigned i = 0; i < length(timeline._taskTypeNames); ++i)
        fprintf(fp, "@EVENT\t%u\t%s\t%s\n", i, toCString(timeline._taskTypeNames[i].i1), toCString(timeline._taskTypeNames[i].i2));

    // Dump events.
    const char * arr[] = {"END", "BEGIN"};
    for (unsigned threadId = 0; threadId < length(timeline._entries); ++threadId)
    {
        for (unsigned i = 0; i < length(timeline._entries[threadId]); ++i)
        {
            while (true)
            {
                if (i + 1 < length(timeline._entries[threadId]) &&
                    !timeline._entries[threadId][i].isBegin &&
                    timeline._entries[threadId][i + 1].isBegin &&
                    timeline._entries[threadId][i].entryType == timeline._entries[threadId][i + 1].entryType &&
                    fabs(timeline._entries[threadId][i + 1].timestamp - timeline._entries[threadId][i].timestamp) < gapIgnore)
                {
                    i += 2;
                }
                else
                {
                    break;
                }
            }
            fprintf(fp, "%u\t%s\t%d\t%f\n", threadId, arr[timeline._entries[threadId][i].isBegin], timeline._entries[threadId][i].entryType, timeline._entries[threadId][i].timestamp);
        }
    }

    fclose(fp);
    delete[] pathBuffer;
}

inline
void
dumpTimeline(char const * path)
{
    dumpTimeline(path, false);
}

}  // namespace seqan

#endif  // #ifndef APP_RAZERS_PROFILE_TIMELINE_H_


text:
package com.vaklinov.zcashui;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.vaklinov.zcashui.ZCashClientCaller.WalletCallException;
import com.vaklinov.zcashui.ZCashInstallationObserver.InstallationDetectionException;

/**
 * Main ZCash Window.
 *
 * @author Ivan Vaklinov <ivan@vaklinov.com>
 */
public class ZCashUI
    extends JFrame
{
    public static final String NAME,VERSION;
    static {
        String name = System.getProperty("wallet.name","@name@");
        if ("@name@".equals(name))
            name = "ZCash Swing Wallet UI";
        NAME = name;
        String version = System.getProperty("wallet.version","@version@");
        if ("@version@".equals(version))
            version = "Custom Version";
        VERSION = version;

        // this is a hack to get the settings dir created before logging
        // subsystem is initialized.
        try {
            OSUtil.getSettingsDirectory();
        } catch (IOException bad) {
            throw new RuntimeException(bad);
        }
    }

    private static final Logger LOG = Logger.getLogger(ZCashUI.class.getName());

    private ZCashInstallationObserver installationObserver;
    private ZCashClientCaller clientCaller;
    private StatusUpdateErrorReporter errorReporter;

    private WalletOperations walletOps;

    private JMenuItem menuItemExit;
    private JMenuItem menuItemAbout;
    private JMenuItem menuItemEncrypt;
    private JMenuItem menuItemBackup;
    private JMenuItem menuItemExportKeys;
    private JMenuItem menuItemImportKeys;
    private JMenuItem menuItemShowPrivateKey;
    private JMenuItem menuItemImportSinglePrivateKey;

    private DashboardPanel dashboard;
    private AddressesPanel addresses;
    private SendCashPanel  sendPanel;
    private AddressBookPanel bookPanel;

    public ZCashUI(ZCashClientCaller clientCaller)
        throws IOException, InterruptedException, WalletCallException
    {
        super(NAME + " "+VERSION);
        ClassLoader cl = this.getClass().getClassLoader();

        this.setIconImage(new ImageIcon(cl.getResource("images/"+NAME+"-246x246.png")).getImage());

        Container contentPane = this.getContentPane();

        errorReporter = new StatusUpdateErrorReporter(this);
        installationObserver = new ZCashInstallationObserver(OSUtil.getProgramDirectory());
        this.clientCaller = clientCaller;

        // Build content
        JTabbedPane tabs = new JTabbedPane();
        Font oldTabFont = tabs.getFont();
        Font newTabFont  = new Font(oldTabFont.getName(), Font.BOLD | Font.ITALIC, oldTabFont.getSize() * 57 / 50);
        tabs.setFont(newTabFont);
        tabs.addTab("Overview ",
        		    new ImageIcon(cl.getResource("images/overview.png")),
        		    dashboard = new DashboardPanel(this, installationObserver, clientCaller, errorReporter));
        tabs.addTab("Own addresses ",
        		    new ImageIcon(cl.getResource("images/address-book.png")),
        		    addresses = new AddressesPanel(clientCaller, errorReporter));
        tabs.addTab("Send cash ",
        		    new ImageIcon(cl.getResource("images/send.png")),
        		    sendPanel = new SendCashPanel(clientCaller, errorReporter));
        tabs.addTab("Address book ",
                new ImageIcon(cl.getResource("images/address-book.png")),
                bookPanel = new AddressBookPanel(sendPanel,tabs));
        contentPane.add(tabs);

        this.walletOps = new WalletOperations(
            	this, tabs, dashboard, addresses, sendPanel, installationObserver, clientCaller, errorReporter);

        this.setSize(new Dimension(870, 427));

        // Build menu
        JMenuBar mb = new JMenuBar();
        JMenu file = new JMenu("Main");
        file.setMnemonic(KeyEvent.VK_M);
        int accelaratorKeyMask = Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask();
	        file.add(menuItemAbout = new JMenuItem("About...", KeyEvent.VK_A));
        menuItemAbout.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, accelaratorKeyMask));
        file.addSeparator();
        file.add(menuItemExit = new JMenuItem("Quit", KeyEvent.VK_Q));
        menuItemExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, accelaratorKeyMask));
        mb.add(file);

        JMenu wallet = new JMenu("Wallet");
        wallet.setMnemonic(KeyEvent.VK_W);
        wallet.add(menuItemBackup = new JMenuItem("Backup...", KeyEvent.VK_B));
        menuItemBackup.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, accelaratorKeyMask));
        wallet.add(menuItemEncrypt = new JMenuItem("Encrypt...", KeyEvent.VK_E));
        menuItemEncrypt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, accelaratorKeyMask));
        wallet.add(menuItemExportKeys = new JMenuItem("Export private keys...", KeyEvent.VK_K));
        menuItemExportKeys.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, accelaratorKeyMask));
        wallet.add(menuItemImportKeys = new JMenuItem("Import private keys...", KeyEvent.VK_I));
        menuItemImportKeys.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, accelaratorKeyMask));
        wallet.add(menuItemShowPrivateKey = new JMenuItem("Show private key...", KeyEvent.VK_P));
        menuItemShowPrivateKey.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, accelaratorKeyMask));
        wallet.add(menuItemImportSinglePrivateKey = new JMenuItem("Import one private key...", KeyEvent.VK_N));
        menuItemImportSinglePrivateKey.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, accelaratorKeyMask));

        mb.add(wallet);

        // TODO: Temporarily disable encryption until further notice - Oct 24 2016
        menuItemEncrypt.setEnabled(false);

        this.setJMenuBar(mb);

        // Add listeners etc.
        menuItemExit.addActionListener(
            new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    ZCashUI.this.exitProgram();
                }
            }
        );

        menuItemAbout.addActionListener(
            new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                	try
                	{
                		AboutDialog ad = new AboutDialog(ZCashUI.this);
                		ad.setVisible(true);
                	} catch (UnsupportedEncodingException uee)
                	{
                		LOG.log(Level.WARNING, "", uee);
                		ZCashUI.this.errorReporter.reportError(uee);
                	}
                }
            }
        );

        menuItemBackup.addActionListener(
        	new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    ZCashUI.this.walletOps.backupWallet();
                }
            }
        );

        menuItemEncrypt.addActionListener(
            new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    ZCashUI.this.walletOps.encryptWallet();
                }
            }
        );

        menuItemExportKeys.addActionListener(
            new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    ZCashUI.this.walletOps.exportWalletPrivateKeys();
                }
            }
       );

       menuItemImportKeys.addActionListener(
            new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    ZCashUI.this.walletOps.importWalletPrivateKeys();
                }
            }
       );

       menuItemShowPrivateKey.addActionListener(
            new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    ZCashUI.this.walletOps.showPrivateKey();
                }
            }
       );

       menuItemImportSinglePrivateKey.addActionListener( (e) -> {
                   ZCashUI.this.walletOps.importSinglePrivateKey();
               }
       );

        // Close operation
        this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        this.addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
                ZCashUI.this.exitProgram();
            }
        });

        // Show initial message
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    String userDir = OSUtil.getSettingsDirectory();
                    File warningFlagFile = new File(userDir + "/initialInfoShown.flag");
                    if (warningFlagFile.exists())
                    {
                        return;
                    } else
                    {
                        warningFlagFile.createNewFile();
                    }

                } catch (IOException ioe)
                {
                    /* TODO: report exceptions to the user */
                    LOG.log(Level.WARNING, "", ioe);
                }

                JOptionPane.showMessageDialog(
                    ZCashUI.this.getRootPane().getParent(),
                    "The ZClassic GUI Wallet is currently considered experimental. Use of this software\n" +
                    "comes at your own risk! Be sure to read the list of known issues and limitations\n" +
                    "at this page: \n" +
                    "https://github.com/vaklinov/zcash-swing-wallet-ui#known-issues-and-limitations\n\n" +
                    "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" +
                    "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" +
                    "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" +
                    "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" +
                    "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" +
                    "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n" +
                    "THE SOFTWARE.\n\n" +
                    "(This message will be shown only once)",
                    "Disclaimer", JOptionPane.INFORMATION_MESSAGE);
            }
        });
    }

    public void exitProgram()
    {
        LOG.info("Exiting ...");

        this.dashboard.stopThreadsAndTimers();

        ZCashUI.this.setVisible(false);
        ZCashUI.this.dispose();

        System.exit(0);
    }

    public static void main(String argv[])
        throws IOException
    {
        try
        {
            LOG.info("Starting "+NAME+" "+VERSION+"...");
            LOG.info("OS: " + System.getProperty("os.name") + " = " + OSUtil.getOSType());
            LOG.info("Current directory: " + new File(".").getCanonicalPath());
            LOG.info("Class path: " + System.getProperty("java.class.path"));
            LOG.info("Environment PATH: " + System.getenv("PATH"));

            ////////////////////////////////////////////////////////////
            if (OSUtil.getOSType() != OSUtil.OS_TYPE.MAC_OS) {
                for (LookAndFeelInfo ui : UIManager.getInstalledLookAndFeels())
                {
                    LOG.info("Available look and feel: " + ui.getName() + " " + ui.getClassName());
                    if (ui.getName().equals("Nimbus"))
                    {
                        UIManager.setLookAndFeel(ui.getClassName());
                        break;
                    }
                }
            } else
                System.setProperty("apple.laf.useScreenMenuBar", "true");

            /////////////////////////////////////////////////////
            ZCashClientCaller clientCaller = new ZCashClientCaller(OSUtil.getProgramDirectory());
            StartupProgressDialog startupBar = new StartupProgressDialog(clientCaller);
            startupBar.setVisible(true);
            startupBar.waitForStartup();
            ZCashUI ui = new ZCashUI(clientCaller);
            ui.setVisible(true);

        } catch (InstallationDetectionException ide)
        {
            LOG.log(Level.WARNING,"ide",ide);
            JOptionPane.showMessageDialog(
                null,
                "This program was started in directory: " + OSUtil.getProgramDirectory() + "\n" +
                ide.getMessage() + "\n" +
                "See the log file for more detailed error information!",
                "Installation error",
                JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        } catch (WalletCallException wce)
        {
            LOG.log(Level.WARNING, "wce", wce);

            if ((wce.getMessage().indexOf("{\"code\":-28,\"message\":\"Verifying blocks")      != -1)  ||
            	(wce.getMessage().indexOf("{\"code\":-28,\"message\":\"Rescanning")            != -1)  ||
            	(wce.getMessage().indexOf("{\"code\":-28,\"message\":\"Loading wallet")        != -1)  ||
            	(wce.getMessage().indexOf("{\"code\":-28,\"message\":\"Activating best chain") != -1)  ||
            	(wce.getMessage().indexOf("{\"code\":-28,\"message\":\"Loading addresses")     != -1))
            {
                JOptionPane.showMessageDialog(
                        null,
                        "It appears that zcashd has been started but is not ready to accept wallet\n" +
                        "connections. It is still loading the wallet and blockchain. Please try to \n" +
                        "start the GUI wallet later...",
                        "Wallet communication error",
                        JOptionPane.ERROR_MESSAGE);
            } else
            {
                JOptionPane.showMessageDialog(
                    null,
                    "There was a problem communicating with the ZCash daemon/wallet. \n" +
                    "Please ensure that the ZCash server zcashd is started (e.g. via \n" +
                    "command  \"zcashd --daemon\"). Error message is: \n" +
                     wce.getMessage() +
                    "See the console output for more detailed error information!",
                    "Wallet communication error",
                    JOptionPane.ERROR_MESSAGE);
            }

            System.exit(2);
        } catch (Exception e)
        {
            LOG.log(Level.WARNING, "Generic exception", e);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            e.printStackTrace(ps);
            ps.flush();
            String stackTrace = new String(baos.toByteArray());
            JOptionPane.showMessageDialog(
                null,
                "A general unexpected critical error has occurred: \n" + e.getMessage() + "\n" +
                stackTrace,
                "Error",
                JOptionPane.ERROR_MESSAGE);
            System.exit(3);
        }
    }
}


text:
<link rel="import" href="../../../packages/polymer/polymer.html">
<link rel="import" href="../utility/safe_html.html">

<polymer-element name="h-tabview">
  <template>
    <link rel="stylesheet" href="tabview.css">

      <content select="h-tab"></content>

      <template if="{{orientation == 'top' || orientation == 'left' || orientation == 'right'}}">

          <template repeat="{{tab in tabs}}">

              {{tab.header}}
              <template if="{{tab.closable}}">

              </template>

          </template>

      </template>

        <template repeat="{{tab in tabs}}">

            <h-safe-html content="{{tab.content}}"></h-safe-html>

        </template>

      <template if="{{orientation == 'bottom'}}">

          <template repeat="{{tab in tabs}}">

              {{tab.header}}
              <template if="{{tab.closable}}">

              </template>

          </template>

      </template>

  </template>

</polymer-element>


text:
<?php
    require('create.php');
    require('project.php');
    require('update.php');
    require('currency_modal.php');
?>

All Clients

            <?php foreach($clients as $client) : ?>

                            <a href="#" onclick="view_client(<?php echo $client['id']; ?>)" data-toggle="modal" data-target="#modal-edit-client"><?php echo $client['company_name']; ?>

                            <button type="button" class="btn btn-success pull-right" onclick="view_client_project(<?php echo $client['id']; ?>)" data-toggle="modal" data-target="#modal-client-project">Projects</button>
                            <button type="button" class="btn btn-default pull-right" onclick="edit_client(<?php echo $client['id']; ?>)" style="margin-right: 10px;" data-toggle="modal" data-target="#modal-edit-client">Edit</button>

            <?php endforeach; ?>

        <button type="button" class="btn btn-primary pull-right" data-toggle="modal" data-target="#modal-add-client">Add Client</button>


text:
define(
    function ( require ) {
        var hasDot = require( './has.dot' );

        return {
            name: 'amd/btModuleId/index',
            check: function () {
                return hasDot.name == 'amd/btModuleId/has.dot'
            }
        };
    }
);


text:
@implementation MCMMiniScoreboardXMLResponseSerializer

- (id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error
{
    NSData *responseData = [super responseObjectForResponse:response data:data error:error];

    NSError *docError = nil;
    ONOXMLDocument *document = [ONOXMLDocument XMLDocumentWithData:responseData error:&docError];

    if (docError) {
        // handle document error
    }

    return [self parseMiniScoreboard:document];
}

- (NSDictionary *)parseMiniScoreboard:(ONOXMLDocument *)document
{
    NSDictionary *gameInfo = [self parseGameInfoInDocument:document];
    NSDictionary *gameStatusInfo = [self parseGameStatusInfoInDocument:document];
    NSDictionary *lineScoreInfo = [self parseLineScoreInfoInDocument:document];
    NSDictionary *postGameInfo = [self parsePostGameInfoInDocument:document];
    NSDictionary *homeRunInfo = [self parseHomeRunInfoInDocument:document];
    NSDictionary *inGameInfo = [self parseInGameInfoInDocument:document];
    NSDictionary *reviewInfo = [self parseReviewInfoInDocument:document];

    return @{ @"game": gameInfo,
              @"gameStatus": gameStatusInfo,
              @"lineScore": lineScoreInfo,
              @"postGame": postGameInfo,
              @"homeRuns": homeRunInfo,
              @"inGame": inGameInfo,
              @"review": reviewInfo };
}

#pragma mark - Element

- (NSDictionary *)parseGameInfoInDocument:(ONOXMLDocument *)document
{
    ONOXMLElement *game = [document firstChildWithXPath:@"//game"];

    return game ? game.attributes : @{};
}

- (NSDictionary *)parseGameStatusInfoInDocument:(ONOXMLDocument *)document
{
    ONOXMLElement *gameStatus = [document firstChildWithXPath:@"//game_status"];

    return gameStatus ? gameStatus.attributes : @{};
}

- (NSDictionary *)parseLineScoreInfoInDocument:(ONOXMLDocument *)document
{
    ONOXMLElement *lineScore = [document firstChildWithXPath:@"//linescore"];

    if (!lineScore) {
        return @{};
    }

    NSArray *innings = [self parseInningsInLineScore:lineScore];
    NSDictionary *runInfo = [self parseRunInfoInLineScore:lineScore];
    NSDictionary *hitInfo = [self parseHitInfoInLineScore:lineScore];
    NSDictionary *errorInfo = [self parseErrorInfoInLineScore:lineScore];
    NSDictionary *homeRunInfo = [self parseHomeRunInfoInLineScore:lineScore];
    NSDictionary *stolenBaseInfo = [self parseStolenBaseInfoInLineScore:lineScore];
    NSDictionary *strikeOutInfo = [self parseStrikeOutInfoInLineScore:lineScore];

    return @{ @"innings": innings,
              @"runs": runInfo,
              @"hits": hitInfo,
              @"errors": errorInfo,
              @"homeRuns": homeRunInfo,
              @"stolenBases": stolenBaseInfo,
              @"strikeOuts": strikeOutInfo, };
}

- (NSDictionary *)parsePostGameInfoInDocument:(ONOXMLDocument *)document
{
    ONOXMLElement *postGame = [document firstChildWithXPath:@"//post_game"];

    if (!postGame) {
        return @{};
    }

    NSDictionary *winningPitcherInfo = [self parseWinningPitcherInfoInPostGame:postGame];
    NSDictionary *losingPitcherInfo = [self parseLosingPitcherInfoInPostGame:postGame];
    NSDictionary *savingPitcherInfo = [self parseSavingPitcherInfoInPostGame:postGame];
    NSDictionary *awayTeamInfo = [self parseAwayTeamInfoInPostGame:postGame];
    NSDictionary *homeTeamInfo = [self parseHomeTeamInfoInPostGame:postGame];

    NSMutableDictionary *postGameInfo = [NSMutableDictionary dictionaryWithDictionary:postGame.attributes];

    postGameInfo[@"winningPitcher"] = winningPitcherInfo;
    postGameInfo[@"losingPitcher"] = losingPitcherInfo;
    postGameInfo[@"savingPitcher"] = savingPitcherInfo;
    postGameInfo[@"awayTeam"] = awayTeamInfo;
    postGameInfo[@"homeTeam"] = homeTeamInfo;

    return postGameInfo;
}

- (NSDictionary *)parseHomeRunInfoInDocument:(ONOXMLDocument *)document
{
    ONOXMLElement *homeRun = [document firstChildWithXPath:@"//home_runs"];

    if (!homeRun) {
        return @{};
    }

    NSArray *players = [self parsePlayersInHomeRun:homeRun];

    return @{ @"players": players };
}

- (NSDictionary *)parseInGameInfoInDocument:(ONOXMLDocument *)document
{
    ONOXMLElement *inGame = [document firstChildWithXPath:@"//in_game"];

    if (!inGame) {
        return @{};
    }

    NSDictionary *batterInfo = [self parseBatterInfoInDocument:inGame];
    NSDictionary *pitcherInfo = [self parsePitcherInfoInDocument:inGame];
    NSDictionary *opposingPitcherInfo = [self parseOpposingPitcherInfoInDocument:inGame];
    NSDictionary *onDeckInfo = [self parseOnDeckInfoInDocument:inGame];
    NSDictionary *inHoleInfo = [self parseInHoleInfoInDocument:inGame];
    NSDictionary *runnerOnFirstBaseInfo = [self parseRunnerOnFirstBaseInfoInDocument:inGame];
    NSDictionary *runnerOnSecondBaseInfo = [self parseRunnerOnSecondBaseInfoInDocument:inGame];
    NSDictionary *runnerOnThirdBaseInfo = [self parseRunnerOnThirdBaseInfoInDocument:inGame];

    NSMutableDictionary *inGameInfo = [NSMutableDictionary dictionaryWithDictionary:inGame.attributes];

    inGameInfo[@"batter"] = batterInfo;
    inGameInfo[@"pitcher"] = pitcherInfo;
    inGameInfo[@"opposingPitcher"] = opposingPitcherInfo;
    inGameInfo[@"onDeck"] = onDeckInfo;
    inGameInfo[@"inHole"] = inHoleInfo;
    inGameInfo[@"runnerOnFirstBase"] = runnerOnFirstBaseInfo;
    inGameInfo[@"runnerOnSecondBase"] = runnerOnSecondBaseInfo;
    inGameInfo[@"runnerOnThirdBase"] = runnerOnThirdBaseInfo;

    return inGameInfo;
}

- (NSDictionary *)parseReviewInfoInDocument:(ONOXMLDocument *)document
{
    ONOXMLElement *review = [document firstChildWithXPath:@"//review"];

    return review ? review.attributes : @{};
}

#pragma mark - Line Score Helpers

- (NSArray *)parseInningsInLineScore:(ONOXMLElement *)lineScore
{
    NSArray *innings = [lineScore childrenWithTag:@"inning"];

    return innings ? [innings valueForKey:@"attributes"] : @[];
}

- (NSDictionary *)parseRunInfoInLineScore:(ONOXMLElement *)lineScore
{
    ONOXMLElement *run = [lineScore firstChildWithTag:@"r"];

    return run ? run.attributes : @{};
}

- (NSDictionary *)parseHitInfoInLineScore:(ONOXMLElement *)lineScore
{
    ONOXMLElement *hit = [lineScore firstChildWithTag:@"h"];

    return hit ? hit.attributes : @{};
}

- (NSDictionary *)parseErrorInfoInLineScore:(ONOXMLElement *)lineScore
{
    ONOXMLElement *error = [lineScore firstChildWithTag:@"e"];

    return error ? error.attributes : @{};
}

- (NSDictionary *)parseHomeRunInfoInLineScore:(ONOXMLElement *)lineScore
{
    ONOXMLElement *homeRun = [lineScore firstChildWithTag:@"hr"];

    return homeRun ? homeRun.attributes : @{};
}

- (NSDictionary *)parseStolenBaseInfoInLineScore:(ONOXMLElement *)lineScore
{
    ONOXMLElement *stolenBase = [lineScore firstChildWithTag:@"sb"];

    return stolenBase ? stolenBase.attributes : @{};
}

- (NSDictionary *)parseStrikeOutInfoInLineScore:(ONOXMLElement *)lineScore
{
    ONOXMLElement *strikeOut = [lineScore firstChildWithTag:@"so"];

    return strikeOut ? strikeOut.attributes : @{};
}

#pragma mark - Post Game Helpers

- (NSDictionary *)parseWinningPitcherInfoInPostGame:(ONOXMLElement *)postGame
{
    ONOXMLElement *winningPitcher = [postGame firstChildWithTag:@"winning_pitcher"];

    return winningPitcher ? winningPitcher.attributes : @{};
}

- (NSDictionary *)parseLosingPitcherInfoInPostGame:(ONOXMLElement *)postGame
{
    ONOXMLElement *losingPitcher = [postGame firstChildWithTag:@"losing_pitcher"];

    return losingPitcher ? losingPitcher.attributes : @{};
}

- (NSDictionary *)parseSavingPitcherInfoInPostGame:(ONOXMLElement *)postGame
{
    ONOXMLElement *savingPitcher = [postGame firstChildWithTag:@"save_pitcher"];

    return savingPitcher ? savingPitcher.attributes : @{};
}

- (NSDictionary *)parseAwayTeamInfoInPostGame:(ONOXMLElement *)postGame
{
    ONOXMLElement *awayTeam = [postGame firstChildWithTag:@"away_team"];

    return awayTeam ? awayTeam.attributes : @{};
}

- (NSDictionary *)parseHomeTeamInfoInPostGame:(ONOXMLElement *)postGame
{
    ONOXMLElement *homeTeam = [postGame firstChildWithTag:@"home_team"];

    return homeTeam ? homeTeam.attributes : @{};
}

#pragma mark - Home Runs Helper

- (NSArray *)parsePlayersInHomeRun:(ONOXMLElement *)homeRun
{
    NSArray *players = [homeRun childrenWithTag:@"player"];

    return players ? [players valueForKey:@"attributes"] : @[];
}

#pragma mark - In Game Helpers

- (NSDictionary *)parseBatterInfoInDocument:(ONOXMLElement *)inGame
{
    ONOXMLElement *batter = [inGame firstChildWithTag:@"batter"];

    return batter ? batter.attributes : @{};
}

- (NSDictionary *)parsePitcherInfoInDocument:(ONOXMLElement *)inGame
{
    ONOXMLElement *pitcher = [inGame firstChildWithTag:@"pitcher"];

    return pitcher ? pitcher.attributes : @{};
}

- (NSDictionary *)parseOpposingPitcherInfoInDocument:(ONOXMLElement *)inGame
{
    ONOXMLElement *opposingPitcher = [inGame firstChildWithTag:@"opposing_pitcher"];

    return opposingPitcher ? opposingPitcher.attributes : @{};
}

- (NSDictionary *)parseOnDeckInfoInDocument:(ONOXMLElement *)inGame
{
    ONOXMLElement *onDeck = [inGame firstChildWithTag:@"ondeck"];

    return onDeck ? onDeck.attributes : @{};
}

- (NSDictionary *)parseInHoleInfoInDocument:(ONOXMLElement *)inGame
{
    ONOXMLElement *inHole = [inGame firstChildWithTag:@"inhole"];

    return inHole ? inHole.attributes : @{};
}

- (NSDictionary *)parseRunnerOnFirstBaseInfoInDocument:(ONOXMLElement *)inGame
{
    ONOXMLElement *firstBase = [inGame firstChildWithTag:@"runner_on_1b"];

    return firstBase ? firstBase.attributes : @{};
}

- (NSDictionary *)parseRunnerOnSecondBaseInfoInDocument:(ONOXMLElement *)inGame
{
    ONOXMLElement *secondBase = [inGame firstChildWithTag:@"runner_on_2b"];

    return secondBase ? secondBase.attributes : @{};
}

- (NSDictionary *)parseRunnerOnThirdBaseInfoInDocument:(ONOXMLElement *)inGame
{
    ONOXMLElement *thirdBase = [inGame firstChildWithTag:@"runner_on_3b"];

    return thirdBase ? thirdBase.attributes : @{};
}

@end


text:
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.SessionState;
using NMoneys.Web.Models;

namespace NMoneys.Web.Controllers
{
	[SessionState(SessionStateBehavior.Disabled)]
	public class CurrenciesController: Controller
	{
		[OutputCache(CacheProfile = "snapshots")]
		public ActionResult Index()
		{
			IEnumerable<GroupedByInitialInBatches> byInitial = GroupedByInitialInBatches.Collection(
				Currency.FindAll()
				.Select(c => new Snapshot(c)),
				s => s.AlphabeticCode,
				batchSize: 4);

			return View(byInitial);
		}

		public ActionResult Detail(CurrencyIsoCode code)
		{
			Currency currency = Currency.Get(code);
			var snapshot = new Snapshot(currency);
			return PartialView(snapshot);
		}
	}
}


text:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

namespace Sanicball.UI
{
    [RequireComponent(typeof(RectTransform), typeof(Image))]
    public class Marker : MonoBehaviour
    {
        [SerializeField]
        private Transform target;
        [SerializeField]
        private Text textField;

        public Transform Target { get { return target; } set { target = value; } }
        public string Text { get { return textField.text; } set { textField.text = value; } }
        public Sprite Sprite { set { image.sprite = value; } }
        public Color Color { set { image.color = value; colorAlpha = value.a; } }
        public Camera CameraToUse { get; set; }
        public bool Clamp { get; set; }
        public bool HideImageWhenInSight { get; set; }

        private RectTransform rectTransform;
        private Image image;
        private float colorAlpha;

        private const float clampMin = 0.2f;
        private const float clampMax = 1 - clampMin;

        private void Awake()
        {
            rectTransform = GetComponent<RectTransform>();
            image = GetComponent<Image>();
            colorAlpha = image.color.a;
        }

        private void Update()
        {
            var cam = Camera.main;
            if (CameraToUse) cam = CameraToUse;

            if (!target || !cam)
            {
                Destroy(gameObject);
                return;
            }

            var relativePosition = cam.transform.InverseTransformPoint(target.position);
            relativePosition.z = Mathf.Max(relativePosition.z, 1);

            Vector3 p = cam.WorldToViewportPoint(cam.transform.TransformPoint(relativePosition));

            if (Clamp)
                p = new Vector3(Mathf.Clamp(p.x, clampMin, clampMax), Mathf.Clamp(p.y, clampMin, clampMax), p.z);

            rectTransform.anchorMin = p;
            rectTransform.anchorMax = p;

            if (HideImageWhenInSight)
            {
                Ray viewportRay = cam.ViewportPointToRay(p);
                RaycastHit hit;
                bool show = true;
                if (Physics.Raycast(viewportRay, out hit, 400))
                {
                    show = hit.transform == Target;
                }
                image.color = new Color(image.color.r, image.color.g, image.color.b, show ? colorAlpha : 0);
            }
        }
    }
}