text:
/*
 * yeshup.c
 *
 * Wrapper for Linux to prevent child processes from becoming orphaned.
 *
 * In Linux, when a parent process calls another process and the parent crashes
 * or is killed, the child process becomes an "orphan process."	yeshup signals
 * child processes to exit cleanly if the parent dies for whatever reason,
 * preventing orphan processes from accumulating on a system.
 *
 * Usage: Simply append "yeshup " to the beginning of your command when
 * spawning your child process, including all arguments normally. For example,
 * instead of running:
 *
 * child_process arguments
 *
 * You can simply run:
 *
 * yeshup child_process arguments
 *
 * Written originally to implement a feature in SetCPU. Works in Linux only,
 * but should be compatible with most distributions, including Android.
 *
 * For a possible use case/scenario, see http://stackoverflow.com/a/13280892
 */

#include <linux/prctl.h>
#include <signal.h>
#include <unistd.h>

int main(int argc, char **argv) {
     if(argc < 2)
          return 1;
     /* When my parent is killed, give me SIGHUP */
     prctl(PR_SET_PDEATHSIG, SIGHUP, 0, 0, 0);
     /* fork() wipes the parent death signal setting, but exec() does not! */
     return execvp(argv[1], &argv[1]);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="@android:integer/config_shortAnimTime"
    android:fromYDelta="100%"
    android:toYDelta="0%" />

redpajama_set_name: RedPajamaGithub


text:
import datetime

class contact:
    def __init__(self, chat_id='', phone_number='', first_name='', last_name=''):
        """
        Constructor
        """
        curr_datetime = datetime.datetime.now()
        self.date = curr_datetime.strftime("%Y%m%d")
        self.time = curr_datetime.strftime("%H:%M:%S.%f %z")
        self.chat_id = chat_id
        self.phone_number = phone_number
        self.first_name = first_name
        self.last_name = last_name

    def str(self):
        """
        Output the object into a comma separated string
        """
        return "'%s','%s','%s','%s','%s','%s'" % \
               (self.date, \
                self.time, \
                self.chat_id, \
                self.phone_number, \
                self.first_name, \
                self.last_name)

    @staticmethod
    def from_contact_record(row, set_curr_time=True):
        """
        Convert a db record to a channel record
        :param record: Database record
        :param set_curr_time: Indicate if current date and time is set
        """
        if not row or len(row) <= 1:
            return contact()
        else:
            ret = contact(chat_id=row[contact.chat_id_index()],
                          phone_number=row[contact.phone_number_index()],
                          first_name=row[contact.first_name_index()],
                          last_name=row[contact.last_name_index()])

            if not set_curr_time:
                ret.date = row[contact.date_index()]
                ret.time = row[contact.time_index()]

            return ret

    @staticmethod
    def field_str():
        return "date text, time text, chatid text, phonenumber text, " + \
               "firstname text, lastname text"

    @staticmethod
    def key_str():
        return "chatid"

    @staticmethod
    def date_index():
        return 0

    @staticmethod
    def time_index():
        return 1

    @staticmethod
    def chat_id_index():
        return 2

    @staticmethod
    def phone_number_index():
        return 3

    @staticmethod
    def first_name_index():
        return 4

    @staticmethod
    def last_name_index():
        return 5


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HomeOutsideWeatherStation.Shared;

namespace HomeOutsideWeatherStation.Models.Home
{
    public class HomeTemperatureFeelsLikeDewPointChartDataPointModel
    {
        public string Timestamp { get; set; }
        public double Temperature { get; set; }
        public double TemperatureFeelsLike { get; set; }
        public double DewPoint { get; set; }

        public HomeTemperatureFeelsLikeDewPointChartDataPointModel(HomeOutsideWeatherStationData data)
        {
            Timestamp = data.Timestamp.ToString();
            Temperature = (double)data.Temperature;
            TemperatureFeelsLike = WeatherDataConversions.WindChill(Temperature, (double)data.WindSpeed);
            DewPoint = WeatherDataConversions.DewPoint(Temperature, (double)data.Humidity);

        }
    }

    public class HomeTemperatureFeelsLikeDewPointChartDataModel
    {
        public List<List<HomeTemperatureFeelsLikeDewPointChartDataPointModel>> Data { get; set; }
        public double MaxY { get; set; }
        public double MinY { get; set; }

        public HomeTemperatureFeelsLikeDewPointChartDataModel(DateTime endDate)
        {
            SensorSeedDataContext database = new SensorSeedDataContext();

            DateTime startOfTenDaysAgo = endDate.Date.AddDays(-9).ToUniversalTime().AddHours(-18);
            DateTime endOfToday = endDate.Date.AddHours(24).ToUniversalTime();
            List<HomeOutsideWeatherStationData> tenDayDatas = database.HomeOutsideWeatherStationDatas.Where(x => x.Timestamp > startOfTenDaysAgo && x.Timestamp < endOfToday).Where(x => (x.Temperature != null || x.Temperature180 != null || x.TemperatureDHT22 != null) && (x.Humidity != null || x.HumidityDHT22 != null) && x.WindSpeed != null).OrderByDescending(x => x.Timestamp).ToList();
            foreach (var dayDatas in tenDayDatas)
            {
                List<decimal?> temperaturesTemp = new List<decimal?> { dayDatas.Temperature, dayDatas.Temperature180, dayDatas.TemperatureDHT22 };
                List<decimal?> humiditiesTemp = new List<decimal?> { dayDatas.Humidity, dayDatas.HumidityDHT22 };
                dayDatas.Temperature = temperaturesTemp.Where(x => x.HasValue).Average();
                dayDatas.Humidity = humiditiesTemp.Where(x => x.HasValue).Average();

            }

            List<List<HomeTemperatureFeelsLikeDewPointChartDataPointModel>> dataTemp = new List<List<HomeTemperatureFeelsLikeDewPointChartDataPointModel>>();
            List<HomeTemperatureFeelsLikeDewPointChartDataPointModel> currentSeries = new List<HomeTemperatureFeelsLikeDewPointChartDataPointModel>();

            for (int i = tenDayDatas.Count - 1; i > -1; i--)
            {
                var currentItem = tenDayDatas.ElementAt(i);
                if ((i + 1) < tenDayDatas.Count)
                {
                    var previousItem = tenDayDatas.ElementAt(i + 1);
                    var timeDifference = (currentItem.Timestamp - previousItem.Timestamp).TotalMinutes;
                    if (timeDifference > 30) // start a new series
                    {
                        currentSeries = currentSeries.Where((x, n) => n % 3 == 0).ToList(); // Remove every 3rd item
                        dataTemp.Add(currentSeries);
                        currentSeries = new List<HomeTemperatureFeelsLikeDewPointChartDataPointModel>();
                        currentSeries.Add(new HomeTemperatureFeelsLikeDewPointChartDataPointModel(currentItem));
                    }
                    else // add to current series
                    {
                        currentSeries.Add(new HomeTemperatureFeelsLikeDewPointChartDataPointModel(currentItem));
                    }

                }
                else // add to current series
                {
                    currentSeries.Add(new HomeTemperatureFeelsLikeDewPointChartDataPointModel(currentItem));
                }
            }

            if (currentSeries.Count > 0)
            {
                currentSeries = currentSeries.Where((x, n) => n % 3 == 0).ToList(); // Remove every 3rd item
                dataTemp.Add(currentSeries);
            }
            Data = dataTemp;

            var maxTemp = (double)tenDayDatas.Max(x => x.Temperature);
            var maxTempFeelsLike = tenDayDatas.Max(x => WeatherDataConversions.WindChill((double)x.Temperature, (double)x.WindSpeed));
            var maxDewPoint = tenDayDatas.Max(x => WeatherDataConversions.DewPoint((double)x.Temperature, (double)x.Humidity));
            var minTemp = (double)tenDayDatas.Min(x => x.Temperature);
            var minTempFeelsLike = tenDayDatas.Min(x => WeatherDataConversions.WindChill((double)x.Temperature, (double)x.WindSpeed));
            var minDewPoint = tenDayDatas.Min(x => WeatherDataConversions.DewPoint((double)x.Temperature, (double)x.Humidity));

            MaxY = new List<double> {maxTemp, maxTempFeelsLike, maxDewPoint}.Max();
            MinY = new List<double> { minTemp, minTempFeelsLike, minDewPoint }.Min();
        }
    }
}


text:
<?php
// Modal
$_['modal_title']					= 'Vă mulțumim pentru instalarea %s!';
$_['modal_alert']					= '
Buna!

Vă mulțumim pentru instalarea %s! Dacă vă bucurați de această lucrare, vă rugăm să sprijiniți dezvoltarea proiectului. Lăsați un feedback sau faceți o donație.

Folosire plăcută!

Cu respect, Anton.
';
$_['modal_review']					= 'Lasă o recenzie';
$_['modal_donations_title']			= 'Donații';
$_['modal_donations_text']			= 'Vă rugăm să sprijiniți dezvoltarea șablonului cu ajutorul donațiilor.';

// Modal Update
$_['modal_title_update']			= 'Vă mulțumim pentru actualizare %s!';
$_['modal_alert_update']			= '
Buna!

Vă mulțumim pentru actualizare %s! Dacă vă bucurați de această lucrare, vă rugăm să sprijiniți dezvoltarea proiectului. Lăsați un feedback sau faceți o donație.

Folosire plăcută!

Cu respect, Anton.
';

// To appeal to users
$_['appeal_marketplace']			= 'Vă rugăm să evaluați Materialalize Template

Deschideți contul pe OpenCart Marketplace

Selectați "Rate your Downloads"

Selectați "Materialize Template"

Trimiteți o evaluare sinceră și lăsați-vă feedbackul :)

';
$_['appeal_github']					= 'Dacă aveți probleme cu activitatea modulului, vă rugăm să creați o temă cu o problemă la Github.';
$_['appeal_twitter']				= 'Urmăriți pentru informații despre actualizările din Twitter oficial.';
$_['appeal_paypal']					= 'Sprijiniți dezvoltarea unui șablon prin PayPal :)';
$_['appeal_yandex_money']			= 'Sprijiniți dezvoltarea unui șablon prin Yandex.Money :)';


text:
package org.github.dtsopensource.remote.test;

import java.util.UUID;

/**
 * @author ligaofeng 2016年12月8日 下午9:02:58
 */
public class GenerateId {

    private GenerateId() {
    }

    /**
     * @return
     */
    public static String generateOrderId() {
        return "order_" + UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * @return
     */
    public static String generatePaymentId() {
        return "payment_" + UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * @return
     */
    public static String generateFlowId() {
        return "flow_" + UUID.randomUUID().toString().replaceAll("-", "");
    }
}


text:
@routeis('webshop.checkout')
    Do something only on the checkout
@endrouteis


text:
<?php

namespace Rednose\FrameworkBundle\Request\ParamConverter;

use Rednose\FrameworkBundle\Model\OrganizationManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class OrganizationParamConverter implements ParamConverterInterface
{
    /**
     * @var OrganizationManagerInterface
     */
    protected $manager;

    /**
     * Constructor.
     *
     * @param OrganizationManagerInterface $manager
     */
    public function __construct(OrganizationManagerInterface $manager)
    {
        $this->manager = $manager;
    }

    /**
     * {@inheritdoc}
     */
    public function apply(Request $request, ParamConverter $configuration)
    {
        $id = $request->query->get('organization_id');

        if (!$id) {
            return;
        }

        $asset = $this->manager->findOrganizationById($id);

        if (!$asset) {
            throw new NotFoundHttpException();
        }

        $request->attributes->set($configuration->getName(), $asset);
    }

    /**
     * {@inheritdoc}
     */
    public function supports(ParamConverter $configuration)
    {
        return $configuration->getClass() === 'Rednose\FrameworkBundle\Model\OrganizationInterface';
    }
}


text:
require 'guard/gradle/version'
require 'guard'
require 'guard/plugin'

module Guard
  class Gradle < Plugin

    def initialize(options = {})
      @command = './gradlew'
      @task = 'test'
      @multi_projs = false
      @flags = false

      if options.has_key? :multi_project
        @multi_projs = options[:multi_project]
      end
      if options.has_key? :command
        @command = options[:command]
      end
      if options.has_key? :task
        @task = options[:task]
      end
      if options.has_key? :flags
        @flags = options[:flags]
      end

      @DEF_CMD = "#{@command} #{@task}"
      if @flags
        @DEF_CMD = "#{@DEF_CMD} #{@flags}"
      end

      super
    end

    def run_on_changes(paths)
      if paths.size == 1 && @multi_projs
        project = paths[0].split('/')[0]
        file = paths[0].split('/')[1]
        if Dir.glob("#{project}/src/test/**/#{file}*").size > 0
          fire_command("#{@DEF_CMD} -p #{project} -Dtest.single=#{file} --daemon")
        else
          run_all
        end
      elsif(paths.size == 1) && (Dir.glob("src/test/**/#{paths[0]}*").size > 0)
        fire_command("#{@DEF_CMD} -Dtest.single=#{paths[0]} --daemon")
      else
        run_all
      end
    end

    def run_all
      fire_command @DEF_CMD
    end

    def fire_command(command)
      UI.info "running #{command}"
      result = system command
      summary = result ? 'Success' : 'Failure'
      image = result ? :success : :failed
      notify(summary, image)
    end

    def notify(summary, image)
      ::Guard::Notifier.notify(summary, title: 'Gradle Test Results', image: image)
    end

    def start
      fire_command @DEF_CMD
    end

    def run_all
      fire_command @DEF_CMD
    end
  end
end


text:
+++
# Date this page was created.
date = "2017-06-29"

# Project title.
title = "StatSnips"

# Project summary to display on homepage.
summary = "Code snippets and musings from statistically-inclined epidemiologists"

# Optional image to display on homepage (relative to `static/img/` folder).
image_preview = "logo.png"

# Tags: can be used for filtering projects.
# Example: `tags = ["machine-learning", "deep-learning"]`
tags = ["programming", "other", "Science"]

# Optional external URL for project (replaces project detail page).
external_link = "https://statsnips.github.io/"

# Does the project detail page use math formatting?
math = false

# Optional featured image (relative to `static/img/` folder).
[header]
#image = "headers/bubbles-wide.jpg"
#caption = ""

+++


text:
package org.apache.cassandra.cql3.validation.entities.udfverify;

import java.nio.ByteBuffer;
import java.util.List;

import com.datastax.driver.core.TypeCodec;
import org.apache.cassandra.cql3.functions.JavaUDF;
import org.apache.cassandra.cql3.functions.UDFContext;
import org.apache.cassandra.transport.ProtocolVersion;

/**
 * Used by {@link org.apache.cassandra.cql3.validation.entities.UFVerifierTest}.
 */
public final class UseOfSynchronizedWithWaitL extends JavaUDF
{
    public UseOfSynchronizedWithWaitL(TypeCodec<Object> returnDataType, TypeCodec<Object>[] argDataTypes, UDFContext udfContext)
    {
        super(returnDataType, argDataTypes, udfContext);
    }

    protected Object executeAggregateImpl(ProtocolVersion protocolVersion, Object firstParam, List<ByteBuffer> params)
    {
        throw new UnsupportedOperationException();
    }

    protected ByteBuffer executeImpl(ProtocolVersion protocolVersion, List<ByteBuffer> params)
    {
        synchronized (this)
        {
            try
            {
                wait(1000L);
            }
            catch (InterruptedException e)
            {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}


text:
import { isValuePresent } from '../../helpers'

export const absenceLocalValidator = ($element, options) => {
  if (isValuePresent($element.val())) {
    return options.message
  }
}

export const presenceLocalValidator = ($element, options) => {
  if (!isValuePresent($element.val())) {
    return options.message
  }
}

export default {
  absenceLocalValidator,
  presenceLocalValidator
}


text:
<?php

declare(strict_types=1);

namespace Spec\SIAP\User\Listener;

use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Events;
use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationFailureResponse;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use SIAP\User\Listener\AuthenticationFailureListener;
use function PHPSTORM_META\type;

class AuthenticationFailureListenerSpec extends ObjectBehavior
{
    public function it_is_initializable()
    {
        $this->shouldHaveType(AuthenticationFailureListener::class);
    }

    public function it_should_subscribe_event_properly()
    {
        $subscribed = $this->getSubscribedEvents();
        $subscribed->shouldHaveKey(Events::AUTHENTICATION_FAILURE);
    }

    public function it_should_handle_authentication_failed_response(
        AuthenticationFailureEvent $event
    ) {
        $event->setResponse(Argument::type(JWTAuthenticationFailureResponse::class));
        $response = $this->onAuthenticationFailureResponse($event);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/fetch_products_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fetch products" />

    <Button
        android:id="@+id/buy_available_product_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Buy available product" />

    <Button
        android:id="@+id/consume_purchases_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Consume purchase" />

    <Button
        android:id="@+id/restore_purchases_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Restore purchases" />

</LinearLayout>


text:
package scala.macros.internal
package engines.scalac

import scala.tools.nsc.Global
import scala.macros.internal.engines.scalac.semantic._
import scala.macros.internal.engines.scalac.trees._

case class Universe(val g: Global)
    extends scala.macros.Universe
    with Semantic
    with Trees
    with Expansions {
  type Abstracts = TreeAbstracts with MirrorAbstracts with ExpansionAbstracts
  object abstracts extends TreeAbstracts with MirrorAbstracts with ExpansionAbstracts
}


text:
package org.apache.ojb.broker.metadata;

import org.apache.ojb.broker.util.DoubleHashtable;
import org.apache.ojb.broker.util.logging.LoggerFactory;
import org.apache.ojb.broker.util.pooling.PoolConfiguration;

/**
 * this class maintains a table mapping the xml-tags used in the
 * repository.dtd to their corresponding ids used within OJB.
 * This table is used in

 * 1. the RepositoryXmlHandler to identify tags on parsing the
 * repository.xml in a large switch statement.
 * 2. in the RepositoryPersistor to get the proper tag for a
 * given XmlCapable id during assembling the repository.xml
 * for output.

 * Important note: This class is the only place where XML tags from the
 * repository.dtd are maintained.
 * All usages of these tags within OJB must use this table to ease
 * changes of the DTD.
 * @author		Thomas Mahler
 */
public class RepositoryTags implements RepositoryElements
{
    /**
     * the two-way hashtable holding all entries.
     */
    private DoubleHashtable table;

    /**
     * the singleton instance of this class.
     */
    private static RepositoryTags instance = new RepositoryTags();

    /**
     * private Constructor, please use getInstance() to obtain
     * the singleton instance of this class.
     */
    private RepositoryTags()
    {
        // construct the mapping table
        table = new DoubleHashtable();
        table.put("descriptor-repository", new Integer(MAPPING_REPOSITORY));
        table.put("version", new Integer(REPOSITORY_VERSION));
        table.put("isolation-level", new Integer(ISOLATION_LEVEL));
        table.put("jdbc-connection-descriptor", new Integer(JDBC_CONNECTION_DESCRIPTOR));
        table.put("platform", new Integer(DBMS_NAME));
        table.put("schema", new Integer(SCHEMA_NAME));
        table.put("jcd-alias", new Integer(JCD_ALIAS));
        table.put("default-connection", new Integer(DEFAULT_CONNECTION));
        table.put("driver", new Integer(DRIVER_NAME));
        table.put("protocol", new Integer(URL_PROTOCOL));
        table.put("subprotocol", new Integer(URL_SUBPROTOCOL));
        table.put("dbalias", new Integer(URL_DBALIAS));
        table.put("username", new Integer(USER_NAME));
        table.put("password", new Integer(USER_PASSWD));
        table.put("eager-release", new Integer(EAGER_RELEASE));
        table.put("batch-mode", new Integer(BATCH_MODE));
        table.put("useAutoCommit", new Integer(USE_AUTOCOMMIT));
        table.put("ignoreAutoCommitExceptions", new Integer(IGNORE_AUTOCOMMIT_EXCEPTION));
        table.put("class-descriptor", new Integer(CLASS_DESCRIPTOR));
        table.put("class", new Integer(CLASS_NAME));
        table.put("proxy", new Integer(CLASS_PROXY));
        table.put("extent-class", new Integer(CLASS_EXTENT));
        table.put("extends", new Integer(EXTENDS));
        table.put("table", new Integer(TABLE_NAME));
        table.put("orderby", new Integer(ORDERBY));
        table.put("conversion", new Integer(FIELD_CONVERSION));
        table.put("row-reader", new Integer(ROW_READER));
        table.put("field-descriptor", new Integer(FIELD_DESCRIPTOR));
        table.put("name", new Integer(FIELD_NAME));
        table.put("column", new Integer(COLUMN_NAME));
        table.put("jdbc-type", new Integer(JDBC_TYPE));
        table.put("primarykey", new Integer(PRIMARY_KEY));
        table.put("autoincrement", new Integer(AUTO_INCREMENT));
        table.put("sequence-name", new Integer(SEQUENCE_NAME));
        table.put("nullable", new Integer(NULLABLE));
        table.put("indexed", new Integer(INDEXED));
        table.put("length", new Integer(LENGTH));
        table.put("precision", new Integer(PRECISION));
        table.put("scale", new Integer(SCALE));
        table.put(TAG_ACCESS, new Integer(ACCESS));

        table.put("reference-descriptor", new Integer(REFERENCE_DESCRIPTOR));
        table.put("class-ref", new Integer(REFERENCED_CLASS));
        table.put("foreignkey", new Integer(FOREIGN_KEY));
        table.put("auto-retrieve", new Integer(AUTO_RETRIEVE));
        table.put("auto-update", new Integer(AUTO_UPDATE));
        table.put("auto-delete", new Integer(AUTO_DELETE));
        table.put("collection-descriptor", new Integer(COLLECTION_DESCRIPTOR));
        table.put("element-class-ref", new Integer(ITEMS_CLASS));
        table.put("inverse-foreignkey", new Integer(INVERSE_FK));
        table.put("collection-class", new Integer(COLLECTION_CLASS));
        table.put("indirection-table", new Integer(INDIRECTION_TABLE));
        table.put("fk-pointing-to-element-class", new Integer(FK_POINTING_TO_ITEMS_CLASS));
        table.put("fk-pointing-to-this-class", new Integer(FK_POINTING_TO_THIS_CLASS));
        table.put("jndi-datasource-name", new Integer(DATASOURCE_NAME));
        table.put("jdbc-level", new Integer(JDBC_LEVEL));
        table.put("locking", new Integer(LOCKING));
        table.put("update-lock", new Integer(UPDATE_LOCK));
        table.put("refresh", new Integer(REFRESH));
        table.put("proxy", new Integer(PROXY_REFERENCE));
        table.put("sort", new Integer(SORT));
        table.put("otm-dependent", new Integer(OTM_DEPENDENT));

        table.put("index-descriptor", new Integer(INDEX_DESCRIPTOR));
        table.put("index-column", new Integer(INDEX_COLUMN));
        table.put("unique", new Integer(UNIQUE));
        table.put("name", new Integer(NAME));

        table.put(PoolConfiguration.MAX_ACTIVE, new Integer(CON_MAX_ACTIVE));
        table.put(PoolConfiguration.MAX_IDLE, new Integer(CON_MAX_IDLE));
        table.put(PoolConfiguration.MAX_WAIT, new Integer(CON_MAX_WAIT));
        table.put(
            PoolConfiguration.MIN_EVICTABLE_IDLE_TIME_MILLIS,
            new Integer(CON_MIN_EVICTABLE_IDLE_TIME_MILLIS));
        table.put(
            PoolConfiguration.NUM_TESTS_PER_EVICTION_RUN,
            new Integer(CON_NUM_TESTS_PER_EVICTION_RUN));
        table.put(PoolConfiguration.TEST_ON_BORROW, new Integer(CON_TEST_ON_BORROW));
        table.put(PoolConfiguration.TEST_ON_RETURN, new Integer(CON_TEST_ON_RETURN));
        table.put(PoolConfiguration.TEST_WHILE_IDLE, new Integer(CON_TEST_WHILE_IDLE));
        table.put(
            PoolConfiguration.TIME_BETWEEN_EVICTION_RUNS_MILLIS,
            new Integer(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS));
        table.put(PoolConfiguration.WHEN_EXHAUSTED_ACTION, new Integer(CON_WHEN_EXHAUSTED_ACTION));
        table.put(PoolConfiguration.VALIDATION_QUERY, new Integer(VALIDATION_QUERY));

        table.put(PoolConfiguration.LOG_ABANDONED, new Integer(CON_LOG_ABANDONED));
        table.put(PoolConfiguration.REMOVE_ABANDONED, new Integer(CON_REMOVE_ABANDONED));
        table.put(
            PoolConfiguration.REMOVE_ABANDONED_TIMEOUT,
            new Integer(CON_REMOVE_ABANDONED_TIMEOUT));

        table.put("connectionFactory", new Integer(CONNECTION_FACTORY));
        table.put("connection-pool", new Integer(CONNECTION_POOL));
        table.put("class-ref", new Integer(CLASS_REF));
        table.put("id", new Integer(ID));
        table.put("field-id-ref", new Integer(FIELD_ID_REF));
        table.put("field-ref", new Integer(FIELD_REF));
        table.put("attribute", new Integer(ATTRIBUTE));
        table.put("attribute-name", new Integer(ATTRIBUTE_NAME));
        table.put("attribute-value", new Integer(ATTRIBUTE_VALUE));
        table.put("documentation", new Integer(DOCUMENTATION));
        table.put("accept-locks", new Integer(ACCEPT_LOCKS));

        table.put("sequence-manager", new Integer(SEQUENCE_MANAGER));
        table.put("className", new Integer(SEQUENCE_MANAGER_CLASS));

        table.put("query-customizer", new Integer(QUERY_CUSTOMIZER));
        table.put("initialization-method", new Integer(INITIALIZATION_METHOD));
        table.put("factory-class", new Integer(FACTORY_CLASS));
        table.put("factory-method", new Integer(FACTORY_METHOD));

        table.put("insert-procedure", new Integer(INSERT_PROCEDURE));
        table.put("update-procedure", new Integer(UPDATE_PROCEDURE));
        table.put("delete-procedure", new Integer(DELETE_PROCEDURE));
        table.put("constant-argument", new Integer(CONSTANT_ARGUMENT));
        table.put("runtime-argument", new Integer(RUNTIME_ARGUMENT));
        table.put("return", new Integer(RETURN));
        table.put("value", new Integer(VALUE));
        table.put("return-field-ref", new Integer(RETURN_FIELD_REF));
        table.put("include-pk-only", new Integer(INCLUDE_PK_FIELDS_ONLY));
        table.put("include-all-fields", new Integer(INCLUDE_ALL_FIELDS));

        table.put("object-cache", new Integer(OBJECT_CACHE));

        table.put("proxy-prefetching-limit", new Integer(PROXY_PREFETCHING_LIMIT));

        // add new tags here !
    }

    /**
     * returns the singleton instance.
     */
    public static RepositoryTags getInstance()
    {
        return instance;
    }

    /**
     * returns the xml-tag literal associated with the repository element with
     * id elementId.
     * @return the resulting tag
     */
    public String getTagById(int elementId)
    {
        return (String) table.getKeyByValue(new Integer(elementId));
    }

    /**
     * returns the opening xml-tag associated with the repository element with
     * id elementId.
     * @return the resulting tag
     */
    public String getOpeningTagById(int elementId)
    {
        return "<" + table.getKeyByValue(new Integer(elementId)) + ">";
    }

    /**
     * returns the opening but non-closing xml-tag
     * associated with the repository element with
     * id elementId.
     * @return the resulting tag
     */
    public String getOpeningTagNonClosingById(int elementId)
    {
        return "<" + table.getKeyByValue(new Integer(elementId));
    }

    /**
     * returns the opening xml-tag associated with the repository element with
     * id elementId.
     * @return the resulting tag
     */
    public String getOpeningTagById(int elementId, String attributes)
    {
        return "<" + table.getKeyByValue(new Integer(elementId)) + " " + attributes + ">";
    }

    /**
     * returns the opening but non-closing xml-tag
     * associated with the repository element with
     * id elementId.
     * @return the resulting tag
     */
    public String getAttribute(int elementId, String value)
    {
        return table.getKeyByValue(new Integer(elementId)) + "=\"" + value + "\"";
    }

    /**
     * returns the closing xml-tag associated with the repository element with
     * id elementId.
     * @return the resulting tag
     */
    public String getClosingTagById(int elementId)
    {
        return "</" + table.getKeyByValue(new Integer(elementId)) + ">";
    }

    /**
     * returns the repository element id associated with the xml-tag
     * literal tag.
     * @return the resulting repository element id.
     * @throws NullPointerException if no value was found for tag
     */
    public int getIdByTag(String tag)
    {
        Integer value = (Integer) table.getValueByKey(tag);
        if (value == null)
            LoggerFactory.getDefaultLogger().error(
                "** " + this.getClass().getName() + ": Tag '" + tag + "' is not defined. **");
        return value.intValue();
    }

    /**
     * returns the opening xml-tag associated with the repository element with
     * id elementId.
     * @return the resulting tag
     */
    public String getCompleteTagById(int elementId, String characters)
    {
        String result = getOpeningTagById(elementId);
        result += characters;
        result += getClosingTagById(elementId);
        return result;
    }
}


text:
var Container = require('./container');
var Optional = require('./optional');

/**
 * A DI container that caches the values once resolved
 * so next time the values are resolved from the cache
 * instead of invoking the factory function/creating the object again.
 * This way we ensure single instance of the dependencies for the current container.
 * @param {Container} parent If present the current container will try the resolve the dependencies from there if not available on the current container.
 * @constructor
 */
module.exports = function(parent) {
    var cache = {};
    var container = new Container(parent);
    var baseResolveCore = container.resolveCore.bind(container);

    return Object.assign(container, {
        resolveCore: function(key) {
            if (key in cache) {
                return Optional.of(cache[key]);
            }

            var result = baseResolveCore(key);
            if (result.hasValue()) {
                cache[key] = result.getValue();
            }

            return result;
        }
    });
};


text:
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// HTTP client. See RFC 2616.
//
// This is the high-level Client interface.
// The low-level implementation is in transport.go.

package httpport

import (
	"crypto/tls"
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/url"
	"strings"
	"sync"
	"time"
)

// A Client is an HTTP client. Its zero value (DefaultClient) is a
// usable client that uses DefaultTransport.
//
// The Client's Transport typically has internal state (cached TCP
// connections), so Clients should be reused instead of created as
// needed. Clients are safe for concurrent use by multiple goroutines.
//
// A Client is higher-level than a RoundTripper (such as Transport)
// and additionally handles HTTP details such as cookies and
// redirects.
type Client struct {
	// Transport specifies the mechanism by which individual
	// HTTP requests are made.
	// If nil, DefaultTransport is used.
	Transport RoundTripper

	// CheckRedirect specifies the policy for handling redirects.
	// If CheckRedirect is not nil, the client calls it before
	// following an HTTP redirect. The arguments req and via are
	// the upcoming request and the requests made already, oldest
	// first. If CheckRedirect returns an error, the Client's Get
	// method returns both the previous Response and
	// CheckRedirect's error (wrapped in a url.Error) instead of
	// issuing the Request req.
	//
	// If CheckRedirect is nil, the Client uses its default policy,
	// which is to stop after 10 consecutive requests.
	CheckRedirect func(req *Request, via []*Request) error

	// Jar specifies the cookie jar.
	// If Jar is nil, cookies are not sent in requests and ignored
	// in responses.
	Jar CookieJar

	// Timeout specifies a time limit for requests made by this
	// Client. The timeout includes connection time, any
	// redirects, and reading the response body. The timer remains
	// running after Get, Head, Post, or Do return and will
	// interrupt reading of the Response.Body.
	//
	// A Timeout of zero means no timeout.
	//
	// The Client cancels requests to the underlying Transport
	// using the Request.Cancel mechanism. Requests passed
	// to Client.Do may still set Request.Cancel; both will
	// cancel the request.
	//
	// For compatibility, the Client will also use the deprecated
	// CancelRequest method on Transport if found. New
	// RoundTripper implementations should use Request.Cancel
	// instead of implementing CancelRequest.
	Timeout time.Duration
}

// DefaultClient is the default Client and is used by Get, Head, and Post.
var DefaultClient = &Client{}

// RoundTripper is an interface representing the ability to execute a
// single HTTP transaction, obtaining the Response for a given Request.
//
// A RoundTripper must be safe for concurrent use by multiple
// goroutines.
type RoundTripper interface {
	// RoundTrip executes a single HTTP transaction, returning
	// a Response for the provided Request.
	//
	// RoundTrip should not attempt to interpret the response. In
	// particular, RoundTrip must return err == nil if it obtained
	// a response, regardless of the response's HTTP status code.
	// A non-nil err should be reserved for failure to obtain a
	// response. Similarly, RoundTrip should not attempt to
	// handle higher-level protocol details such as redirects,
	// authentication, or cookies.
	//
	// RoundTrip should not modify the request, except for
	// consuming and closing the Request's Body.
	//
	// RoundTrip must always close the body, including on errors,
	// but depending on the implementation may do so in a separate
	// goroutine even after RoundTrip returns. This means that
	// callers wanting to reuse the body for subsequent requests
	// must arrange to wait for the Close call before doing so.
	//
	// The Request's URL and Header fields must be initialized.
	RoundTrip(*Request) (*Response, error)
}

// Given a string of the form "host", "host:port", or "[ipv6::address]:port",
// return true if the string includes a port.
func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") }

// refererForURL returns a referer without any authentication info or
// an empty string if lastReq scheme is https and newReq scheme is http.
func refererForURL(lastReq, newReq *url.URL) string {
	// https://tools.ietf.org/html/rfc7231#section-5.5.2
	//   "Clients SHOULD NOT include a Referer header field in a
	//    (non-secure) HTTP request if the referring page was
	//    transferred with a secure protocol."
	if lastReq.Scheme == "https" && newReq.Scheme == "http" {
		return ""
	}
	referer := lastReq.String()
	if lastReq.User != nil {
		// This is not very efficient, but is the best we can
		// do without:
		// - introducing a new method on URL
		// - creating a race condition
		// - copying the URL struct manually, which would cause
		//   maintenance problems down the line
		auth := lastReq.User.String() + "@"
		referer = strings.Replace(referer, auth, "", 1)
	}
	return referer
}

// Used in Send to implement io.ReadCloser by bundling together the
// bufio.Reader through which we read the response, and the underlying
// network connection.
type readClose struct {
	io.Reader
	io.Closer
}

func (c *Client) send(req *Request, deadline time.Time) (*Response, error) {
	if c.Jar != nil {
		for _, cookie := range c.Jar.Cookies(req.URL) {
			req.AddCookie(cookie)
		}
	}
	resp, err := send(req, c.transport(), deadline)
	if err != nil {
		return nil, err
	}
	if c.Jar != nil {
		if rc := resp.Cookies(); len(rc) > 0 {
			c.Jar.SetCookies(req.URL, rc)
		}
	}
	return resp, err
}

// Do sends an HTTP request and returns an HTTP response, following
// policy (e.g. redirects, cookies, auth) as configured on the client.
//
// An error is returned if caused by client policy (such as
// CheckRedirect), or if there was an HTTP protocol error.
// A non-2xx response doesn't cause an error.
//
// When err is nil, resp always contains a non-nil resp.Body.
//
// Callers should close resp.Body when done reading from it. If
// resp.Body is not closed, the Client's underlying RoundTripper
// (typically Transport) may not be able to re-use a persistent TCP
// connection to the server for a subsequent "keep-alive" request.
//
// The request Body, if non-nil, will be closed by the underlying
// Transport, even on errors.
//
// Generally Get, Post, or PostForm will be used instead of Do.
func (c *Client) Do(req *Request) (resp *Response, err error) {
	method := valueOrDefault(req.Method, "GET")
	if method == "GET" || method == "HEAD" {
		return c.doFollowingRedirects(req, shouldRedirectGet)
	}
	if method == "POST" || method == "PUT" {
		return c.doFollowingRedirects(req, shouldRedirectPost)
	}
	return c.send(req, c.deadline())
}

func (c *Client) deadline() time.Time {
	if c.Timeout > 0 {
		return time.Now().Add(c.Timeout)
	}
	return time.Time{}
}

func (c *Client) transport() RoundTripper {
	if c.Transport != nil {
		return c.Transport
	}
	return DefaultTransport
}

// send issues an HTTP request.
// Caller should close resp.Body when done reading from it.
func send(ireq *Request, rt RoundTripper, deadline time.Time) (*Response, error) {
	req := ireq // req is either the original request, or a modified fork

	if rt == nil {
		req.closeBody()
		return nil, errors.New("http: no Client.Transport or DefaultTransport")
	}

	if req.URL == nil {
		req.closeBody()
		return nil, errors.New("http: nil Request.URL")
	}

	if req.RequestURI != "" {
		req.closeBody()
		return nil, errors.New("http: Request.RequestURI can't be set in client requests.")
	}

	// forkReq forks req into a shallow clone of ireq the first
	// time it's called.
	forkReq := func() {
		if ireq == req {
			req = new(Request)
			*req = *ireq // shallow clone
		}
	}

	// Most the callers of send (Get, Post, et al) don't need
	// Headers, leaving it uninitialized.  We guarantee to the
	// Transport that this has been initialized, though.
	if req.Header == nil {
		forkReq()
		req.Header = make(Header)
	}

	if u := req.URL.User; u != nil && req.Header.Get("Authorization") == "" {
		username := u.Username()
		password, _ := u.Password()
		forkReq()
		req.Header = cloneHeader(ireq.Header)
		req.Header.Set("Authorization", "Basic "+basicAuth(username, password))
	}

	if !deadline.IsZero() {
		forkReq()
	}
	stopTimer, wasCanceled := setRequestCancel(req, rt, deadline)

	resp, err := rt.RoundTrip(req)
	if err != nil {
		stopTimer()
		if resp != nil {
			log.Printf("RoundTripper returned a response & error; ignoring response")
		}
		if tlsErr, ok := err.(tls.RecordHeaderError); ok {
			// If we get a bad TLS record header, check to see if the
			// response looks like HTTP and give a more helpful error.
			// See golang.org/issue/11111.
			if string(tlsErr.RecordHeader[:]) == "HTTP/" {
				err = errors.New("http: server gave HTTP response to HTTPS client")
			}
		}
		return nil, err
	}
	if !deadline.IsZero() {
		resp.Body = &cancelTimerBody{
			stop:           stopTimer,
			rc:             resp.Body,
			reqWasCanceled: wasCanceled,
		}
	}
	return resp, nil
}

// setRequestCancel sets the Cancel field of req, if deadline is
// non-zero. The RoundTripper's type is used to determine whether the legacy
// CancelRequest behavior should be used.
func setRequestCancel(req *Request, rt RoundTripper, deadline time.Time) (stopTimer func(), wasCanceled func() bool) {
	if deadline.IsZero() {
		return nop, alwaysFalse
	}

	initialReqCancel := req.Cancel // the user's original Request.Cancel, if any

	cancel := make(chan struct{})
	req.Cancel = cancel

	wasCanceled = func() bool {
		select {
		case <-cancel:
			return true
		default:
			return false
		}
	}

	doCancel := func() {
		// The new way:
		close(cancel)

		// The legacy compatibility way, used only
		// for RoundTripper implementations written
		// before Go 1.5 or Go 1.6.
		type canceler interface {
			CancelRequest(*Request)
		}
		switch v := rt.(type) {
		case *Transport /*, *http2Transport*/ :
			// Do nothing. The net/http package's transports
			// support the new Request.Cancel channel
		case canceler:
			v.CancelRequest(req)
		}
	}

	stopTimerCh := make(chan struct{})
	var once sync.Once
	stopTimer = func() { once.Do(func() { close(stopTimerCh) }) }

	timer := time.NewTimer(deadline.Sub(time.Now()))
	go func() {
		select {
		case <-initialReqCancel:
			doCancel()
		case <-timer.C:
			doCancel()
		case <-stopTimerCh:
			timer.Stop()
		}
	}()

	return stopTimer, wasCanceled
}

// See 2 (end of page 4) http://www.ietf.org/rfc/rfc2617.txt
// "To receive authorization, the client sends the userid and password,
// separated by a single colon (":") character, within a base64
// encoded string in the credentials."
// It is not meant to be urlencoded.
func basicAuth(username, password string) string {
	auth := username + ":" + password
	return base64.StdEncoding.EncodeToString([]byte(auth))
}

// True if the specified HTTP status code is one for which the Get utility should
// automatically redirect.
func shouldRedirectGet(statusCode int) bool {
	switch statusCode {
	case StatusMovedPermanently, StatusFound, StatusSeeOther, StatusTemporaryRedirect:
		return true
	}
	return false
}

// True if the specified HTTP status code is one for which the Post utility should
// automatically redirect.
func shouldRedirectPost(statusCode int) bool {
	switch statusCode {
	case StatusFound, StatusSeeOther:
		return true
	}
	return false
}

// Get issues a GET to the specified URL. If the response is one of
// the following redirect codes, Get follows the redirect, up to a
// maximum of 10 redirects:
//
//    301 (Moved Permanently)
//    302 (Found)
//    303 (See Other)
//    307 (Temporary Redirect)
//
// An error is returned if there were too many redirects or if there
// was an HTTP protocol error. A non-2xx response doesn't cause an
// error.
//
// When err is nil, resp always contains a non-nil resp.Body.
// Caller should close resp.Body when done reading from it.
//
// Get is a wrapper around DefaultClient.Get.
//
// To make a request with custom headers, use NewRequest and
// DefaultClient.Do.
func Get(url string) (resp *Response, err error) {
	return DefaultClient.Get(url)
}

// Get issues a GET to the specified URL. If the response is one of the
// following redirect codes, Get follows the redirect after calling the
// Client's CheckRedirect function:
//
//    301 (Moved Permanently)
//    302 (Found)
//    303 (See Other)
//    307 (Temporary Redirect)
//
// An error is returned if the Client's CheckRedirect function fails
// or if there was an HTTP protocol error. A non-2xx response doesn't
// cause an error.
//
// When err is nil, resp always contains a non-nil resp.Body.
// Caller should close resp.Body when done reading from it.
//
// To make a request with custom headers, use NewRequest and Client.Do.
func (c *Client) Get(url string) (resp *Response, err error) {
	req, err := NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	return c.doFollowingRedirects(req, shouldRedirectGet)
}

func alwaysFalse() bool { return false }

func (c *Client) doFollowingRedirects(ireq *Request, shouldRedirect func(int) bool) (resp *Response, err error) {
	var base *url.URL
	redirectChecker := c.CheckRedirect
	if redirectChecker == nil {
		redirectChecker = defaultCheckRedirect
	}
	var via []*Request

	if ireq.URL == nil {
		ireq.closeBody()
		return nil, errors.New("http: nil Request.URL")
	}

	req := ireq
	deadline := c.deadline()

	urlStr := "" // next relative or absolute URL to fetch (after first request)
	redirectFailed := false
	for redirect := 0; ; redirect++ {
		if redirect != 0 {
			nreq := new(Request)
			nreq.Cancel = ireq.Cancel
			nreq.Method = ireq.Method
			if ireq.Method == "POST" || ireq.Method == "PUT" {
				nreq.Method = "GET"
			}
			nreq.Header = make(Header)
			nreq.URL, err = base.Parse(urlStr)
			if err != nil {
				break
			}
			if len(via) > 0 {
				// Add the Referer header.
				lastReq := via[len(via)-1]
				if ref := refererForURL(lastReq.URL, nreq.URL); ref != "" {
					nreq.Header.Set("Referer", ref)
				}

				err = redirectChecker(nreq, via)
				if err != nil {
					redirectFailed = true
					break
				}
			}
			req = nreq
		}

		urlStr = req.URL.String()
		if resp, err = c.send(req, deadline); err != nil {
			if !deadline.IsZero() && !time.Now().Before(deadline) {
				err = &httpError{
					err:     err.Error() + " (Client.Timeout exceeded while awaiting headers)",
					timeout: true,
				}
			}
			break
		}

		if shouldRedirect(resp.StatusCode) {
			// Read the body if small so underlying TCP connection will be re-used.
			// No need to check for errors: if it fails, Transport won't reuse it anyway.
			const maxBodySlurpSize = 2 << 10
			if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
				io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize)
			}
			resp.Body.Close()
			if urlStr = resp.Header.Get("Location"); urlStr == "" {
				err = fmt.Errorf("%d response missing Location header", resp.StatusCode)
				break
			}
			base = req.URL
			via = append(via, req)
			continue
		}
		return resp, nil
	}

	method := valueOrDefault(ireq.Method, "GET")
	urlErr := &url.Error{
		Op:  method[:1] + strings.ToLower(method[1:]),
		URL: urlStr,
		Err: err,
	}

	if redirectFailed {
		// Special case for Go 1 compatibility: return both the response
		// and an error if the CheckRedirect function failed.
		// See https://golang.org/issue/3795
		return resp, urlErr
	}

	if resp != nil {
		resp.Body.Close()
	}
	return nil, urlErr
}

func defaultCheckRedirect(req *Request, via []*Request) error {
	if len(via) >= 10 {
		return errors.New("stopped after 10 redirects")
	}
	return nil
}

// Post issues a POST to the specified URL.
//
// Caller should close resp.Body when done reading from it.
//
// If the provided body is an io.Closer, it is closed after the
// request.
//
// Post is a wrapper around DefaultClient.Post.
//
// To set custom headers, use NewRequest and DefaultClient.Do.
func Post(url string, bodyType string, body io.Reader) (resp *Response, err error) {
	return DefaultClient.Post(url, bodyType, body)
}

// Post issues a POST to the specified URL.
//
// Caller should close resp.Body when done reading from it.
//
// If the provided body is an io.Closer, it is closed after the
// request.
//
// To set custom headers, use NewRequest and Client.Do.
func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error) {
	req, err := NewRequest("POST", url, body)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", bodyType)
	return c.doFollowingRedirects(req, shouldRedirectPost)
}

// PostForm issues a POST to the specified URL, with data's keys and
// values URL-encoded as the request body.
//
// The Content-Type header is set to application/x-www-form-urlencoded.
// To set other headers, use NewRequest and DefaultClient.Do.
//
// When err is nil, resp always contains a non-nil resp.Body.
// Caller should close resp.Body when done reading from it.
//
// PostForm is a wrapper around DefaultClient.PostForm.
func PostForm(url string, data url.Values) (resp *Response, err error) {
	return DefaultClient.PostForm(url, data)
}

// PostForm issues a POST to the specified URL,
// with data's keys and values URL-encoded as the request body.
//
// The Content-Type header is set to application/x-www-form-urlencoded.
// To set other headers, use NewRequest and DefaultClient.Do.
//
// When err is nil, resp always contains a non-nil resp.Body.
// Caller should close resp.Body when done reading from it.
func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {
	return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}

// Head issues a HEAD to the specified URL.  If the response is one of
// the following redirect codes, Head follows the redirect, up to a
// maximum of 10 redirects:
//
//    301 (Moved Permanently)
//    302 (Found)
//    303 (See Other)
//    307 (Temporary Redirect)
//
// Head is a wrapper around DefaultClient.Head
func Head(url string) (resp *Response, err error) {
	return DefaultClient.Head(url)
}

// Head issues a HEAD to the specified URL.  If the response is one of the
// following redirect codes, Head follows the redirect after calling the
// Client's CheckRedirect function:
//
//    301 (Moved Permanently)
//    302 (Found)
//    303 (See Other)
//    307 (Temporary Redirect)
func (c *Client) Head(url string) (resp *Response, err error) {
	req, err := NewRequest("HEAD", url, nil)
	if err != nil {
		return nil, err
	}
	return c.doFollowingRedirects(req, shouldRedirectGet)
}

// cancelTimerBody is an io.ReadCloser that wraps rc with two features:
// 1) on Read error or close, the stop func is called.
// 2) On Read failure, if reqWasCanceled is true, the error is wrapped and
//    marked as net.Error that hit its timeout.
type cancelTimerBody struct {
	stop           func() // stops the time.Timer waiting to cancel the request
	rc             io.ReadCloser
	reqWasCanceled func() bool
}

func (b *cancelTimerBody) Read(p []byte) (n int, err error) {
	n, err = b.rc.Read(p)
	if err == nil {
		return n, nil
	}
	b.stop()
	if err == io.EOF {
		return n, err
	}
	if b.reqWasCanceled() {
		err = &httpError{
			err:     err.Error() + " (Client.Timeout exceeded while reading body)",
			timeout: true,
		}
	}
	return n, err
}

func (b *cancelTimerBody) Close() error {
	err := b.rc.Close()
	b.stop()
	return err
}


text:
namespace NodeBinding
{
    class WebGLProgram : public Napi::ObjectWrap<WebGLProgram>
    {
    public:
        WebGLProgram(const Napi::CallbackInfo &info);
        static void Init(Napi::Env env);
        static Napi::Object NewInstance(Napi::Env env, const Napi::Value arg);
        inline GLuint getId() const { return mId; }

    private:
        GLuint mId = 0;
        static Napi::FunctionReference constructor;
    };
} // namespace NodeBinding
#endif


text:
import argparse
import datetime
import os

import numpy as np
import h5py

def getListOfFiles(dirName):
    listOfFiles = os.listdir(dirName)
    allFiles = list()

    for entry in listOfFiles:
        fullPath = os.path.join(dirName, entry)
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(fullPath)

    return allFiles

def load_hdf5(filename):
    """
    load training samples from *.hdf5 file
    """
    if not(os.path.exists(filename)):
        print("file:", filename, "does not exist")
        os._exit(1)
    if os.path.splitext(filename)[1] != '.h5':
        print("file:", filename, "is not an hdf5 file")
        os._exit(1)

    h5_file = h5py.File(filename, 'r')
    values = list(h5_file.values())[0]
    print("load data size:", values.shape[0])
    return values

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='generate training samples\
            from a specified directory')
    parser.add_argument('directory', type=str,
                        help='directory contains feature files in .h5')
    parser.add_argument('-n', '--npy', action='store_true',
                        help='if is .npy rather than .h5, use this.')
    args = parser.parse_args()
    path = args.directory

    if not args.npy:
        print("load h5 from directory: {}".format(path))
        if os.path.isdir(path):
            features = None
            labels = None

            h5_files = getListOfFiles(path)
            print("Total number of files:", len(h5_files))
            for i, h5_file in enumerate(h5_files):
                print("Process File", i, ":", h5_file)
                feature = load_hdf5(h5_file)
                if np.any(np.isinf(feature)):
                    print("inf data found")
                features = np.concatenate((features, feature), axis=0) if features is not None \
                    else feature
        else:
            print("Fail to find", path)
            os._exit(-1)

        date = datetime.datetime.now().strftime('%Y-%m-%d')
        sample_file = path + '/merged' + date + '.h5'
        print("Save samples file to:", sample_file)
        h5_file = h5py.File(sample_file, 'w')
        h5_file.create_dataset('data', data=features)
        h5_file.close()
    else:
        print("load npy from directory: {}".format(path))
        if os.path.isdir(path):
            features_go = None
            features_cutin = None
            npy_files = getListOfFiles(path)
            print("Total number of files:", len(npy_files))
            for i, npy_file in enumerate(npy_files):
                print("Process File", i, ":", npy_file)
                temp_features = np.load(npy_file)
                feature_go = np.zeros((temp_features.shape[0], 157))
                feature_cutin = np.zeros((temp_features.shape[0], 157))
                count_go = 0
                count_cutin = 0
                for j in range(temp_features.shape[0]):
                    fea = np.asarray(temp_features[j])
                    if fea.shape[0] != 157:
                        continue
                    if fea[-1] < -1 or fea[-1] > 4:
                        continue
                    fea = fea.reshape((1, 157))
                    if fea[0, -1] % 2 == 0:
                        feature_go[count_go] = fea
                        count_go += 1
                    else:
                        feature_cutin[count_cutin] = fea
                        count_cutin += 1

                feature_go = feature_go[:count_go]
                feature_cutin = feature_cutin[:count_cutin]
                features_go = np.concatenate((features_go, feature_go), axis=0) if features_go is not None \
                    else feature_go
                features_cutin = np.concatenate((features_cutin, feature_cutin), axis=0) if features_cutin is not None \
                    else feature_cutin
        else:
            print("Fail to find", path)
            os._exit(-1)

        print(features_go.shape)
        print(features_cutin.shape)
        date = datetime.datetime.now().strftime('%Y-%m-%d')
        sample_file_go = path + '/merged_go_' + date + '.h5'
        sample_file_cutin = path + '/merged_cutin_' + date + '.h5'
        h5_file_go = h5py.File(sample_file_go, 'w')
        h5_file_go.create_dataset('data', data=features_go)
        h5_file_go.close()
        h5_file_cutin = h5py.File(sample_file_cutin, 'w')
        h5_file_cutin.create_dataset('data', data=features_cutin)
        h5_file_cutin.close()


text:
@implementation IntNegation

- (id) initWith: (id <IntExpression>) expression {
    if (self = [super init]) {
        self.expression = expression;
    }
    return self;
}

-(int) evaluateAgainst:(EnvironmentModel *)environment {

    int theValue = [self.expression evaluateAgainst:environment];
    if ([ProgramException checkExceptionWithEnvironment:environment andIdentifier:@"IntNegation Expression"])
        return 0;

    return -theValue;

}

- (void) accept:(id <ExpressionVisitor>)visitor {
    [visitor visitIntNegation:self];
}

@end


text:
using System;
using Xunit;
using Codetasy.Cli;
using System.Collections.Generic;
using System.IO;

namespace Codetasy.Cli.Tests
{
    public class IntegrationTest
    {
        [Fact]
        public void Main()
        {
            using (StringWriter sw = new StringWriter())
            {
                Console.SetOut(sw);

                var arguments = new [] {"goodbye", "name=Frodo"};
                new Cli(arguments).Run(this);

                Assert.Equal("Bye Frodo!", sw.ToString());
            }
        }
    }
}


text:
def format_float(x, size=8, lr='>'):
    """Format a float number

    Parameters
    ----------
    x : float
        The float number.
    size : int, optional
        Desired size of the output string.
    lr : str ('<' or '>')
        Indicates if it should be left or right aligned.

    Returns
    -------
    out : str
        The formatted string.

    """
    y = str(x)
    if '.' in y:
        has_floating_point = True
    else:
        has_floating_point = False
    if lr == '<':
        y = y.ljust(size)[:size]
    elif lr == '>':
        y = y.rjust(size)[:size]
    else:
        raise ValueError("`lr` must be '<' or '>'")
    if not '.' in y and has_floating_point:
        raise ValueError('Float %f does not fit in size = %d' % (x, size))
    return y