text:
<?php

namespace DagbestedingBundle\Form;

use AppBundle\Form\BaseType;
use DagbestedingBundle\Entity\Resultaatgebiedsoort;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ResultaatgebiedsoortType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('naam')
            ->add('actief')
            ->add('submit', SubmitType::class, ['label' => 'Opslaan'])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Resultaatgebiedsoort::class,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return BaseType::class;
    }
}


text:
local playerTag = { }
addEventHandler ( "onPlayerMute", root, function ( )
	if ( isElement ( playerTag[source] ) ) then
		destroyElement ( playerTag[source] )
		playerTag[source] = nil
	end

	playerTag[source] = exports['NGJobs']:create3DText ( "[MUTED]", { 0, 0, 0 }, { 255, 0, 0 }, source, { 5 } )
end )

addEventHandler ( 'onPlayerUnmute', root, function ( )
	if ( isElement ( playerTag[source] ) ) then
		destroyElement ( playerTag[source] )
		playerTag[source] = nil
	end
end )

addEventHandler ( "onPlayerQuit", root, function ( ) if ( isElement ( playerTag[source] ) ) then destroyElement ( playerTag[source] ) end end )
addEventHandler ( "onResourceStop", resourceRoot, function ( ) for i, v in pairs ( playerTag ) do  if ( isElement ( v ) ) then destroyElement ( v ) end end end )
addEventHandler ( "onResourceStart", resourceRoot, function ( ) for i, v in ipairs ( getElementsByType ( 'player' ) ) do  if ( isPlayerMuted ( v ) ) then playerTag[v] = exports['NGJobs']:create3DText ( "[MUTED]", { 0, 0, 0 }, { 255, 0, 0 }, source, { 5 } ) end end end )

redpajama_set_name: RedPajamaGithub


text: ActionView::Base.send(:include, Canonical::CanonicalHelper)


text:
	<a href="<?= $predecessorURL; ?>"  class="btn btn-default">Zurück
	<input type="submit" value="Weiter" class="btn btn-info" />


text:
import codecs
import os
import re

from setuptools import find_packages, setup

###################################################################

NAME = "django-materializecss-form"
PACKAGES = find_packages()
META_PATH = os.path.join("materializecssform", "meta.py")
KEYWORDS = ["materialize", "django", "css", "materializecss", "django forms"]
CLASSIFIERS = [
    "Development Status :: 5 - Production/Stable",
    "Framework :: Django",
    "Intended Audience :: Developers",
    "Natural Language :: English",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
    "Programming Language :: Python",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.4",
    "Programming Language :: Python :: 3.5",
    "Programming Language :: Python :: 3.6",
    "Programming Language :: Python :: 3.7",
    "Programming Language :: Python :: 3.8",
    "Programming Language :: Python :: Implementation :: CPython",
    "Programming Language :: Python :: Implementation :: PyPy",
    "Topic :: Software Development :: Libraries :: Python Modules",
]
INSTALL_REQUIRES = []

###################################################################

HERE = os.path.abspath(os.path.dirname(__file__))

def read(*parts):
    """
    Build an absolute path from *parts* and and return the contents of the
    resulting file.  Assume UTF-8 encoding.
    """
    with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f:
        return f.read()

META_FILE = read(META_PATH)

def find_meta(meta):
    """
    Extract __*meta*__ from META_FILE.
    """
    meta_match = re.search(
        r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M
    )
    if meta_match:
        return meta_match.group(1)
    raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))

if __name__ == "__main__":
    setup(
        name=NAME,
        description=find_meta("description"),
        license=find_meta("license"),
        url=find_meta("uri"),
        version=find_meta("version"),
        author=find_meta("author"),
        author_email=find_meta("email"),
        maintainer=find_meta("author"),
        maintainer_email=find_meta("email"),
        keywords=KEYWORDS,
        long_description=read("README.md"),
        long_description_content_type="text/markdown",
        packages=PACKAGES,
        zip_safe=False,
        classifiers=CLASSIFIERS,
        install_requires=INSTALL_REQUIRES,
        options={"bdist_wheel": {"universal": "1"}},
        include_package_data=True,
    )


text:
<?php

namespace Misd\GuzzleBundle\Tests\Functional;

use Misd\GuzzleBundle\Request\ParamConverter\GuzzleParamConverter3x;

class GuzzleParamConverter3xTest extends AbstractGuzzleParamConverterTest
{
    public function setUp()
    {
        // skip the test if the installed version of SensioFrameworkExtraBundle
        // is not compatible with the GuzzleParamConverter3x class
        $parameter = new \ReflectionParameter(
            array(
                'Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface',
                'supports',
            ),
            'configuration'
        );
        if ('Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter' != $parameter->getClass()->getName()) {
            $this->markTestSkipped(
                'skipping GuzzleParamConverter3xTest due to an incompatible version of the SensioFrameworkExtraBundle'
            );
        }

        $this->converter = new GuzzleParamConverter3x();

        parent::setUp();
    }
}


text:
'use strict';

/* Animations */

define(['angular', 'jquery', 'angular-animate'],function(angular, $){
    return angular.module('phonecatAnimations', ['ngAnimate']).animation('.phone', function() {

        var animateUp = function(element, className, done) {
            if(className !== 'active') {
                return;
            }
            element.css({
                position: 'absolute',
                top: 500,
                left: 0,
                display: 'block'
            });

            $(element).animate({
                top: 0
            }, done);

            return function(cancel) {
                if(cancel && element.stop) {
                    element.stop();
                }
            };
        };

        var animateDown = function(element, className, done) {
            if(className !== 'active') {
                return;
            }
            element.css({
                position: 'absolute',
                left: 0,
                top: 0
            });

            $(element).animate({
                top: -500
            }, done);

            return function(cancel) {
                if(cancel && element.stop) {
                    element.stop();
                }
            };
        };

        return {
            addClass: animateUp,
            removeClass: animateDown
        };
    });
});


text:
#include <string.h>
#include <zephyr/logging/log.h>

#include "psa/error.h"
#include "psa/protected_storage.h"
#include "util_app_cfg.h"
#include "util_app_log.h"

/** The 64-bit UID associated with the config record in secure storage. */
static psa_storage_uid_t cfg_data_uid = 0x0000000055CFDA7A;

LOG_MODULE_DECLARE(app, CONFIG_LOG_DEFAULT_LEVEL);

/**
 * @brief Default config settings. These settings will be used when a new
 *        config record is created, or when the config record is reset.
 */
static struct cfg_data cfg_data_dflt = {
	.magic = 0x55CFDA7A,
	.version = 1,
	.scratch = { 0 }
};

psa_status_t cfg_create_data(void)
{
	psa_status_t status;

	LOG_INF("app_cfg: Creating new config file with UID 0x%llX",
		(uint64_t)cfg_data_uid);

	/*
	 * psa_ps_create can also be used here, which enables to the use of
	 * the psa_ps_set_extended function, but this requires us to set a
	 * maximum file size for resource allocation. Since the upper limit
	 * isn't known at present, we opt here for the simpler psa_ps_set
	 * call which also creates the secure storage record if necessary,
	 * but precludes the use of psa_ps_set_extended.
	 */
	status = psa_ps_set(cfg_data_uid, sizeof(cfg_data_dflt),
			    (void *)&cfg_data_dflt, 0);
	if (status) {
		goto err;
	}

err:
	return (status ? al_psa_status(status, __func__) : status);
}

psa_status_t cfg_load_data(struct cfg_data *p_cfg_data)
{
	psa_status_t status;
	struct psa_storage_info_t p_info;

	memset(&p_info, 0, sizeof(p_info));

	/* Check if the config record exists, if not create it. */
	status = psa_ps_get_info(cfg_data_uid, &p_info);
	if (status == PSA_ERROR_DOES_NOT_EXIST) {
		/* Create a new config file. */
		status = cfg_create_data();
		/* Copy default values to the cfg_data placeholder. */
		memcpy(p_cfg_data, &cfg_data_dflt, sizeof(cfg_data_dflt));
	}
	if (status) {
		goto err;
	}

err:
	return (status ? al_psa_status(status, __func__) : status);
}


text:
package com.linecorp.armeria.internal.logging;

import static com.linecorp.armeria.internal.logging.ContentPreviewingUtil.setUpRequestContentPreviewer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;

import org.junit.jupiter.api.Test;

import com.linecorp.armeria.common.HttpData;
import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.HttpRequestWriter;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.common.RequestHeaders;
import com.linecorp.armeria.common.logging.ContentPreviewer;
import com.linecorp.armeria.common.logging.ContentPreviewerFactory;
import com.linecorp.armeria.common.logging.RequestLog;
import com.linecorp.armeria.common.logging.RequestLogProperty;
import com.linecorp.armeria.common.util.Functions;
import com.linecorp.armeria.server.ServiceRequestContext;

class ContentPreviewingUtilTest {

    @Test
    void abortedRequestShouldAlsoBeCompleted() {
        final HttpRequestWriter req = HttpRequest.streaming(RequestHeaders.builder(HttpMethod.POST, "/")
                                                                          .contentType(MediaType.PLAIN_TEXT)
                                                                          .build());
        req.write(HttpData.ofUtf8("Armeria"));
        req.abort(new RuntimeException());
        final ServiceRequestContext ctx = ServiceRequestContext.of(req);

        final ContentPreviewer contentPreviewer =
                ContentPreviewerFactory.text(1024).requestContentPreviewer(ctx, req.headers());

        final HttpRequest filteredReq = setUpRequestContentPreviewer(ctx, req,
                                                                     contentPreviewer,
                                                                     Functions.second());
        assertThat(ctx.logBuilder().isDeferred(RequestLogProperty.REQUEST_CONTENT_PREVIEW)).isTrue();

        try {
            filteredReq.aggregate().join();
            fail("aborted request should fail aggregate().join()");
        } catch (Exception e) {
            // ignored
        }

        ctx.logBuilder().endRequest();
        ctx.logBuilder().endResponse();
        ctx.logBuilder().ensureComplete();

        final RequestLog log = ctx.log().whenComplete().join();
        assertThat(log.requestContentPreview()).isEmpty();
    }
}


text:
Framework for integration testing an API server.

## Installation

Add this line to your application's Gemfile:

    gem 'api-validator'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install api-validator

## Usage

```ruby
class MyValidation < ApiValidator::Spec

  def create_resource
    # ...
    set(:resource, data)
  end

  def fudge_resource
    # ...
    set(:resource, fudged_data)
  end

  describe "GET /posts/{entity}/{id}" do
    shared_examples :not_found do
      expect_response(:schema => :error, :status => 404) do
        # ...
        response
      end
    end

    context "when resource exists", :before => :create_resource do
      context "when authorized to read all posts" do
        authorize!(:server => :remote, :scopes => %w[ read_posts ], :read_types => %w[ all ])

        expect_response(:schema => :post, :status => 200) do
          expect_headers({ 'Content-Type' => /json\b/ })
          expect_properties(:entity => get(:resource, :entity), :id => get(:resource, :id))
          expect_schema(:post_content, "/content")

          # ...
          response
        end
      end

      context "when authorize to write resource but not read" do
        authorize!(:server => :remote, :scopes => %w[ write_posts ], :write_types => %w[ all ])
        behaves_as :not_found
      end

      context "when not authorized" do
        behaves_as :not_found
      end
    end

    context "when resource does not exist", :before => :fudge_resource do
      behaves_as :not_found
    end
  end

end
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package com.ocdsoft.bacta.swg.precu.message;

/**
 * Created by crush on 8/13/2014.
 */
public class UpdatePvpStatusMessage {
    //int flags
    //int factionId
    //NetworkId target
}


text:
name: heady-topper-clone
layout: post
title: Heady Topper clone v0.1
date: 2015-02-05
author: Scott Chamberlain
datemadeon: 2015-02-05
volume: 5
gravity_one: 1.xx
gravity_two: 1.xx
datesecondferm: 2015-01-xx
datebottled: 2015-01-xx
categories:
- todo
tags:
- ale
- clone
- todo
---

* http://www.homebrewtalk.com/f12/heady-topper-can-you-clone-390082/
* http://www.farmhousebrewingsupply.com/heady-topper-clone-all-grain/
* http://www.bear-flavored.com/2013/08/brewing-heady-topper-clone-recipe-group.html
* http://www.reddit.com/r/Homebrewing/comments/2jftip/heady_topper_clone/


text:
import pytest
import os.path
from processfile.decoders.json_decoder import JSONFileDecoder

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))

def test_json_correct():
    '''Test the decoding when a correct file is given'''

    decoder = JSONFileDecoder(os.path.join(CURRENT_DIR, 'correct.json'))
    assert len(decoder.get_employees()) == 3

def test_json_bad_format():

    decoder = JSONFileDecoder(os.path.join(CURRENT_DIR, 'bad_format.json'))
    with pytest.raises(Exception):
        decoder.get_employees()

def test_json_not_found():

    with pytest.raises(Exception):
        JSONFileDecoder(os.path.join(CURRENT_DIR, 'not_found.json'))


text:
export SRCDIR=`dirname $0`
. `dirname $0`/setup-env.sh

# pass a single test name as the first paramter (without .tpgk extension)
ONE_TEST=$1
shift

"${TPKG}" $* exe ${SRCDIR}/${ONE_TEST}.tpkg


text:
using namespace xbox::httpclient;

const int MIN_DELAY_FOR_HTTP_INTERNAL_ERROR_IN_MS = 10000;
#if HC_UNITTEST_API
    const int MIN_HTTP_TIMEOUT_IN_MS = 0; // speed up unit tests
#else
    const int MIN_HTTP_TIMEOUT_IN_MS = 5000;
#endif
const double MAX_DELAY_TIME_IN_SEC = 60.0;
const int RETRY_AFTER_CAP_IN_SEC = 15;
#define RETRY_AFTER_HEADER ("Retry-After")

HC_CALL::~HC_CALL()
{
    HC_TRACE_VERBOSE(HTTPCLIENT, "HCCallHandle dtor");
}

STDAPI
HCHttpCallCreate(
    _Out_ HCCallHandle* callHandle
    ) noexcept
try
{
    if (callHandle == nullptr)
    {
        return E_INVALIDARG;
    }

    auto httpSingleton = get_http_singleton();
    if (nullptr == httpSingleton)
        return E_HC_NOT_INITIALISED;

    HC_CALL* call = Make<HC_CALL>();
    if (call == nullptr)
    {
        return E_OUTOFMEMORY;
    }
    call->retryAllowed = httpSingleton->m_retryAllowed;
    call->timeoutInSeconds = httpSingleton->m_timeoutInSeconds;
    call->timeoutWindowInSeconds = httpSingleton->m_timeoutWindowInSeconds;
    call->retryDelayInSeconds = httpSingleton->m_retryDelayInSeconds;
    call->retryIterationNumber = 0;
    call->id = ++httpSingleton->m_lastId;

    HC_TRACE_INFORMATION(HTTPCLIENT, "HCHttpCallCreate [ID %llu]", call->id);

    *callHandle = call;
    return S_OK;
}
CATCH_RETURN()

STDAPI_(HCCallHandle) HCHttpCallDuplicateHandle(
    _In_ HCCallHandle call
    ) noexcept
try
{
    if (call == nullptr)
    {
        return nullptr;
    }

    HC_TRACE_INFORMATION(HTTPCLIENT, "HCHttpCallDuplicateHandle [ID %llu]", static_cast<HC_CALL*>(call)->id);
    ++call->refCount;

    return call;
}
CATCH_RETURN_WITH(nullptr)

STDAPI
HCHttpCallCloseHandle(
    _In_ HCCallHandle call
    ) noexcept
try
{
    if (call == nullptr)
    {
        return E_INVALIDARG;
    }

    HC_TRACE_INFORMATION(HTTPCLIENT, "HCHttpCallCloseHandle [ID %llu]", call->id);
    int refCount = --call->refCount;
    if (refCount <= 0)
    {
        ASSERT(refCount == 0); // should only fire at 0
        Delete(call);
    }

    return S_OK;
}
CATCH_RETURN()

HRESULT perform_http_call(
    _In_ std::shared_ptr<http_singleton> httpSingleton,
    _In_ HCCallHandle call,
    _Inout_ XAsyncBlock* asyncBlock
    )
{
    HRESULT hr = XAsyncBegin(asyncBlock, call, reinterpret_cast<void*>(perform_http_call), __FUNCTION__,
        [](XAsyncOp opCode, const XAsyncProviderData* data)
    {
        auto httpSingleton = get_http_singleton();
        if (nullptr == httpSingleton)
        {
            return E_HC_NOT_INITIALISED;
        }

        switch (opCode)
        {
            case XAsyncOp::DoWork:
            {
                HCCallHandle call = static_cast<HCCallHandle>(data->context);
                bool matchedMocks = false;

                matchedMocks = Mock_Internal_HCHttpCallPerformAsync(call);
                if (matchedMocks)
                {
                    XAsyncComplete(data->async, S_OK, 0);
                }
                else // if there wasn't a matched mock, then real call
                {
                    HttpPerformInfo const& info = httpSingleton->m_httpPerform;
                    if (info.handler != nullptr)
                    {
                        try
                        {
                            info.handler(call, data->async, info.context, httpSingleton->m_performEnv.get());
                        }
                        catch (...)
                        {
                            if (call->traceCall) { HC_TRACE_ERROR(HTTPCLIENT, "HCHttpCallPerform [ID %llu]: failed", static_cast<HC_CALL*>(call)->id); }
                        }
                    }
                }

                return E_PENDING;
            }

            default: return S_OK;
        }
    });

    if (SUCCEEDED(hr))
    {
        uint32_t delayInMilliseconds = static_cast<uint32_t>(call->delayBeforeRetry.count());
        hr = XAsyncSchedule(asyncBlock, delayInMilliseconds);
    }

    return hr;
}

void clear_http_call_response(_In_ HCCallHandle call)
{
    call->responseString.clear();
    call->responseBodyBytes.clear();
    call->responseHeaders.clear();
    call->statusCode = 0;
    call->networkErrorCode = S_OK;
    call->platformNetworkErrorCode = 0;
    call->task.reset();
}

std::chrono::seconds GetRetryAfterHeaderTime(_In_ HC_CALL* call)
{
    auto it = call->responseHeaders.find(RETRY_AFTER_HEADER);
    if (it != call->responseHeaders.end())
    {
        int value = 0;
        http_internal_stringstream ss(it->second);
        ss >> value;

        if (!ss.fail())
        {
            if (value > RETRY_AFTER_CAP_IN_SEC)
            {
                // Cap the Retry-After header so users won't be locked out of an endpoint
                // for a long time the limit is hit near the end of a period
                value = RETRY_AFTER_CAP_IN_SEC;
            }

            return std::chrono::seconds(value);
        }
    }

    return std::chrono::seconds(0);
}

bool http_call_should_retry(
    _In_ HCCallHandle call,
    _In_ const chrono_clock_t::time_point& responseReceivedTime)
{
    if (!call->retryAllowed)
    {
        return false;
    }

    if (call->networkErrorCode == E_HC_NO_NETWORK)
    {
        return false;
    }

    auto httpStatus = call->statusCode;

    if (httpStatus == 408 || // Request Timeout
        httpStatus == 429 || // Too Many Requests
        httpStatus == 500 || // Internal Error
        httpStatus == 502 || // Bad Gateway
        httpStatus == 503 || // Service Unavailable
        httpStatus == 504 || // Gateway Timeout
        call->networkErrorCode != S_OK)
    {
        std::chrono::milliseconds retryAfter = GetRetryAfterHeaderTime(call);

        // Compute how much time left before hitting the TimeoutWindow setting
        std::chrono::milliseconds timeElapsedSinceFirstCall = std::chrono::duration_cast<std::chrono::milliseconds>(responseReceivedTime - call->firstRequestStartTime);

        uint32_t timeoutWindowInSeconds = 0;
        HCHttpCallRequestGetTimeoutWindow(call, &timeoutWindowInSeconds);
        std::chrono::seconds timeoutWindow = std::chrono::seconds(timeoutWindowInSeconds);
        std::chrono::milliseconds remainingTimeBeforeTimeout = timeoutWindow - timeElapsedSinceFirstCall;
        if (call->traceCall) { HC_TRACE_INFORMATION(HTTPCLIENT, "HCHttpCallPerformExecute [ID %llu] remainingTimeBeforeTimeout %lld ms", call->id, remainingTimeBeforeTimeout.count()); }

        // Based on the retry iteration, delay 2,4,8,16,etc seconds by default between retries
        // Jitter the response between the current and next delay based on system clock
        // Max wait time is 1 minute
        uint32_t retryDelayInSeconds = 0;
        HCHttpCallRequestGetRetryDelay(call, &retryDelayInSeconds);
        double secondsToWaitMin = std::pow(retryDelayInSeconds, call->retryIterationNumber);
        double secondsToWaitMax = std::pow(retryDelayInSeconds, call->retryIterationNumber + 1);
        double secondsToWaitDelta = secondsToWaitMax - secondsToWaitMin;
        double lerpScaler = (responseReceivedTime.time_since_epoch().count() % 10000) / 10000.0; // from 0 to 1 based on clock
#if HC_UNITTEST_API
        lerpScaler = 0; // make unit tests deterministic
#endif
        double secondsToWaitUncapped = secondsToWaitMin + secondsToWaitDelta * lerpScaler; // lerp between min & max wait
        double secondsToWait = std::min(secondsToWaitUncapped, MAX_DELAY_TIME_IN_SEC); // cap max wait to 1 min
        std::chrono::milliseconds waitTime = std::chrono::milliseconds(static_cast<int64_t>(secondsToWait * 1000.0));
        if (retryAfter.count() > 0)
        {
            // Use either the waitTime or Retry-After header, whichever is bigger
            call->delayBeforeRetry = std::chrono::milliseconds(std::max(waitTime.count(), retryAfter.count()));
        }
        else
        {
            call->delayBeforeRetry = waitTime;
        }
        if (call->traceCall) { HC_TRACE_INFORMATION(HTTPCLIENT, "HCHttpCallPerformExecute [ID %llu] delayBeforeRetry %lld ms", call->id, call->delayBeforeRetry.count()); }

        // Remember result if there was an error and there was a Retry-After header
        if (call->retryAfterCacheId != 0 &&
            retryAfter.count() > 0 &&
            httpStatus > 400)
        {
            auto retryAfterTime = retryAfter + responseReceivedTime;
            http_retry_after_api_state state(retryAfterTime, httpStatus);
            auto httpSingleton = get_http_singleton();
            if (httpSingleton)
            {
                httpSingleton->set_retry_state(call->retryAfterCacheId, state);
            }
        }

        if (httpStatus == 500) // Internal Error
        {
            // For 500 - Internal Error, wait at least 10 seconds before retrying.
            if (call->delayBeforeRetry.count() < MIN_DELAY_FOR_HTTP_INTERNAL_ERROR_IN_MS)
            {
                call->delayBeforeRetry = std::chrono::milliseconds(MIN_DELAY_FOR_HTTP_INTERNAL_ERROR_IN_MS);
            }
        }

        if (remainingTimeBeforeTimeout.count() <= MIN_HTTP_TIMEOUT_IN_MS)
        {
            // Need at least 5 seconds to bother making a call
            return false;
        }

        if (remainingTimeBeforeTimeout < call->delayBeforeRetry + std::chrono::milliseconds(MIN_HTTP_TIMEOUT_IN_MS))
        {
            // Don't bother retrying when out of time
            return false;
        }

        return true;
    }

    return false;
}

bool should_fast_fail(
    _In_ http_retry_after_api_state apiState,
    _In_ HC_CALL* call,
    _In_ const chrono_clock_t::time_point& currentTime,
    _Out_ bool* clearState
    )
{
    *clearState = false;

    if (apiState.statusCode < 400)
    {
        return false;
    }

    std::chrono::milliseconds remainingTimeBeforeRetryAfterInMS = std::chrono::duration_cast<std::chrono::milliseconds>(apiState.retryAfterTime - currentTime);
    if (remainingTimeBeforeRetryAfterInMS.count() <= 0)
    {
        // Only clear the API cache when Retry-After time is up
        *clearState = true;
        return false;
    }

    std::chrono::seconds timeoutWindowInSeconds = std::chrono::seconds(call->timeoutWindowInSeconds);
    chrono_clock_t::time_point timeoutTime = call->firstRequestStartTime + timeoutWindowInSeconds;

    // If the Retry-After will happen first, just wait till Retry-After is done, and don't fast fail
    if (apiState.retryAfterTime < timeoutTime)
    {
        call->delayBeforeRetry = remainingTimeBeforeRetryAfterInMS;
        return false;
    }
    else
    {
        return true;
    }
}

class HcCallWrapper
{
public:
    HcCallWrapper(_In_ HC_CALL* call)
    {
        assert(call != nullptr);
        if (call != nullptr)
        {
            m_call = HCHttpCallDuplicateHandle(call);
        }
    }

    ~HcCallWrapper()
    {
        if (m_call)
        {
            HCHttpCallCloseHandle(m_call);
        }
    }

    HC_CALL* get()
    {
        return m_call;
    }

private:
    HC_CALL* m_call{ nullptr };
};

typedef struct retry_context
{
    std::shared_ptr<HcCallWrapper> call;
    XAsyncBlock* outerAsyncBlock;
    XTaskQueueHandle outerQueue;
} retry_context;

void notify_call_routed_handlers(std::shared_ptr<http_singleton> httpSingleton, HC_CALL* call)
{
    std::lock_guard<std::recursive_mutex> lock(httpSingleton->m_callRoutedHandlersLock);
    for (const auto& pair : httpSingleton->m_callRoutedHandlers)
    {
        pair.second.first(call, pair.second.second);
    }
}

void retry_http_call_until_done(
    _In_ HC_UNIQUE_PTR<retry_context> retryContext
    )
{
    auto httpSingleton = get_http_singleton();
    if (nullptr == httpSingleton)
    {
        HC_TRACE_WARNING(HTTPCLIENT, "Http call after HCCleanup was called. Aborting call.");
        XAsyncComplete(retryContext->outerAsyncBlock, E_HC_NOT_INITIALISED, 0);
        return;
    }

    auto requestStartTime = chrono_clock_t::now();
    HC_CALL* call = retryContext->call->get();
    if (call->retryIterationNumber == 0)
    {
        call->firstRequestStartTime = requestStartTime;
    }
    call->retryIterationNumber++;
    if (call->traceCall) { HC_TRACE_INFORMATION(HTTPCLIENT, "HCHttpCallPerformExecute [ID %llu] Iteration %d", call->id, call->retryIterationNumber); }

    http_retry_after_api_state apiState = httpSingleton->get_retry_state(call->retryAfterCacheId);
    if (apiState.statusCode >= 400)
    {
        bool clearState = false;
        if (should_fast_fail(apiState, call, requestStartTime, &clearState))
        {
            HCHttpCallResponseSetStatusCode(call, apiState.statusCode);
            if (call->traceCall) { HC_TRACE_INFORMATION(HTTPCLIENT, "HCHttpCallPerformExecute [ID %llu] Fast fail %d", call->id, apiState.statusCode); }
            XAsyncComplete(retryContext->outerAsyncBlock, S_OK, 0);
            return;
        }

        if( clearState )
        {
            httpSingleton->clear_retry_state(call->retryAfterCacheId);
        }
    }

    auto nestedBlock = http_allocate_unique<XAsyncBlock>();
    if (nestedBlock == nullptr)
    {
        XAsyncComplete(retryContext->outerAsyncBlock, E_OUTOFMEMORY, 0);
        return;
    }

    XTaskQueueHandle nestedQueue = nullptr;
    if (retryContext->outerQueue != nullptr)
    {
        XTaskQueuePortHandle workPort;
        XTaskQueueGetPort(retryContext->outerQueue, XTaskQueuePort::Work, &workPort);
        XTaskQueueCreateComposite(workPort, workPort, &nestedQueue);
    }
    nestedBlock->queue = nestedQueue;
    nestedBlock->context = retryContext.get();
    nestedBlock->callback = [](XAsyncBlock* nestedAsyncBlock)
    {
        HC_UNIQUE_PTR<XAsyncBlock> nestedAsyncPtr{ nestedAsyncBlock };
        HC_UNIQUE_PTR<retry_context> retryContext{ static_cast<retry_context*>(nestedAsyncBlock->context) };

        auto httpSingleton = get_http_singleton();
        if (httpSingleton == nullptr)
        {
            HC_TRACE_WARNING(HTTPCLIENT, "Http completed after HCCleanup was called. Aborting call.");
            XAsyncComplete(retryContext->outerAsyncBlock, E_HC_NOT_INITIALISED, 0);
        }
        else
        {
            auto callStatus = XAsyncGetStatus(nestedAsyncBlock, false);
            auto responseReceivedTime = chrono_clock_t::now();
            uint32_t timeoutWindowInSeconds = 0;
            HC_CALL* call = retryContext->call->get();
            HCHttpCallRequestGetTimeoutWindow(call, &timeoutWindowInSeconds);
            notify_call_routed_handlers(httpSingleton, call);

            if (SUCCEEDED(callStatus) && http_call_should_retry(call, responseReceivedTime))
            {
                if (call->traceCall) { HC_TRACE_INFORMATION(HTTPCLIENT, "HCHttpCallPerformExecute [ID %llu] Retry after %lld ms", call->id, call->delayBeforeRetry.count()); }
                clear_http_call_response(call);
                retry_http_call_until_done(std::move(retryContext));
            }
            else
            {
                XAsyncComplete(retryContext->outerAsyncBlock, callStatus, 0);
            }
        }

        if (nestedAsyncBlock->queue != nullptr)
        {
            XTaskQueueCloseHandle(nestedAsyncBlock->queue);
        }
        // Cleanup with happen when unique ptr's go out of scope
    };

    HRESULT hr = perform_http_call(httpSingleton, call, nestedBlock.get());
    if (SUCCEEDED(hr))
    {
        nestedBlock.release(); // at this point we know do work will be called eventually
        retryContext.release(); // at this point we know do work will be called eventually
    }
    else
    {
        // Cleanup with happen when unique ptr's go out of scope if they weren't released
        XAsyncComplete(retryContext->outerAsyncBlock, hr, 0);
        return;
    }
}

STDAPI
HCHttpCallPerformAsync(
    _In_ HCCallHandle call,
    _Inout_ XAsyncBlock* asyncBlock
    ) noexcept
try
{
    if (call == nullptr)
    {
        return E_INVALIDARG;
    }

    if (call->traceCall) { HC_TRACE_INFORMATION(HTTPCLIENT, "HCHttpCallPerform [ID %llu] uri: %s", call->id, call->url.c_str()); }
    call->performCalled = true;

    auto retryContext = http_allocate_unique<retry_context>();
    if (retryContext == nullptr)
    {
        HCHttpCallCloseHandle(call);
        return E_HC_NOT_INITIALISED;
    }
    retryContext->call = http_allocate_shared<HcCallWrapper>(static_cast<HC_CALL*>(call)); // RAII will keep the HCCallHandle alive during HTTP call
    retryContext->outerAsyncBlock = asyncBlock;
    retryContext->outerQueue = asyncBlock->queue;

    HRESULT hr = XAsyncBegin(asyncBlock, retryContext.get(), reinterpret_cast<void*>(HCHttpCallPerformAsync), __FUNCTION__,
        [](_In_ XAsyncOp op, _In_ const XAsyncProviderData* data)
    {
        auto httpSingleton = get_http_singleton();
        if (nullptr == httpSingleton)
        {
            return E_HC_NOT_INITIALISED;
        }

        switch (op)
        {
            case XAsyncOp::DoWork:
            {
                HC_UNIQUE_PTR<retry_context> retryContext{ static_cast<retry_context*>(data->context) };
                retry_http_call_until_done(std::move(retryContext));
                return E_PENDING;
            }

            default:
                break;
        }

        return S_OK;
    });

    if (SUCCEEDED(hr))
    {
        hr = XAsyncSchedule(asyncBlock, 0);
        if (SUCCEEDED(hr))
        {
            retryContext.release(); // at this point we know do work will be called eventually
        }
    }

    return hr;
}
CATCH_RETURN()

STDAPI_(uint64_t)
HCHttpCallGetId(
    _In_ HCCallHandle call
    ) noexcept
try
{
    if (call == nullptr)
    {
        return 0;
    }
    return call->id;
}
CATCH_RETURN()

STDAPI
HCHttpCallSetTracing(
    _In_ HCCallHandle call,
    _In_ bool logCall
    ) noexcept
try
{
    if (call == nullptr)
    {
        return E_INVALIDARG;
    }
    call->traceCall = logCall;
    return S_OK;
}
CATCH_RETURN()

STDAPI
HCHttpCallSetContext(
    _In_ HCCallHandle call,
    _In_opt_ void* context
    ) noexcept
try
{
    if (call == nullptr)
    {
        return E_INVALIDARG;
    }

    call->context = context;

    return S_OK;
}
CATCH_RETURN()

STDAPI
HCHttpCallGetContext(
    _In_ HCCallHandle call,
    _In_ void** context
    ) noexcept
try
{
    if (call == nullptr)
    {
        return E_INVALIDARG;
    }

    *context = call->context;

    return S_OK;
}
CATCH_RETURN()

STDAPI
HCHttpCallGetRequestUrl(
    _In_ HCCallHandle call,
    _Out_ const char** url
    ) noexcept
try
{
    if (call == nullptr)
    {
        return E_INVALIDARG;
    }

    *url = call->url.data();
    return S_OK;
}
CATCH_RETURN()

bool http_header_compare::operator()(http_internal_string const& l, http_internal_string const& r) const
{
    return str_icmp(l, r) < 0;
}

void PerformEnvDeleter::operator()(HC_PERFORM_ENV* performEnv) noexcept
{
    Internal_CleanupHttpPlatform(performEnv);
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Caching;

namespace Masuit.Tools.Net
{
    /// <summary>
    /// 全局统一的缓存类
    /// </summary>
    public static class CacheHelper
    {
        #region  获取数据缓存

        /// <summary>
        /// 获取数据缓存
        /// </summary>
        /// <typeparam name="T">返回的类型</typeparam>
        /// <param name="cache"></param>
        /// <param name="cacheKey">键</param>
        public static T GetCache<T>(this Cache cache, string cacheKey)
        {
            return (T)cache[cacheKey];
        }

        #endregion

        #region  设置数据缓存

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="cacheKey">键</param>
        /// <param name="objObject">值</param>
        public static void SetCache(this Cache cache, string cacheKey, object objObject)
        {
            cache.Insert(cacheKey, objObject);
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="cacheKey">键</param>
        /// <param name="objObject">值</param>
        /// <param name="timeout">过期时间</param>
        /// <exception cref="ArgumentNullException"><paramref name="cacheKey"/>"/> is <c>null</c>.</exception>
        public static void SetCache(this Cache cache, string cacheKey, object objObject, TimeSpan timeout)
        {
            if (cacheKey == null)
            {
                throw new ArgumentNullException(nameof(cacheKey));
            }

            cache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);
        }

        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="cacheKey">键</param>
        /// <param name="objObject">值</param>
        /// <param name="absoluteExpiration">绝对过期时间</param>
        /// <param name="slidingExpiration">滑动过期时间</param>
        public static void SetCache(this Cache cache, string cacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            cache.Insert(cacheKey, objObject, null, absoluteExpiration, slidingExpiration);
        }

        #endregion

        #region   移除缓存

        /// <summary>
        /// 移除指定数据缓存
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="cacheKey">键</param>
        public static void RemoveAllCache(this Cache cache, string cacheKey) => cache.Remove(cacheKey);

        /// <summary>
        /// 移除全部缓存
        /// </summary>
        public static void RemoveAllCache(this Cache cache)
        {
            IDictionaryEnumerator cacheEnum = cache.GetEnumerator();
            while (cacheEnum.MoveNext())
            {
                cache.Remove(cacheEnum.Key.ToString());
            }
        }

        #endregion

        private static SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
        private static volatile Cache instance;
        private static readonly object LockHelper = new object();

        /// <summary>
        /// 添加缓存数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void Add(string key, object value)
        {
            dic.Add(key, value);
        }

        /// <summary>
        /// 缓存实例
        /// </summary>
        public static Cache Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (LockHelper)
                    {
                        if (instance == null)
                        {
                            instance = new Cache();
                        }
                    }
                }

                return instance;
            }
        }
    }
}


text:
namespace Discord
{
    /// <summary>
    ///     Provides properties that are used to modify an <see cref="IVoiceChannel" /> with the specified changes.
    /// </summary>
    public class VoiceChannelProperties : GuildChannelProperties
    {
        /// <summary>
        ///     Gets or sets the bitrate of the voice connections in this channel. Must be greater than 8000.
        /// </summary>
        public Optional<int> Bitrate { get; set; }
        /// <summary>
        ///     Gets or sets the maximum number of users that can be present in a channel, or <c>null</c> if none.
        /// </summary>
        public Optional<int?> UserLimit { get; set; }
    }
}


text:
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Slide;

/**
 * SlideContentSearch represents the model behind the search form about `common\models\SlideContent`.
 */
class SlideSearch extends Slide
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'content_id', 'status', 'created_at', 'updated_at'], 'integer'],
            [['des'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params,$type)
    {
        $query = Slide::find()->andWhere(['type'=>$type]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'content_id' => $this->content_id,
            'status' => $this->status,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'des', $this->des]);
        return $dataProvider;
    }
}


text:
import basilisk = require('../basilisk');

// we use this a *lot*, so simplify it here.
import SM = basilisk.SimpleStringMap;

class Sample extends basilisk.ts.Struct {
    constructor(opts:{ name:string }) {
        this.name = opts.name;
        super();
    }

    public name:string;

    public equals(other:any):boolean {
        if (this === other) {
            return true;
        }

        if (Object.getPrototypeOf(this) !== Object.getPrototypeOf(other)) {
            return false;
        }

        if (other === null || other === undefined) {
            return false;
        }

        return this.name === other.name;
    }
}

function mapOfThree():SM<Sample> {
    return SM.from({
        'a': new Sample({ name: 'a'}),
        'b': new Sample({ name: 'b'}),
        'c': new Sample({ name: 'c'})
    });
}

describe("SimpleStringMap", function () {

    function mapOfThree ():SM<Sample> {
        return SM.from({
            'a': new Sample({ name: 'a'}),
            'b': new Sample({ name: 'b'}),
            'c': new Sample({ name: 'c'})
        });
    }

    describe(".from", function () {
        it("Can be constructed from a simple hash.", function () {
            var sample = SM.from({
                'a': new Sample({ name: 'a'}),
                'b': new Sample({ name: 'b'})
            });

            expect(sample instanceof SM).toBeTruthy();
            expect(sample.get('a')).toEqual(jasmine.objectContaining({ name: 'a' }));
            expect(sample.get('b')).toEqual(jasmine.objectContaining({ name: 'b' }));
            expect(sample.get('c', null)).toBeNull();
            expect(sample.get('c', new Sample({ name: 'cat'}))).toEqual(jasmine.objectContaining({ name: 'cat' }));
        });

        it("Can be constructed from another SimpleStringMap", function () {
            var sample = SM.from({
                'a': new Sample({ name: 'a'}),
                'b': new Sample({ name: 'b'})
            }),
                alt = SM.from(sample);

            expect(sample).not.toBe(alt);
            expect(sample.get('a')).toBe(alt.get('a'));
            expect(sample.get('b')).toBe(alt.get('b'));
        });
    });

    describe('Replace functionality', function () {
        it("Can have a particular object replaced.", function () {
            var sample = mapOfThree(),
                alt = sample.set('b', new Sample({ name: 'replaced' }));

            expect(alt).not.toBe(sample);
            expect(alt.get('b')).toEqual(jasmine.objectContaining({ name: 'replaced' }));
            expect(sample.get('b')).toEqual(jasmine.objectContaining({ name: 'b' }));
        });

        it("Should be safe to use hostile names.", function () {
            var sample = mapOfThree(),
                alt = sample.set('__proto__', new Sample({ name: 'replaced' }));

            expect(alt).not.toBe(sample);
            expect(alt.get('__proto__')).toEqual(jasmine.objectContaining({ name: 'replaced' }));
            expect(sample.get('b')).toEqual(jasmine.objectContaining({ name: 'b' }));
        });
    });

    describe("Get functionality", function () {
        it("Should be able to retrieve objects by id.", function () {
            var sample = mapOfThree();

            expect(sample.get('a').name).toBe('a');
        });

        it("Should be able to retrieve default objects, if the actual object is not there..", function () {
            var sample = mapOfThree();

            expect(sample.get('j', new Sample({ name: 'cat' }))).toEqual(jasmine.objectContaining({ name: 'cat' }));
        })
    });

    describe("Has functionality", function () {
        it("Can check basic objects via has.", function () {
            var sample = mapOfThree();

            expect(sample.has('a')).toBe(true);
            expect(sample.has('b')).toBe(true);
            expect(sample.has('c')).toBe(true);
            expect(sample.has('d')).toBe(false);
        });
    });
    describe("forEach functionality", function () {
        it("Basic count behaviour", function () {
            var sample = mapOfThree(),
                seen = {},
                count = 0;

            sample.forEach(function (value:Sample, key:string) {
                count += 1;
                seen[value.name] = true;
                expect(key).toBe(value.name);
            });

            expect(count).toBe(3);
            expect(seen['a']).toBeTruthy();
            expect(seen['b']).toBeTruthy();
            expect(seen['c']).toBeTruthy();
            expect(seen['d']).not.toBeTruthy();
        })
    });

    describe("Equality functionality", function () {
        it("Should be equal to itself", function () {
            var m = basilisk.SimpleStringMap.from({
                'a': 'test'
            });

            expect(m.equals(m)).toBe(true);
        });

        it("Should not be equal if a key is different.", function () {
            var a = basilisk.SimpleStringMap.from<string>({
                'a': 'test'
            }), b = basilisk.SimpleStringMap.from<string>({
                    'a': 'different'
                });

            expect(a.equals(b)).toBe(false);
        });

        it("Should not be equal if an extra key is present in other.", function () {
            var a = basilisk.SimpleStringMap.from<string>({
                    'a': 'test'
                }), b = basilisk.SimpleStringMap.from<string>({
                    'a': 'test',
                    'b': 'different'
                })
                ;

            expect(a.equals(b)).toBe(false);
        });

        it("Should be equal across multiple items.", function () {
            var a = basilisk.SimpleStringMap.from<string>({
                    'a': 'test',
                    'b': 'same'
                }),
                b = basilisk.SimpleStringMap.from<string>({
                    'a': 'test',
                    'b': 'same'
                });

            expect(a.equals(b)).toBe(true);
        });

        it("Should be equal for complex children with equality defined.", function () {
            var a = basilisk.SimpleStringMap.from({
                    'a': new Sample({ name: 'test' })
                }),
                b = basilisk.SimpleStringMap.from<string>({
                    'a': new Sample({ name: 'test' })
                });

            expect(a.equals(b)).toBe(true);
        });
    });

    describe("Remove functionality", function () {
        it("Should remove keys if they are present.", function () {
            var sample = basilisk.SimpleStringMap.from<string>({
                'a': 'hello',
                'b': 'goodbye'
            }),
                changed = sample.remove('a');

            expect(sample.get('a')).toBe('hello');
            expect(changed.get('a')).toBe(null);
            expect(changed.get('b')).toBe('goodbye');
        });
    });

});


text:
package io.crate.operation.reference.sys.cluster;

import io.crate.metadata.ColumnIdent;
import io.crate.metadata.ReferenceIdent;
import io.crate.metadata.ReferenceImplementation;
import io.crate.metadata.ReferenceInfo;
import io.crate.metadata.sys.SysClusterTableInfo;
import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.inject.multibindings.MapBinder;

import java.util.Map;

public class SysClusterExpressionModule extends AbstractModule {

    @Override
    protected void configure() {
        MapBinder<ReferenceIdent, ReferenceImplementation> b = MapBinder
                .newMapBinder(binder(), ReferenceIdent.class, ReferenceImplementation.class);

        Map<ColumnIdent, ReferenceInfo> infos = SysClusterTableInfo.INFOS;
        b.addBinding(infos.get(new ColumnIdent(ClusterIdExpression.NAME)).ident()).to(
                ClusterIdExpression.class).asEagerSingleton();
        b.addBinding(infos.get(new ColumnIdent(ClusterNameExpression.NAME)).ident()).to(
                ClusterNameExpression.class).asEagerSingleton();
        b.addBinding(infos.get(new ColumnIdent(ClusterMasterNodeExpression.NAME)).ident()).to(
                ClusterMasterNodeExpression.class).asEagerSingleton();
        b.addBinding(infos.get(new ColumnIdent(ClusterSettingsExpression.NAME)).ident()).to(
                ClusterSettingsExpression.class).asEagerSingleton();
    }
}


text:
package kieker.examples.livedemo.analysis.sink;

import java.util.HashMap;
import java.util.Map;

import org.primefaces.model.chart.CartesianChartModel;
import org.primefaces.model.chart.ChartSeries;

import kieker.analysis.IProjectContext;
import kieker.common.configuration.Configuration;
import kieker.common.record.jvm.GCRecord;
import kieker.examples.livedemo.analysis.util.LimitedHashMap;

/**
 * @author Nils Christian Ehmke
 *
 * @since 1.10
 */
public class GCCountDisplayFilter extends AbstractNonAggregatingDisplayFilter<GCRecord, CartesianChartModel> {

	private final Map<String, Map<Object, Number>> dataMap = new HashMap<String, Map<Object, Number>>();

	public GCCountDisplayFilter(final Configuration configuration, final IProjectContext projectContext) {
		super(configuration, projectContext);
	}

	@Override
	protected CartesianChartModel createChartModel(final int numberOfEntries) {
		return new CartesianChartModel();
	}

	@Override
	protected void fillChartModelWithRecordData(final CartesianChartModel chartModel, final GCRecord record, final String minutesAndSeconds,
			final int numberOfEntries) {
		final String gcName = record.getGcName();
		if (!this.dataMap.containsKey(gcName)) {
			final ChartSeries series = new ChartSeries();
			final Map<Object, Number> data = new LimitedHashMap<Object, Number>(numberOfEntries);

			chartModel.addSeries(series);
			series.setData(data);
			series.setLabel(gcName);
			this.dataMap.put(gcName, data);
		}

		final Map<Object, Number> data = this.dataMap.get(gcName);
		data.put(minutesAndSeconds, record.getCollectionCount());
	}

}


text: export * from './collection';


text:
import React from 'react';

export default class FuncDesc extends React.Component {
  render() {
    var desc = this.props.description;
    return (
      <p className="func-desc">
        {desc}
      </p>
    );
  }
}


text:
"""Check if a domain is in a top-million domain list from Alexa or Cisco."""

from .onemillion import OneMillion

__author__ = """Floyd Hightower"""
__version__ = '1.0.0'


text:
**Appveyor**
![AppVeyor](https://img.shields.io/appveyor/ci/ademcatamak/alternatives-gbx0h.svg) ![AppVeyor tests](https://img.shields.io/appveyor/tests/ademcatamak/alternatives-gbx0h.svg)

**Travis**
![Travis (.com)](https://img.shields.io/travis/AdemCatamak/Alternatives.svg)

**Nuget Versions**

Alternatives : ![Nuget](https://img.shields.io/nuget/v/Alternatives.svg)

Alternatives.CollectionExtensions : ![Nuget](https://img.shields.io/nuget/v/Alternatives.CollectionExtensions.svg)

Alternatives.ConversionExtensions : ![Nuget](https://img.shields.io/nuget/v/Alternatives.ConversionExtensions.svg)

Alternatives.Crypto : ![Nuget](https://img.shields.io/nuget/v/Alternatives.Crypto.svg)

Alternatives.ReflectionExtensions : ![Nuget](https://img.shields.io/nuget/v/Alternatives.ReflectionExtensions.svg)

You can download and use this project via NuGet Package Manager > Install-Package Alternatives

You can download and use this project via NuGet Package Manager > Install-Package Alternatives.CollectionExtensions

You can download and use this project via NuGet Package Manager > Install-Package Alternatives.ConversionExtensions

You can download and use this project via NuGet Package Manager > Install-Package Alternatives.Crypto

You can download and use this project via NuGet Package Manager > Install-Package Alternatives.ReflectionExtensions

You can examine function signature and learn general information about that via https://github.com/AdemCatamak/Alternatives/wiki


text:
// Type definitions for jquery.filterTable v1.5.7
// Project: https://github.com/sunnywalker/jQuery.FilterTable
// Definitions by: TotPeRo <https://github.com/totpero>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3

///<reference types="jquery" />

declare namespace FilterTable {
    interface FilterTableOptions {
        /**
         * Makes the filter input field autofocused (not recommended for accessibility reasons)
         * Default: 'false'
         */
        autofocus?: boolean;
        /**
        * Callback function after a filter is performed.
        * Default: 'null'
        * @param term filter term (string)
        * @param table table being filtered (JQuery object)
        * @returns {void}
        */
        callback?: (term:string, table:JQuery) => void;
        /**
         * Class applied to the main filter input container
         * Default: 'filter-table'
         */
        containerClass?: string;
        /**
         * Tag name of the main filter input container
         * Default: 'p'
         */
        containerTag?: string;
        /**
         * Controls whether the table's tfoot(s) will be hidden when the table is filtered
         * Default: 'false'
         */
        hideTFootOnFilter?: boolean;
        /**
         * Class applied to cells containing the filter term
         * Default: 'alt'
         */
        highlightClass?: string;
        /**
         * Ignore these columns (0-indexed) when filtering
         * Default: '[]'
         */
        ignoreColumns?: number[];
        /**
         * Use this selector to find the filter input instead of creating a new one (only works if selector returns a single element)
         * Default: 'null'
         */
        inputSelector?: string;
        /**
        * Name attribute of the filter input field
        * Default: 'filter-table'
        */
        inputName?: string;
        /**
         * Tag name of the filter input itself
         * Default: 'search'
         */
        inputType?: string;
        /**
        * Text to precede the filter input
        * Default: 'Filter:'
        */
        label?: string;
        /**
        * Filter only when at least this number of characters are in the filter input field
        * Default: '1'
        */
        minChars?: number;
        /**
        * Only show the filter on tables with this number of rows or more
        * Default: '8'
        */
        minRows?: number;
        /**
        * HTML5 placeholder text for the filter input
        * Default: 'search this table'
        */
        placeholder?: string;
        /**
        * Trap the return key in the filter input field to prevent form submission
        * Default: 'true'
        */
        preventReturnKey?: boolean;
        /**
        * List of clickable phrases to quick fill the search
        * Default: '[]'
        */
        quickList?: string[];
        /**
        * Class of each quick list item
        * Default: 'quick'
        */
        quickListClass?: string;
        /**
        * Label for the clear filtering quick list item (or none if blank)
        * Default: ''
        */
        quickListClear?: string;
        /**
        * Tag name surrounding quick list items (e.g., ul)
        * Default: ''
        */
        quickListGroupTag?: string;
        /**
        * Tag name of each quick list item (e.g., a or li)
        * Default: 'a'
        */
        quickListTag?: string; // "a" | "li"
        /**
        * Class applied to visible rows
        * Default: 'visible'
        */
        visibleClass?: string;
    }

    interface FilterTableStatic {
        /**
         * init with default options
         * @returns {JQuery}
         */
        (): JQuery;

        /**
         * init with custom options
         * @param options
         * @returns {JQuery}
         */
        (options: FilterTableOptions): JQuery;
    }
}

interface JQuery {
    /**
     * if this code appears after your tables; otherwise, include it in your document.ready() code.
     * $('table').filterTable()
     */
    filterTable: FilterTable.FilterTableStatic;
}


text:
package com.xeiam.xchart.demo.charts.theme;

import java.util.ArrayList;
import java.util.Collection;

import com.xeiam.xchart.Chart;
import com.xeiam.xchart.SwingWrapper;
import com.xeiam.xchart.demo.charts.ExampleChart;

/**
 * Default XChart Theme
 *

 * Demonstrates the following:
 *

 *
Setting marker size
 */
public class ThemeChart01 implements ExampleChart {

  public static void main(String[] args) {

    ExampleChart exampleChart = new ThemeChart01();
    Chart chart = exampleChart.getChart();
    new SwingWrapper(chart).displayChart();
  }

  @Override
  public Chart getChart() {

    // Create Chart
    Chart chart = new Chart(800, 600);

    for (int i = 1; i <= 14; i++) {

      // generates linear data
      int b = 20;
      Collection<Number> xData = new ArrayList<Number>();
      Collection<Number> yData = new ArrayList<Number>();
      for (int x = 0; x <= b; x++) {
        xData.add(2 * x - b);
        yData.add(2 * i * x - i * b);
      }

      // Customize Chart
      chart.setChartTitle("XChart Theme");
      chart.setXAxisTitle("X");
      chart.setYAxisTitle("Y");

      String seriesName = "y=" + 2 * i + "x-" + i * b + "b";
      chart.addSeries(seriesName, xData, yData);
      chart.getStyleManager().setMarkerSize(11);

    }
    return chart;
  }
}


text:
using Lasso, FactCheck
DATADIR = joinpath(dirname(@__FILE__), "data")

# Test against fused lasso results from glmgen
lakehuron = readcsv(joinpath(DATADIR, "LakeHuron.csv"); header=true)[1][:, 3]
facts("FusedLasso") do
	for lambda in (10, 1, 0.1)
		context("λ = $(lambda)") do
			@fact coef(fit(FusedLasso, lakehuron, lambda)) => roughly(vec(readcsv(joinpath(DATADIR, "LakeHuron_lambda_$lambda.csv"))))
		end
	end
end


text:
package com.poomoo.edao.activity;

import java.io.StringReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import com.google.gson.Gson;
import com.poomoo.edao.R;
import com.poomoo.edao.application.eDaoClientApplication;
import com.poomoo.edao.config.eDaoClientConfig;
import com.poomoo.edao.model.ResponseData;
import com.poomoo.edao.util.HttpCallbackListener;
import com.poomoo.edao.util.HttpUtil;
import com.poomoo.edao.util.Utity;
import com.poomoo.edao.weixinpay.Constants;
import com.poomoo.edao.weixinpay.MD5;
import com.poomoo.edao.weixinpay.Util;
import com.poomoo.edao.widget.MessageBox_YES;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 *
 * @ClassName RechargeActivity
 * @Description TODO 充值
 * @author 李苜菲
 * @date 2015-8-27 下午2:20:26
 */
public class RechargeActivity extends BaseActivity implements OnClickListener {

	private EditText editText_pay_money;
	private Button button_pay;

	private String money = "";
	private eDaoClientApplication application = null;
	private ProgressDialog progressDialog;
	private Gson gson = new Gson();
	private MessageBox_YES box_YES;
	private String orderId = "";
	private PayReq req;
	final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
	private Map<String, String> resultunifiedorder;
	public static RechargeActivity instance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自动生成的方法存根
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recharge);
		// 实现沉浸式状态栏效果
		setImmerseLayout(findViewById(R.id.navigation_fragment));
		application = (eDaoClientApplication) getApplication();
		instance = this;
		init();
		weixin();
	}

	private void init() {
		// TODO 自动生成的方法存根
		editText_pay_money = (EditText) findViewById(R.id.recharge_editText_pay_money);

		button_pay = (Button) findViewById(R.id.recharge_btn_pay);

		button_pay.setOnClickListener(this);
	}

	private void weixin() {
		// TODO 自动生成的方法存根
		req = new PayReq();
		msgApi.registerApp(Constants.APP_ID);
	}

	@Override
	public void onClick(View v) {
		// TODO 自动生成的方法存根
		switch (v.getId()) {
		case R.id.recharge_btn_pay:
			if (checkInput()) {
				confirm();
			}
			break;
		}

	}

	private boolean checkInput() {
		// TODO 自动生成的方法存根
		money = editText_pay_money.getText().toString().trim();
		if (TextUtils.isEmpty(money)) {
			Utity.showToast(getApplicationContext(), "请输入金额");
			return false;
		}
		return true;
	}

	private void confirm() {
		// TODO 自动生成的方法存根
		Map<String, String> data = new HashMap<String, String>();
		data.put("bizName", "50000");
		data.put("method", "50009");
		data.put("fromUserId", application.getUserId());
		data.put("payFee", money);

		showProgressDialog("提交中...");
		HttpUtil.SendPostRequest(gson.toJson(data), eDaoClientConfig.url, new HttpCallbackListener() {

			@Override
			public void onFinish(final ResponseData responseData) {
				// TODO 自动生成的方法存根
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO 自动生成的方法存根
						if (responseData.getRsCode() != 1) {
							closeProgressDialog();
							box_YES = new MessageBox_YES(RechargeActivity.this);
							box_YES.showDialog(responseData.getMsg(), null);
						} else {
							try {
								JSONObject result = new JSONObject(responseData.getJsonData().toString());
								orderId = result.getString("ordersId");
								GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
								getPrepayId.execute();
							} catch (JSONException e) {
								// TODO 自动生成的 catch 块
								e.printStackTrace();
							}
						}

					}
				});
			}

			@Override
			public void onError(Exception e) {
				// TODO 自动生成的方法存根
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO 自动生成的方法存根
						closeProgressDialog();
					}
				});
			}
		});
	}

	private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onPostExecute(Map<String, String> result) {
			resultunifiedorder = result;
			System.out.println("onPostExecute resultunifiedorder:" + resultunifiedorder);
			genPayReq();
			sendPayReq();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected Map<String, String> doInBackground(Void... params) {
			System.out.println("doInBackground");
			String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
			String entity = genProductArgs();

			Log.e("orion", entity);

			byte[] buf = Util.httpPost(url, entity);
			String content = new String(buf);
			System.out.println("微信返回:" + content);
			Map<String, String> xml = decodeXml(content);

			return xml;
		}
	}

	private void sendPayReq() {
		msgApi.registerApp(Constants.APP_ID);
		msgApi.sendReq(req);
	}

	private String genProductArgs() {
		StringBuffer xml = new StringBuffer();

		try {
			String nonceStr = genNonceStr();

			xml.append("</xml>");
			List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
			packageParams.add(new BasicNameValuePair("appid", Constants.APP_ID));
			packageParams.add(new BasicNameValuePair("body", "充值"));
			packageParams.add(new BasicNameValuePair("mch_id", Constants.MCH_ID));
			packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
			packageParams.add(new BasicNameValuePair("notify_url", eDaoClientConfig.wxReUrl));
			packageParams.add(new BasicNameValuePair("out_trade_no", orderId));
			packageParams.add(new BasicNameValuePair("spbill_create_ip", Utity.getLocalHostIp()));
			Double fee = Double.parseDouble(money) * 100;
			packageParams
					.add(new BasicNameValuePair("total_fee", String.valueOf(Utity.subZeroAndDot(String.valueOf(fee)))));
			packageParams.add(new BasicNameValuePair("trade_type", "APP"));

			String sign = genPackageSign(packageParams);
			packageParams.add(new BasicNameValuePair("sign", sign));

			String xmlstring = toXml(packageParams);
			xmlstring = new String(xmlstring.getBytes("UTF-8"), "ISO-8859-1");

			return xmlstring;

		} catch (Exception e) {
			System.out.println("genProductArgs异常" + e.getMessage());
			return null;
		}

	}

	private String genPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);

		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion", packageSign);
		return packageSign;
	}

	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);

		String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion", appSign);
		return appSign;
	}

	public Map<String, String> decodeXml(String content) {

		try {
			Map<String, String> xml = new HashMap<String, String>();
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(new StringReader(content));
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {

				String nodeName = parser.getName();
				switch (event) {
				case XmlPullParser.START_DOCUMENT:

					break;
				case XmlPullParser.START_TAG:

					if ("xml".equals(nodeName) == false) {
						// 实例化student对象
						xml.put(nodeName, parser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					break;
				}
				event = parser.next();
			}

			return xml;
		} catch (Exception e) {
			Log.e("orion", e.toString());
		}
		return null;

	}

	private String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<" + params.get(i).getName() + ">");

			sb.append(params.get(i).getValue());
			sb.append("</" + params.get(i).getName() + ">");
		}
		sb.append("</xml>");

		Log.e("orion", sb.toString());
		return sb.toString();
	}

	private String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}

	private long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}

	private void genPayReq() {

		req.appId = Constants.APP_ID;
		req.partnerId = Constants.MCH_ID;
		req.prepayId = resultunifiedorder.get("prepay_id");
		req.packageValue = "Sign=WXPay";
		req.nonceStr = genNonceStr();
		req.timeStamp = String.valueOf(genTimeStamp());

		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		signParams.add(new BasicNameValuePair("appid", req.appId));
		signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
		signParams.add(new BasicNameValuePair("package", req.packageValue));
		signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
		signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
		signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

		req.sign = genAppSign(signParams);

		Log.e("orion", signParams.toString());

	}
}


text:
namespace libmatroska {
    class KaxTrackEntry;
}

namespace ZMKV {
    class CodecInfo;

    class Track {
    public:
        Track(Muxer &muxer, const CodecInfo &codecInfo, unsigned int trackNum, unsigned long long trackUUID);

        virtual ~Track() { };
    protected:
        Muxer &muxer;
        libmatroska::KaxTrackEntry &track;

        void AddCodecPrivate(const CodecInfo &codecInfo);
    };
}

#endif //ZMG_TRACK_H


text:
layout: post
title: 'Databases & Rails: Week 3 Pure Ruby Views'
date: '2012-06-26T09:56:00-05:00'
tags:
- ruby
- rails
- view
- erb
- html
- array
- iterator
- server
permalink: /post/25925957093/databases-rails-week-3-pure-ruby-views
---

In week one we learned about storing data and using databases. In week 2 we saw how we can model relationships with databases, and use those relationships with Ruby and Active Record to build models in Rails. This week we start out with a quick  Recap of last week followed by a Quiz. Once you finish the quiz you can check out the Quiz Solutions.

This week we will be focused on building cool things with Pure Ruby (no Rails). We’re going to cover some Ruby basics, and then dive into an exercise where we build an HTML generator using only Ruby. The students really enjoyed the exercise, and got quite a bit out of it, so you shouldn’t skip it. Even if you’ve been using rails for years, the exercise might give you new insight into how exactly some of that Rails magic works.

We’ll also cover using GIT and you’ll need that for the exercise. Get ready cause here comes some serious learning.

Week 3 Videos

Introduction of topics covered:

Ruby arrays and iterating over them with each and map methods:

Using the functions found in Ruby’s STDlib:

Using the ERB library from Ruby’s STDlib to generate HTML:

Finally an Introduction to using GIT. We cover the basics of using a source control management software (GIT) as well as the mechanics of saving files, adding them to a repo, and committing them. GIT is a valuable skill to have, and is needed for the exercise.

Week 3 Exercise

First you need to Fork and Clone my Generating HTML views with pure Ruby repository . Then you can follow along with the exercises in the readme.

If you’re thinking about skipping the exercise, don’t. Programming is a language that you have to learn by using it. As always if you get stuck try googling, or posting onto StackOverflow.

The only difference is that I won’t be grading your work, so don’t submit a pull request when you’re done.

Good luck and happy coding.

Fin

Next week we’ll be putting what we learned about databased backed models and view generation together to start building a fully functional app. Stay tuned, subscribe to this tumblr blog, or youtube channel and let me know if you’ve got any comments @schneems


text:
title: Dublin Novice Cross Country Championships
location: Tymon Park, Dublin
date: 2021-10-10 14:00
latitude: 53.3522291
longitude: -6.3214874
results:
  - place: 4
    name: Sinead McDonald
    time: 14.46
    category: Novice Women
  - place: 19
    name: Mollie O'Donnell
    time: 15.41
    category: Novice Women
  - place: 43
    name: Siobhán Nugent
    time: 16.53
    category: Novice Women
  - place: 57
    name: Orla Gordon
    time: 17.35
    category: Novice Women
  - place: 62
    name: Aisling McAleer
    time: 17.42
    category: Novice Women
  - place: 63
    name: Brigid Long
    time: 17.43
    category: Novice Women
  - place: 66
    name: Rachel Murphy
    time: 17.52
    category: Novice Women
  - place: 92
    name: Aoife Brady
    time: 19.53
    category: Novice Women
  - place: 20
    name: Sergei Dolgy
    time: 20.27
    category: Novice Men
  - place: 41
    name: Geoffrey Alexandre
    time: 21.13
    category: Novice Men
  - place: 58
    name: Simon Monds
    time: 22.02
    category: Novice Men
  - place: 85
    name: Keith Lunders
    time: 23.10
    category: Novice Men
  - place: 90
    name: Declan Connor
    time: 23.14
    category: Novice Men
  - place: 85
    name: Cormac Long
    time: 23.19
    category: Novice Men
  - place: 95
    name: Kevin McDonald
    time: 23.30
    category: Novice Men
  - place: 96
    name: John Touhy
    time: 23.34
    category: Novice Men
  - place: 99
    name: Leo Kavanagh
    time: 23.49
    category: Novice Men
---


text:
#undef KAZLIB_OPAQUE_DEBUG

#ifndef HASH_H
#define HASH_H

#include <limits.h>
#include <stdint.h>

#ifdef KAZLIB_SIDEEFFECT_DEBUG
#include "sfx.h"
#endif

/*
 * Blurb for inclusion into C++ translation units
 */

#ifdef __cplusplus
extern "C" {
#endif

typedef unsigned long hashcount_t;
#define HASHCOUNT_T_MAX ULONG_MAX

typedef uint32_t hash_val_t;
#define HASH_VAL_T_MAX UINT32_MAX

static const int hash_val_t_bit = 32;

#ifndef HASH_VAL_T_BIT
#define HASH_VAL_T_BIT ((int) hash_val_t_bit)
#endif

/*
 * Hash chain node structure.
 * Notes:
 * 1. This preprocessing directive is for debugging purposes.  The effect is
 *    that if the preprocessor symbol KAZLIB_OPAQUE_DEBUG is defined prior to the
 *    inclusion of this header,  then the structure shall be declared as having
 *    the single member   int __OPAQUE__.   This way, any attempts by the
 *    client code to violate the principles of information hiding (by accessing
 *    the structure directly) can be diagnosed at translation time. However,
 *    note the resulting compiled unit is not suitable for linking.
 * 2. This is a pointer to the next node in the chain. In the last node of a
 *    chain, this pointer is null.
 * 3. The key is a pointer to some user supplied data that contains a unique
 *    identifier for each hash node in a given table. The interpretation of
 *    the data is up to the user. When creating or initializing a hash table,
 *    the user must supply a pointer to a function for comparing two keys,
 *    and a pointer to a function for hashing a key into a numeric value.
 * 4. The value is a user-supplied pointer to void which may refer to
 *    any data object. It is not interpreted in any way by the hashing
 *    module.
 * 5. The hashed key is stored in each node so that we don't have to rehash
 *    each key when the table must grow or shrink.
 */

typedef struct hnode_t {
    #if defined(HASH_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG)	/* 1 */
    struct hnode_t *hash_next;		/* 2 */
    const void *hash_key;		/* 3 */
    void *hash_data;			/* 4 */
    hash_val_t hash_hkey;		/* 5 */
    #else
    int hash_dummy;
    #endif
} hnode_t;

/*
 * The comparison function pointer type. A comparison function takes two keys
 * and produces a value of -1 if the left key is less than the right key, a
 * value of 0 if the keys are equal, and a value of 1 if the left key is
 * greater than the right key.
 */

typedef int (*hash_comp_t)(const void *, const void *);

/*
 * The hashing function performs some computation on a key and produces an
 * integral value of type hash_val_t based on that key. For best results, the
 * function should have a good randomness properties in *all* significant bits
 * over the set of keys that are being inserted into a given hash table. In
 * particular, the most significant bits of hash_val_t are most significant to
 * the hash module. Only as the hash table expands are less significant bits
 * examined. Thus a function that has good distribution in its upper bits but
 * not lower is preferrable to one that has poor distribution in the upper bits
 * but not the lower ones.
 */

typedef hash_val_t (*hash_fun_t)(const void *);

/*
 * allocator functions
 */

typedef hnode_t *(*hnode_alloc_t)(void *);
typedef void (*hnode_free_t)(hnode_t *, void *);

/*
 * This is the hash table control structure. It keeps track of information
 * about a hash table, as well as the hash table itself.
 * Notes:
 * 1.  Pointer to the hash table proper. The table is an array of pointers to
 *     hash nodes (of type hnode_t). If the table is empty, every element of
 *     this table is a null pointer. A non-null entry points to the first
 *     element of a chain of nodes.
 * 2.  This member keeps track of the size of the hash table---that is, the
 *     number of chain pointers.
 * 3.  The count member maintains the number of elements that are presently
 *     in the hash table.
 * 4.  The maximum count is the greatest number of nodes that can populate this
 *     table. If the table contains this many nodes, no more can be inserted,
 *     and the hash_isfull() function returns true.
 * 5.  The high mark is a population threshold, measured as a number of nodes,
 *     which, if exceeded, will trigger a table expansion. Only dynamic hash
 *     tables are subject to this expansion.
 * 6.  The low mark is a minimum population threshold, measured as a number of
 *     nodes. If the table population drops below this value, a table shrinkage
 *     will occur. Only dynamic tables are subject to this reduction.  No table
 *     will shrink beneath a certain absolute minimum number of nodes.
 * 7.  This is the a pointer to the hash table's comparison function. The
 *     function is set once at initialization or creation time.
 * 8.  Pointer to the table's hashing function, set once at creation or
 *     initialization time.
 * 9.  The current hash table mask. If the size of the hash table is 2^N,
 *     this value has its low N bits set to 1, and the others clear. It is used
 *     to select bits from the result of the hashing function to compute an
 *     index into the table.
 * 10. A flag which indicates whether the table is to be dynamically resized. It
 *     is set to 1 in dynamically allocated tables, 0 in tables that are
 *     statically allocated.
 */

typedef struct hash_t {
    #if defined(HASH_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG)
    struct hnode_t **hash_table;		/* 1 */
    hashcount_t hash_nchains;			/* 2 */
    hashcount_t hash_nodecount;			/* 3 */
    hashcount_t hash_maxcount;			/* 4 */
    hashcount_t hash_highmark;			/* 5 */
    hashcount_t hash_lowmark;			/* 6 */
    hash_comp_t hash_compare;			/* 7 */
    hash_fun_t hash_function;			/* 8 */
    hnode_alloc_t hash_allocnode;
    hnode_free_t hash_freenode;
    void *hash_context;
    hash_val_t hash_mask;			/* 9 */
    int hash_dynamic;				/* 10 */
    #else
    int hash_dummy;
    #endif
} hash_t;

/*
 * Hash scanner structure, used for traversals of the data structure.
 * Notes:
 * 1. Pointer to the hash table that is being traversed.
 * 2. Reference to the current chain in the table being traversed (the chain
 *    that contains the next node that shall be retrieved).
 * 3. Pointer to the node that will be retrieved by the subsequent call to
 *    hash_scan_next().
 */

typedef struct hscan_t {
    #if defined(HASH_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG)
    hash_t *hash_table;		/* 1 */
    hash_val_t hash_chain;	/* 2 */
    hnode_t *hash_next;		/* 3 */
    #else
    int hash_dummy;
    #endif
} hscan_t;

extern hash_t *hash_create(hashcount_t, hash_comp_t, hash_fun_t);
extern void hash_set_allocator(hash_t *, hnode_alloc_t, hnode_free_t, void *);
extern void hash_destroy(hash_t *);
extern void hash_free_nodes(hash_t *);
extern void hash_free(hash_t *);
extern hash_t *hash_init(hash_t *, hashcount_t, hash_comp_t,
	hash_fun_t, hnode_t **, hashcount_t);
extern void hash_insert(hash_t *, hnode_t *, const void *);
extern hnode_t *hash_lookup(hash_t *, const void *);
extern hnode_t *hash_delete(hash_t *, hnode_t *);
extern int hash_alloc_insert(hash_t *, const void *, void *);
extern void hash_delete_free(hash_t *, hnode_t *);

extern void hnode_put(hnode_t *, void *);
extern void *hnode_get(hnode_t *);
extern const void *hnode_getkey(hnode_t *);
extern hashcount_t hash_count(hash_t *);
extern hashcount_t hash_size(hash_t *);

extern int hash_isfull(hash_t *);
extern int hash_isempty(hash_t *);

extern void hash_scan_begin(hscan_t *, hash_t *);
extern hnode_t *hash_scan_next(hscan_t *);
extern hnode_t *hash_scan_delete(hash_t *, hnode_t *);
extern void hash_scan_delfree(hash_t *, hnode_t *);

extern int hash_verify(hash_t *);

extern hnode_t *hnode_create(void *);
extern hnode_t *hnode_init(hnode_t *, void *);
extern void hnode_destroy(hnode_t *);

#if defined(HASH_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG)
#ifdef KAZLIB_SIDEEFFECT_DEBUG
#define hash_isfull(H) (SFX_CHECK(H)->hash_nodecount == (H)->hash_maxcount)
#else
#define hash_isfull(H) ((H)->hash_nodecount == (H)->hash_maxcount)
#endif
#define hash_isempty(H) ((H)->hash_nodecount == 0)
#define hash_count(H) ((H)->hash_nodecount)
#define hash_size(H) ((H)->hash_nchains)
#define hnode_get(N) ((N)->hash_data)
#define hnode_getkey(N) ((N)->hash_key)
#define hnode_put(N, V) ((N)->hash_data = (V))
#endif

#ifdef __cplusplus
}
#endif

#endif


text:
using System.Threading.Tasks;
using AllReady.Models;
using MediatR;
using Microsoft.Data.Entity;
using System.Linq;

namespace AllReady.Areas.Admin.Features.Itineraries
{
    public class AddTeamMemberCommandHandlerAsync : IAsyncRequestHandler<AddTeamMemberCommand, bool>
    {
        private readonly AllReadyContext _context;
        private readonly IMediator _mediator;

        public AddTeamMemberCommandHandlerAsync(AllReadyContext context, IMediator mediator)
        {
            _context = context;
            _mediator = mediator;
        }

        public async Task<bool> Handle(AddTeamMemberCommand message)
        {
            var itinerary = await _context.Itineraries
                .Where(x => x.Id == message.ItineraryId)
                .Select(x => new
                {
                    EventId = x.EventId,
                    Date = x.Date
                }).SingleOrDefaultAsync();

            if (itinerary == null)
            {
                // todo: sgordon: enhance this with a error message so the controller can better respond to the issue
                return false;
            }

            // We requery for potential team members in case something has changed or the task signup id was modified before posting
            var potentialTaskSignups = await _mediator.SendAsync(new PotentialItineraryTeamMembersQuery { EventId = itinerary.EventId, Date = itinerary.Date });

            var matchedSignup = false;
            foreach(var signup in potentialTaskSignups)
            {
                var id = int.Parse(signup.Value);
                if (id == message.TaskSignupId)
                {
                    matchedSignup = true;
                    break;
                }
            }

            if(matchedSignup)
            {
                var taskSignup = new TaskSignup
                {
                    Id = message.TaskSignupId,
                    ItineraryId = message.ItineraryId
                };

                _context.TaskSignups.Attach(taskSignup);
                _context.Entry(taskSignup).Property(x => x.ItineraryId).IsModified = true;
                await _context.SaveChangesAsync();
            }

            return true;
        }
    }
}


text:
import numpy as np
import logging
import sys
import argparse

import pyrecoutils

class MatrixFactorization:
    def __init__(self, components, epochs, learning_rate, decay_rate, user_l2, item_l2, seed):
        # Overall
        self.overall = 0
        self.k = components
        np.random.seed(seed)
        # User parameters
        self.user_biases = {}
        self.user_counts = {}
        self.user_latent = {}
        # Item parameters
        self.item_biases = {}
        self.item_counts = {}
        self.item_latent = {}
        # Learning parameters
        self.epochs = epochs
        self.learning_rate = learning_rate
        self.decay_rate = decay_rate
        self.user_l2 = user_l2
        self.item_l2 = item_l2
        self.user_threshold = 0
        self.item_threshold = 0

    def _initialize(self, reviews):
        self.overall = np.mean([r for u, i, r in reviews])
        for u, i, r in reviews:
            self.user_biases[u] = np.random.randn()
            self.user_counts[u] = self.user_counts.get(u, 0) + 1
            self.user_latent[u] = np.random.randn(self.k)
            self.item_biases[i] = np.random.randn()
            self.item_counts[i] = self.item_counts.get(i, 0) + 1
            self.item_latent[i] = np.random.randn(self.k)

    def fit(self, training_reviews, validation_reviews, test_reviews):
        self._initialize(training_reviews)
        for epoch in range(self.epochs):
            for u, i, r in training_reviews:
                b_u, b_i = self.user_biases[u], self.item_biases[i]
                p_u, q_i = self.user_latent[u], self.item_latent[i]
                delta = self.overall + b_u + b_i + np.dot(p_u, q_i) - r
                self.user_biases[u] -= self.learning_rate * (delta + self.user_l2 * b_u)
                self.user_latent[u] -= self.learning_rate * (delta * q_i + self.user_l2 * p_u)
                self.item_biases[i] -= self.learning_rate * (delta + self.item_l2 * b_i)
                self.item_latent[i] -= self.learning_rate * (delta * p_u + self.item_l2 * q_i)
            self.learning_rate *= self.decay_rate
            training_rmse = pyrecoutils.rmse(training_reviews, [self.predict(u, i) for u, i, r in training_reviews])
            validation_rmse = pyrecoutils.rmse(validation_reviews,
                                               [self.predict(u, i) for u, i, r in validation_reviews])
            test_rmse = pyrecoutils.rmse(test_reviews, [self.predict(u, i) for u, i, r in test_reviews])
            logging.info(u"Epoch % 4d - RMSE %f %f %f", epoch, training_rmse, validation_rmse, test_rmse)

    def select(self, reviews):
        logging.info(u"Selecting threshold on %d reviews", len(reviews))
        rmses = []
        for t_u in range(10):
            self.user_threshold = t_u
            for t_i in range(10):
                self.item_threshold = t_i
                predictions = [self.predict(u, i) for u, i, r in reviews]
                rmses.append(pyrecoutils.rmse(reviews, predictions))
        threshold = np.argmin(rmses)
        user_threshold = threshold / 10
        item_threshold = threshold % 10
        logging.info(u"Selected user threshold: %f", user_threshold)
        self.user_threshold = user_threshold
        logging.info(u"Selected item threshold: %f", item_threshold)
        self.item_threshold = item_threshold

    def predict(self, user, item):
        prediction = self.overall
        if self.user_counts.get(user, 0) > self.user_threshold and self.item_counts.get(item, 0) > self.item_threshold:
            prediction += self.user_biases[user] + self.item_biases[item]
            prediction += np.dot(self.user_latent[user], self.item_latent[item])
        return prediction

def main(input_filename, output_filename, components, epochs, learning_rate, decay_rate, user_l2, item_l2, seed):
    reviews = pyrecoutils.load_ratings(input_filename)
    training_set, validation_set, test_set = pyrecoutils.split_sets(reviews)

    model = MatrixFactorization(components, epochs, learning_rate, decay_rate, user_l2, item_l2, seed)
    model.fit(training_set, validation_set, test_set)
    model.select(validation_set)

    with pyrecoutils.PredictionWriter(output_filename) as out:
        training_prediction = [model.predict(u, i) for u, i, r in training_set]
        out.dump(training_set, training_prediction)
        training_rmse = pyrecoutils.rmse(training_set, training_prediction)
        out.space_line()

        validation_prediction = [model.predict(u, i) for u, i, r in validation_set]
        out.dump(validation_set, validation_prediction)
        validation_rmse = pyrecoutils.rmse(validation_set, validation_prediction)
        out.space_line()

        test_prediction = [model.predict(u, i) for u, i, r in test_set]
        out.dump(test_set, test_prediction)
        test_rmse = pyrecoutils.rmse(test_set, test_prediction)
    logging.info(u"RMSE: %.4f %.4f %.4f", training_rmse, validation_rmse, test_rmse)

if __name__ == u"__main__":
    logging.basicConfig(format=u'%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO, stream=sys.stdout)
    logging.info(u"Called: %s", u" ".join(sys.argv))
    parser = argparse.ArgumentParser()
    parser.add_argument(u"input", help=u"Path to the input file.", type=unicode)
    parser.add_argument(u"output", help=u"Path to the output file.", type=unicode)
    parser.add_argument(u"components", help=u"Inner dimension of the factorization.", type=int)
    parser.add_argument(u"epochs", help=u"Training epochs.", type=int)
    parser.add_argument(u"learning_rate", help=u"Learning rate to use.", type=float)
    parser.add_argument(u"decay_rate", help=u"Decay rate of the learning rate.", type=float)
    parser.add_argument(u"user_l2", help=u"L2 regularization on the user.", type=float)
    parser.add_argument(u"item_l2", help=u"L2 regularization on the item.", type=float)
    parser.add_argument(u"seed", help=u"Seed of the random generator.", type=int)
    args = parser.parse_args()
    main(args.input, args.output, args.components, args.epochs,
         args.learning_rate, args.decay_rate, args.user_l2, args.item_l2, args.seed)


text:
require 'json'

module MessagebirdTexter
  class Message < ActionTexter::Message
    def request
      MessagebirdTexter::Request.new(to_json)
    end

    def to_json
      JSON.generate(recipients: to,
                    originator: from,
                    body: body)

    end

    def valid?
      true
    end
  end
end