text:
package redis

import (
	"context"
	"fmt"

	"github.com/docker/distribution"
	"github.com/docker/distribution/reference"
	"github.com/docker/distribution/registry/storage/cache"
	"github.com/garyburd/redigo/redis"
	"github.com/opencontainers/go-digest"
)

// redisBlobStatService provides an implementation of
// BlobDescriptorCacheProvider based on redis. Blob descriptors are stored in
// two parts. The first provide fast access to repository membership through a
// redis set for each repo. The second is a redis hash keyed by the digest of
// the layer, providing path, length and mediatype information. There is also
// a per-repository redis hash of the blob descriptor, allowing override of
// data. This is currently used to override the mediatype on a per-repository
// basis.
//
// Note that there is no implied relationship between these two caches. The
// layer may exist in one, both or none and the code must be written this way.
type redisBlobDescriptorService struct {
	pool *redis.Pool

	// TODO(stevvooe): We use a pool because we don't have great control over
	// the cache lifecycle to manage connections. A new connection if fetched
	// for each operation. Once we have better lifecycle management of the
	// request objects, we can change this to a connection.
}

// NewRedisBlobDescriptorCacheProvider returns a new redis-based
// BlobDescriptorCacheProvider using the provided redis connection pool.
func NewRedisBlobDescriptorCacheProvider(pool *redis.Pool) cache.BlobDescriptorCacheProvider {
	return &redisBlobDescriptorService{
		pool: pool,
	}
}

// RepositoryScoped returns the scoped cache.
func (rbds *redisBlobDescriptorService) RepositoryScoped(repo string) (distribution.BlobDescriptorService, error) {
	if _, err := reference.ParseNormalizedNamed(repo); err != nil {
		return nil, err
	}

	return &repositoryScopedRedisBlobDescriptorService{
		repo:     repo,
		upstream: rbds,
	}, nil
}

// Stat retrieves the descriptor data from the redis hash entry.
func (rbds *redisBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	if err := dgst.Validate(); err != nil {
		return distribution.Descriptor{}, err
	}

	conn := rbds.pool.Get()
	defer conn.Close()

	return rbds.stat(ctx, conn, dgst)
}

func (rbds *redisBlobDescriptorService) Clear(ctx context.Context, dgst digest.Digest) error {
	if err := dgst.Validate(); err != nil {
		return err
	}

	conn := rbds.pool.Get()
	defer conn.Close()

	// Not atomic in redis <= 2.3
	reply, err := conn.Do("HDEL", rbds.blobDescriptorHashKey(dgst), "digest", "size", "mediatype")
	if err != nil {
		return err
	}

	if reply == 0 {
		return distribution.ErrBlobUnknown
	}

	return nil
}

// stat provides an internal stat call that takes a connection parameter. This
// allows some internal management of the connection scope.
func (rbds *redisBlobDescriptorService) stat(ctx context.Context, conn redis.Conn, dgst digest.Digest) (distribution.Descriptor, error) {
	reply, err := redis.Values(conn.Do("HMGET", rbds.blobDescriptorHashKey(dgst), "digest", "size", "mediatype"))
	if err != nil {
		return distribution.Descriptor{}, err
	}

	// NOTE(stevvooe): The "size" field used to be "length". We treat a
	// missing "size" field here as an unknown blob, which causes a cache
	// miss, effectively migrating the field.
	if len(reply) < 3 || reply[0] == nil || reply[1] == nil { // don't care if mediatype is nil
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	var desc distribution.Descriptor
	if _, err := redis.Scan(reply, &desc.Digest, &desc.Size, &desc.MediaType); err != nil {
		return distribution.Descriptor{}, err
	}

	return desc, nil
}

// SetDescriptor sets the descriptor data for the given digest using a redis
// hash. A hash is used here since we may store unrelated fields about a layer
// in the future.
func (rbds *redisBlobDescriptorService) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
	if err := dgst.Validate(); err != nil {
		return err
	}

	if err := cache.ValidateDescriptor(desc); err != nil {
		return err
	}

	conn := rbds.pool.Get()
	defer conn.Close()

	return rbds.setDescriptor(ctx, conn, dgst, desc)
}

func (rbds *redisBlobDescriptorService) setDescriptor(ctx context.Context, conn redis.Conn, dgst digest.Digest, desc distribution.Descriptor) error {
	if _, err := conn.Do("HMSET", rbds.blobDescriptorHashKey(dgst),
		"digest", desc.Digest,
		"size", desc.Size); err != nil {
		return err
	}

	// Only set mediatype if not already set.
	if _, err := conn.Do("HSETNX", rbds.blobDescriptorHashKey(dgst),
		"mediatype", desc.MediaType); err != nil {
		return err
	}

	return nil
}

func (rbds *redisBlobDescriptorService) blobDescriptorHashKey(dgst digest.Digest) string {
	return "blobs::" + dgst.String()
}

type repositoryScopedRedisBlobDescriptorService struct {
	repo     string
	upstream *redisBlobDescriptorService
}

var _ distribution.BlobDescriptorService = &repositoryScopedRedisBlobDescriptorService{}

// Stat ensures that the digest is a member of the specified repository and
// forwards the descriptor request to the global blob store. If the media type
// differs for the repository, we override it.
func (rsrbds *repositoryScopedRedisBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	if err := dgst.Validate(); err != nil {
		return distribution.Descriptor{}, err
	}

	conn := rsrbds.upstream.pool.Get()
	defer conn.Close()

	// Check membership to repository first
	member, err := redis.Bool(conn.Do("SISMEMBER", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst))
	if err != nil {
		return distribution.Descriptor{}, err
	}

	if !member {
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	upstream, err := rsrbds.upstream.stat(ctx, conn, dgst)
	if err != nil {
		return distribution.Descriptor{}, err
	}

	// We allow a per repository mediatype, let's look it up here.
	mediatype, err := redis.String(conn.Do("HGET", rsrbds.blobDescriptorHashKey(dgst), "mediatype"))
	if err != nil {
		return distribution.Descriptor{}, err
	}

	if mediatype != "" {
		upstream.MediaType = mediatype
	}

	return upstream, nil
}

// Clear removes the descriptor from the cache and forwards to the upstream descriptor store
func (rsrbds *repositoryScopedRedisBlobDescriptorService) Clear(ctx context.Context, dgst digest.Digest) error {
	if err := dgst.Validate(); err != nil {
		return err
	}

	conn := rsrbds.upstream.pool.Get()
	defer conn.Close()

	// Check membership to repository first
	member, err := redis.Bool(conn.Do("SISMEMBER", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst))
	if err != nil {
		return err
	}

	if !member {
		return distribution.ErrBlobUnknown
	}

	return rsrbds.upstream.Clear(ctx, dgst)
}

func (rsrbds *repositoryScopedRedisBlobDescriptorService) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
	if err := dgst.Validate(); err != nil {
		return err
	}

	if err := cache.ValidateDescriptor(desc); err != nil {
		return err
	}

	if dgst != desc.Digest {
		if dgst.Algorithm() == desc.Digest.Algorithm() {
			return fmt.Errorf("redis cache: digest for descriptors differ but algorithm does not: %q != %q", dgst, desc.Digest)
		}
	}

	conn := rsrbds.upstream.pool.Get()
	defer conn.Close()

	return rsrbds.setDescriptor(ctx, conn, dgst, desc)
}

func (rsrbds *repositoryScopedRedisBlobDescriptorService) setDescriptor(ctx context.Context, conn redis.Conn, dgst digest.Digest, desc distribution.Descriptor) error {
	if _, err := conn.Do("SADD", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst); err != nil {
		return err
	}

	if err := rsrbds.upstream.setDescriptor(ctx, conn, dgst, desc); err != nil {
		return err
	}

	// Override repository mediatype.
	if _, err := conn.Do("HSET", rsrbds.blobDescriptorHashKey(dgst), "mediatype", desc.MediaType); err != nil {
		return err
	}

	// Also set the values for the primary descriptor, if they differ by
	// algorithm (ie sha256 vs sha512).
	if desc.Digest != "" && dgst != desc.Digest && dgst.Algorithm() != desc.Digest.Algorithm() {
		if err := rsrbds.setDescriptor(ctx, conn, desc.Digest, desc); err != nil {
			return err
		}
	}

	return nil
}

func (rsrbds *repositoryScopedRedisBlobDescriptorService) blobDescriptorHashKey(dgst digest.Digest) string {
	return "repository::" + rsrbds.repo + "::blobs::" + dgst.String()
}

func (rsrbds *repositoryScopedRedisBlobDescriptorService) repositoryBlobSetKey(repo string) string {
	return "repository::" + rsrbds.repo + "::blobs"
}


text:
//
//  Entity.h
//  Odin.MacOSX
//
//  Created by Daniel on 15/10/15.
//  Copyright (c) 2015 DG. All rights reserved.
//

#ifndef __Odin_MacOSX__Entity__
#define __Odin_MacOSX__Entity__

#include "Drawable.h"
#include "RenderStates.h"

namespace odin
{
    class Entity
    {
    public:
        Entity();
        Entity(render::Drawable& drawable, render::RenderStates& states);

        void setDrawable(render::Drawable& drawable);
        render::Drawable* getDrawable() const;

        void setRenderStates(const render::RenderStates& states);
        const render::RenderStates& getRenderStates() const;

        void draw() const;

    private:
        render::Drawable* m_drawable;
        render::RenderStates m_states;
    };
}

/*
 Sort for blending:

 std::map<float, glm::vec3> sorted;
 for (GLuint i = 0; i < windows.size(); i++) // windows contains all window positions
 {
 GLfloat distance = glm::length(camera.Position - windows[i]);
 sorted[distance] = windows[i];
 }

 then iterate in reverse order:

 for(std::map<float,glm::vec3>::reverse_iterator it = sorted.rbegin(); it != sorted.rend(); ++it)
 {
 model = glm::mat4();
 model = glm::translate(model, it->second);
 glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
 glDrawArrays(GL_TRIANGLES, 0, 6);
 }
 */

#endif /* defined(__Odin_MacOSX__Entity__) */

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bpl.tucao.dao.BplLikeDao">

	<sql id="bplLikeColumns">
		a.id AS "id",
		a.hotid AS "hotid",
		a.userid AS "userid",
		a.nick_name AS "nickName",
		a.create_time AS "createTime",
		a.update_time AS "updateTime"
	</sql>

	<sql id="bplLikeJoins">
	</sql>

	<select id="get" resultType="BplLike">
		SELECT
			<include refid="bplLikeColumns"/>
		FROM bpl_like a
		<include refid="bplLikeJoins"/>
		WHERE a.id = #{id}
	</select>

	<select id="findList" resultType="BplLike">
		SELECT
			<include refid="bplLikeColumns"/>
		FROM bpl_like a
		<include refid="bplLikeJoins"/>
		<where>

		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
			</otherwise>
		</choose>
	</select>

	<select id="findAllList" resultType="BplLike">
		SELECT
			<include refid="bplLikeColumns"/>
		FROM bpl_like a
		<include refid="bplLikeJoins"/>
		<where>

		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
			</otherwise>
		</choose>
	</select>

	<insert id="insert">
		INSERT INTO bpl_like(
			id,
			hotid,
			userid,
			nick_name,
			create_time,
			update_time
		) VALUES (
			#{id},
			#{hotid},
			#{userid},
			#{nickName},
			#{createTime},
			#{updateTime}
		)
	</insert>

	<update id="update">
		UPDATE bpl_like SET
			hotid = #{hotid},
			userid = #{userid},
			nick_name = #{nickName},
			create_time = #{createTime},
			update_time = #{updateTime}
		WHERE id = #{id}
	</update>

	<update id="delete">
		DELETE FROM bpl_like
		WHERE id = #{id}
	</update>

</mapper>


text:
package com.granveaud.offheapbench.store;

import java.io.Serializable;

public interface OffHeapStore {
    void put(Serializable key, Serializable value);

    Object get(Serializable key);

    void remove(Serializable key);

    int size();

    void close();

    void displayStats();
}


text:
package org.diirt.datasource.pods.web;

import javax.websocket.CloseReason;

/**
 *
 * @author carcassi
 */
public class WebPodsChannelListener {

    public void onConnectionEvent(boolean connected, boolean writeConnected) {

    }

    public void onValueEvent(Object value) {

    }

    public void onErrorEvent(String errorMessage) {

    }

    public void onWriteCompletedEvent(boolean successful, String error){

    }

    public void onDisconnect(CloseReason reason) {

    }

}


text:
Executable wrapper for [clie](https://github.com/tristanls/clie) incorporating telemetry events and logs.

## Example `bin/cli.js` for your [clie](https://github.com/tristanls/clie) app

```javascript
#!/usr/bin/env node
"use strict";

var bin = require('clie-telemetry-bin');
var path = require('path');
var pkg = require('../package.json');

var commandsDirectory = path.normalize(path.join(__dirname, '..', 'commands'));

bin(pkg, commandsDirectory);
```


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="Date-Revision-yyyymmdd" content="20190206" />
    <meta http-equiv="Content-Language" content="en" />
    <title>Play! 2.x Maven Plugin – About Play2 Maven Plugin</title>
    <link rel="stylesheet" href="./css/apache-maven-fluido-1.6.min.css" />
    <link rel="stylesheet" href="./css/site.css" />
    <link rel="stylesheet" href="./css/print.css" media="print" />

<link rel="stylesheet" href="./css/site.css" type="text/css" />

Play! 2.x Maven Plugin

Last Published: 2019-02-06|

Version: 1.0.0-rc5

Parent Project

Play! 2.x

Overview

Introduction

Goals

JavaDocs

Project Documentation

Project Information

Project Reports

About Play2 Maven Plugin

This is Maven plugin for Play! Framework.

Supports Play! 2.1.x, 2.2.x, 2.3.x, 2.4.x, 2.5.x and 2.6.x versions only (2.0.x versions are not supported).

Maven plugin for Play! 1.x is available here

Copyright ©2013–2019.
All rights reserved.


text:
namespace {

class BatterySaverUnitTest : public ::testing::Test {
 public:
  BatterySaverUnitTest() = default;
  ~BatterySaverUnitTest() override = default;

  void TearDown() override { battery::ResetIsBatterySaverEnabledForTesting(); }
};

TEST_F(BatterySaverUnitTest, BatterSaverModeCheck) {
  battery::OverrideIsBatterySaverEnabledForTesting(true);
  EXPECT_TRUE(battery::IsBatterySaverEnabled());
  battery::OverrideIsBatterySaverEnabledForTesting(false);
  EXPECT_FALSE(battery::IsBatterySaverEnabled());
}

}  // namespace


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dialogdemo2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
         >
        <activity
            android:name="com.example.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.example.activity.MySimpleActivity"/>

		<activity android:name="com.example.fragment.FragmentTabActivity"/>
		<activity android:name="com.example.fragment.MyFragmentActivity"/>

		<activity android:name="com.example.activity.TabHostDemoActivity"/>
		<activity android:name="com.example.activity.Tab"/>
		<activity android:name="com.example.activity.TabOne"/>
		<activity android:name="com.example.activity.TabTwo"/>
		<activity android:name="com.example.activity.TabThree"/>
    </application>

</manifest>


text:
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="14dp">
    <shape android:shape="rectangle">
        <solid android:color="@color/list_divider" />
    </shape>
</inset>


text:
using UnityEngine;

public class HearthStoneAbility : UntargettedAbility
{

    [SerializeField]
    private Transform _hearthStoneLocation;

    /**
     * SetHearthStone should be called by server/gamecontroller when sides for players have been chosen
     */
    public void SetHearthStone(Transform loc)
    {
        _hearthStoneLocation = loc;
    }

    override protected void UpdateEffect()
    {
        //base.UpdateEffect();
    }

    /**
     * This function is called from an event in the animation, right when the arms have fully spread
     */
    override public void AbilityStartEffect()
    {
        base.AbilityStartEffect();
        Debug.Log("Going Home");
        _hero.transform.position = _hearthStoneLocation.transform.position;
        _hero.transform.rotation = _hearthStoneLocation.transform.rotation;
        //skip straight to status "cooldown", because teleport is instantaneous
        this.SetStatus(SkillStatus.COOLDOWN);
    }

    public override void AbilityCastingFinished()
    {
        //contrary to "normal" untargetted ability, this time the hero *should* go back to IDLE
        _hero.SetStatus(MOBAUnit.UnitStatus.IDLE);
    }

}


text:
package org.dmfs.rfc3986.schemes;

import org.dmfs.rfc3986.Scheme;
import org.dmfs.rfc3986.validation.CharSets;
import org.dmfs.rfc3986.validation.Validated;

import java.util.Locale;

/**
 * A {@link Scheme} derived from a String.
 *
 * @author Marten Gajda
 */
public final class StringScheme implements Scheme
{
    private final CharSequence mScheme;

    public StringScheme(String scheme)
    {
        mScheme = new Validated(scheme.toLowerCase(Locale.ENGLISH), CharSets.SCHEME_CHAR);
    }

    @Override
    public int length()
    {
        return mScheme.length();
    }

    @Override
    public char charAt(int i)
    {
        return mScheme.charAt(i);
    }

    @Override
    public CharSequence subSequence(int i, int i1)
    {
        return mScheme.subSequence(i, i1);
    }

    @Override
    public String toString()
    {
        return mScheme.toString();
    }
}


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

@import models.amendModels.AmendCurrentPensionModel
@import uk.gov.hmrc.play.views.html.{helpers => govHelpers}
@import helpers.templates.{moneyInputFormat,helpTextAccordion}
@import play.api.data._
@import views.html.helper
@import common.Links
@import controllers.PlaLanguageController
@import play.api.Application
@import config.FrontendAppConfig

@this(
    main_template: main_template)

@(amendCurrentPensionForm: Form[AmendCurrentPensionModel])(implicit request: Request[_], messages: Messages, context: config.PlaContext, partialRetriever: uk.gov.hmrc.play.partials.FormPartialRetriever, templateRenderer: uk.gov.hmrc.renderer.TemplateRenderer, appConfig: FrontendAppConfig, errorSummary: uk.gov.hmrc.play.views.html.helpers.ErrorSummary, form: uk.gov.hmrc.play.views.html.helpers.FormWithCSRF)

@helpTextAccordionContent = {

@Messages("pla.currentPensions.hiddenTextPara")

@Messages("pla.currentPensions.hiddenText1")

@Messages("pla.currentPensions.hiddenText2")

@Messages("pla.currentPensions.hiddenText3")

@Messages("pla.currentPensions.hiddenText4")

@Html(
        Messages(
            "pla.currentPensions.readGuidance",
            s"""

                        ${Messages("pla.currentPensions.helpLinkText")} (${Messages("pla.base.newWindow")})

                """
        ))

}

@main_template(title = Messages("pla.currentPensions.title")) {

    @if(amendCurrentPensionForm.hasErrors){
    @errorSummary(Messages("pla.base.errorSummaryLabel"), amendCurrentPensionForm)
    }

@Messages("pla.currentPensions.title")

@Messages("pla.currentPensions.question")

    @helpTextAccordion("ip16-amend-current-pensions-help", Messages("pla.currentPensions.hiddenLink"), helpTextAccordionContent)

    @form(action = routes.AmendsController.submitAmendCurrentPension) {

        @moneyInputFormat(
            amendCurrentPensionForm("amendedUKPensionAmt"),
            '_legend -> s"${Messages("pla.currentPensions.title")}"
        )

    <button class="button" type="submit" id="continue-button">@Messages("pla.base.change")</button>

        @helper.inputText(amendCurrentPensionForm("protectionType"), 'type -> "hidden", 'class -> "hidden")
        @helper.inputText(amendCurrentPensionForm("status"), 'type -> "hidden", 'class -> "hidden")

    }

}


text:
int APIENTRY wWinMain(HINSTANCE, HINSTANCE, wchar_t*, int) {
  base::AtExitManager exit_manager;

  // Initialize the commandline singleton from the environment.
  CommandLine::Init(0, NULL);

  base::FilePath chrome_exe(chrome_launcher_support::GetAnyChromePath());
  if (chrome_exe.empty()) {
    LOG(INFO) << "No Chrome executable could be found. Let's install it.";
    HRESULT hr = app_host::InstallBinaries();
    if (FAILED(hr)) {
      LOG(ERROR) << "Failed to install the Chrome Binaries. Error: " << hr;
      return 1;
    } else {
      chrome_exe = chrome_launcher_support::GetAnyChromePath();
      if (chrome_exe.empty()) {
        LOG(ERROR) << "Failed to find the Chrome Binaries despite a "
                   << "'successful' installation.";
        return 1;
      }
    }
  }

  CommandLine chrome_exe_command_line(chrome_exe);
  chrome_exe_command_line.AppendArguments(
      *CommandLine::ForCurrentProcess(), false);
  // Launch Chrome before checking for update, for faster user experience.
  bool launch_result = base::LaunchProcess(chrome_exe_command_line,
                                           base::LaunchOptions(), NULL);
  if (launch_result)
    LOG(INFO) << "Delegated to Chrome executable at " << chrome_exe.value();
  else
    LOG(INFO) << "Failed to launch Chrome executable at " << chrome_exe.value();

  app_host::EnsureAppHostUpToDate();

  return !launch_result;
}


text:
<?php

/* TwigBundle:Exception:error.txt.twig */
class __TwigTemplate_82381ccb3a7a15f592943b295033e5d64d622436e792c76b5cf6bb601460adfa extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "Oops! An Error Occurred
=======================

The server returned a \"";
        // line 4
        echo (isset($context["status_code"]) ? $context["status_code"] : $this->getContext($context, "status_code"));
        echo " ";
        echo (isset($context["status_text"]) ? $context["status_text"] : $this->getContext($context, "status_text"));
        echo "\".

Something is broken. Please let us know what you were doing when this error occurred.
We will fix it as soon as possible. Sorry for any inconvenience caused.
";
    }

    public function getTemplateName()
    {
        return "TwigBundle:Exception:error.txt.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  24 => 4,  19 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("Oops! An Error Occurred
=======================

The server returned a \"{{ status_code }} {{ status_text }}\".

Something is broken. Please let us know what you were doing when this error occurred.
We will fix it as soon as possible. Sorry for any inconvenience caused.
", "TwigBundle:Exception:error.txt.twig", "C:\\wamp\\www\\tunisiehologram\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\TwigBundle/Resources/views/Exception/error.txt.twig");
    }
}


text:
<?php

namespace Webmozart\KeyValueStore\Tests\Decorator;

use PHPUnit_Framework_MockObject_MockObject;
use PHPUnit_Framework_TestCase;
use Webmozart\KeyValueStore\Api\KeyValueStore;
use Webmozart\KeyValueStore\Decorator\AbstractDecorator;
use Webmozart\KeyValueStore\Decorator\SortableDecorator;

/**
 * @since  1.0
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 * @author Titouan Galopin <galopintitouan@gmail.com>
 */
abstract class AbstractDecoratorTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var PHPUnit_Framework_MockObject_MockObject|KeyValueStore
     */
    protected $innerStore;

    /**
     * @var SortableDecorator
     */
    protected $decorator;

    /**
     * @param KeyValueStore $innerStore
     *
     * @return KeyValueStore|AbstractDecorator The created store.
     */
    abstract protected function createDecorator(KeyValueStore $innerStore);

    protected function setUp()
    {
        $this->innerStore = $this->getMock('Webmozart\KeyValueStore\Api\KeyValueStore');
        $this->decorator = $this->createDecorator($this->innerStore);
    }

    protected function tearDown()
    {
        if ($this->decorator) {
            $this->decorator->clear();
        }
    }

    public function testGetDelegate()
    {
        $this->innerStore->expects($this->once())
            ->method('get')
            ->with('key');

        $this->decorator->get('key');
    }

    public function testGetOrFailDelegate()
    {
        $this->innerStore->expects($this->once())
            ->method('getOrFail')
            ->with('key');

        $this->decorator->getOrFail('key');
    }

    public function testGetMultipleDelegate()
    {
        $this->innerStore->expects($this->once())
            ->method('getMultiple')
            ->with(array('key1', 'key2'));

        $this->decorator->getMultiple(array('key1', 'key2'));
    }

    public function testGetMultipleOrFailDelegate()
    {
        $this->innerStore->expects($this->once())
            ->method('getMultipleOrFail')
            ->with(array('key1', 'key2'));

        $this->decorator->getMultipleOrFail(array('key1', 'key2'));
    }

    public function testSetDelegate()
    {
        $this->innerStore->expects($this->once())
            ->method('set')
            ->with('key', 'value');

        $this->decorator->set('key', 'value');
    }

    public function testRemoveDelegate()
    {
        $this->innerStore->expects($this->once())
            ->method('remove')
            ->with('key');

        $this->decorator->remove('key');
    }

    public function testExistsDelegate()
    {
        $this->innerStore->expects($this->once())
            ->method('exists')
            ->with('key');

        $this->decorator->exists('key');
    }

    public function testClearDelegate()
    {
        $this->innerStore->expects($this->once())
            ->method('clear');

        $this->decorator->clear();
    }

    public function testKeysDelegate()
    {
        $this->innerStore->expects($this->once())
            ->method('keys');

        $this->decorator->keys();
    }
}


text:
package github.nisrulz.sample.splashscreen;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;

public class SplashActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Use a handler to delay code execution
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        // Start the MainActivity
        startActivity(new Intent(SplashActivity.this, MainActivity.class));

        // Close this activity
        finish();
      }
    }, 2000);
  }
}


text:
from xmlrpc.server import DocXMLRPCServer
import http.client
import sys
from test import support
threading = support.import_module('threading')
import time
import socket
import unittest

PORT = None

def make_request_and_skipIf(condition, reason):
    # If we skip the test, we have to make a request because
    # the server created in setUp blocks expecting one to come in.
    if not condition:
        return lambda func: func
    def decorator(func):
        def make_request_and_skip(self):
            self.client.request("GET", "/")
            self.client.getresponse()
            raise unittest.SkipTest(reason)
        return make_request_and_skip
    return decorator

def server(evt, numrequests):
    serv = DocXMLRPCServer(("localhost", 0), logRequests=False)

    try:
        global PORT
        PORT = serv.socket.getsockname()[1]

        # Add some documentation
        serv.set_server_title("DocXMLRPCServer Test Documentation")
        serv.set_server_name("DocXMLRPCServer Test Docs")
        serv.set_server_documentation(
            "This is an XML-RPC server's documentation, but the server "
            "can be used by POSTing to /RPC2. Try self.add, too.")

        # Create and register classes and functions
        class TestClass(object):
            def test_method(self, arg):
                """Test method's docs. This method truly does very little."""
                self.arg = arg

        serv.register_introspection_functions()
        serv.register_instance(TestClass())

        def add(x, y):
            """Add two instances together. This follows PEP008, but has nothing
            to do with RFC1952. Case should matter: pEp008 and rFC1952.  Things
            that start with http and ftp should be auto-linked, too:
            http://google.com.
            """
            return x + y

        def annotation(x: int):
            """ Use function annotations. """
            return x

        class ClassWithAnnotation:
            def method_annotation(self, x: bytes):
                return x.decode()

        serv.register_function(add)
        serv.register_function(lambda x, y: x-y)
        serv.register_function(annotation)
        serv.register_instance(ClassWithAnnotation())

        while numrequests > 0:
            serv.handle_request()
            numrequests -= 1
    except socket.timeout:
        pass
    finally:
        serv.server_close()
        PORT = None
        evt.set()

class DocXMLRPCHTTPGETServer(unittest.TestCase):
    def setUp(self):
        self._threads = support.threading_setup()
        # Enable server feedback
        DocXMLRPCServer._send_traceback_header = True

        self.evt = threading.Event()
        threading.Thread(target=server, args=(self.evt, 1)).start()

        # wait for port to be assigned
        deadline = time.monotonic() + 10.0
        while PORT is None:
            time.sleep(0.010)
            if time.monotonic() > deadline:
                break

        self.client = http.client.HTTPConnection("localhost:%d" % PORT)

    def tearDown(self):
        self.client.close()

        self.evt.wait()

        # Disable server feedback
        DocXMLRPCServer._send_traceback_header = False
        support.threading_cleanup(*self._threads)

    def test_valid_get_response(self):
        self.client.request("GET", "/")
        response = self.client.getresponse()

        self.assertEqual(response.status, 200)
        self.assertEqual(response.getheader("Content-type"), "text/html")

        # Server raises an exception if we don't start to read the data
        response.read()

    def test_invalid_get_response(self):
        self.client.request("GET", "/spam")
        response = self.client.getresponse()

        self.assertEqual(response.status, 404)
        self.assertEqual(response.getheader("Content-type"), "text/plain")

        response.read()

    def test_lambda(self):
        """Test that lambda functionality stays the same.  The output produced
        currently is, I suspect invalid because of the unencoded brackets in the
        HTML, "<lambda>".

        The subtraction lambda method is tested.
        """
        self.client.request("GET", "/")
        response = self.client.getresponse()

        self.assertIn((b'

'
                       b'<lambda>(x, y)

'),
                      response.read())

    @make_request_and_skipIf(sys.flags.optimize >= 2,
                     "Docstrings are omitted with -O2 and above")
    def test_autolinking(self):
        """Test that the server correctly automatically wraps references to
        PEPS and RFCs with links, and that it linkifies text starting with
        http or ftp protocol prefixes.

        The documentation for the "add" method contains the test material.
        """
        self.client.request("GET", "/")
        response = self.client.getresponse().read()

        self.assertIn(
            (b'

add(x, y)

'
             b'<tt>Add two instances together. This '
             b'follows '
             b'PEP008, but has nothing
\nto do '
             b'with '
             b'RFC1952. Case should matter: pEp008 '
             b'and rFC1952.  Things
\nthat start '
             b'with http and ftp should be '
             b'auto-linked, too:
\n'
             b'http://google.com.</tt>

'), response)

    @make_request_and_skipIf(sys.flags.optimize >= 2,
                     "Docstrings are omitted with -O2 and above")
    def test_system_methods(self):
        """Test the precense of three consecutive system.* methods.

        This also tests their use of parameter type recognition and the
        systems related to that process.
        """
        self.client.request("GET", "/")
        response = self.client.getresponse().read()

        self.assertIn(
            (b'

system.methodHelp'
             b'(method_name)

<tt>system.methodHelp(\'add\') => "Adds '
             b'two integers together"
\n
\nReturns a'
             b' string containing documentation for '
             b'the specified method.</tt>

\n

system.methodSignature'
             b'(method_name)

<tt>'
             b'system.methodSignature(\'add\') => [double, '
             b'int, int]
\n
\nReturns a list '
             b'describing the signature of the method.'
             b' In the
\nabove example, the add '
             b'method takes two integers as arguments'
             b'
\nand returns a double result.
\n '
             b'
\nThis server does NOT support system'
             b'.methodSignature.</tt>

'), response)

    def test_autolink_dotted_methods(self):
        """Test that selfdot values are made strong automatically in the
        documentation."""
        self.client.request("GET", "/")
        response = self.client.getresponse()

        self.assertIn(b"""Try self.add, too.""",
                      response.read())

    def test_annotations(self):
        """ Test that annotations works as expected """
        self.client.request("GET", "/")
        response = self.client.getresponse()
        docstring = (b'' if sys.flags.optimize >= 2 else
                     b'
<tt>Use function annotations.</tt>
')
        self.assertIn(
            (b'

annotation'
             b'(x: int)
' + docstring + b'
\n'
             b'

'
             b'method_annotation(x: bytes)

'),
            response.read())

if __name__ == '__main__':
    unittest.main()


text:
"""Functions for computing statistics of samples."""

import functools
import math
# Dependency imports

import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.internal import dtype_util
from tensorflow_probability.python.internal import nest_util
from tensorflow_probability.python.internal import prefer_static as ps
from tensorflow_probability.python.mcmc import diagnostic
from tensorflow.python.util import nest  # pylint: disable=g-direct-tensorflow-import

__all__ = [
    'RunningCentralMoments',
    'RunningCovariance',
    'RunningMean',
    'RunningPotentialScaleReduction',
    'RunningVariance',
]

JAX_MODE = False

if JAX_MODE:
  ac_decorator = lambda **kwargs: lambda cls: cls
  ACClass = object
else:
  from tensorflow_probability.python.internal import auto_composite_tensor  # pylint: disable=g-import-not-at-top

  def ac_decorator(**kwargs):

    def _decorator(cls):
      return auto_composite_tensor.auto_composite_tensor(**kwargs)(cls)

    return _decorator
  ACClass = auto_composite_tensor.AutoCompositeTensor

@ac_decorator(omit_kwargs='name')
class RunningCovariance(ACClass):
  """A running covariance computation.

  The running covariance computation supports batching. The `event_ndims`
  parameter indicates the number of trailing dimensions to treat as part of
  the event, and to compute covariance across. The leading dimensions, if
  any, are treated as batch shape, and no cross terms are computed.

  For example, if the incoming samples have shape `[5, 7]`, the `event_ndims`
  selects among three different covariance computations:
  - `event_ndims=0` treats the samples as a `[5, 7]` batch of scalar random
    variables, and computes their variances in batch.  The shape of the result
    is `[5, 7]`.
  - `event_ndims=1` treats the samples as a `[5]` batch of vector random
    variables of shape `[7]`, and computes their covariances in batch.  The
    shape of the result is `[5, 7, 7]`.
  - `event_ndims=2` treats the samples as a single random variable of
    shape `[5, 7]` and computes its covariance.  The shape of the result
    is `[5, 7, 5, 7]`.

  `RunningCovariance` is meant to serve general streaming covariance needs.
  For a specialized version that fits streaming over MCMC samples, see
  `CovarianceReducer` in `tfp.experimental.mcmc`.
  """

  def __init__(self, num_samples, mean, sum_squared_residuals, event_ndims,
               name='RunningCovariance'):
    with tf.name_scope(name) as name:
      dtype = dtype_util.common_dtype(
          [num_samples, mean, sum_squared_residuals], dtype_hint=tf.float32)
      self.num_samples = tf.convert_to_tensor(num_samples, dtype=dtype)
      self.mean = tf.convert_to_tensor(mean, dtype=dtype)
      self.sum_squared_residuals = tf.convert_to_tensor(
          sum_squared_residuals, dtype=dtype)
      self.event_ndims = event_ndims
      self.name = name

  def tree_flatten(self):
    return (self.num_samples, self.mean, self.sum_squared_residuals), (
        self.event_ndims,
        self.name,
    )

  @classmethod
  def tree_unflatten(cls, metadata, tensors):
    return cls(*tensors, *metadata)

  @classmethod
  def from_shape(cls, shape=(), dtype=tf.float32, event_ndims=None,
                 name='RunningCovariance'):
    """Starts a `RunningCovariance` from shape and dtype metadata.

    Args:
      shape: Python `Tuple` or `TensorShape` representing the shape of incoming
        samples.  This is useful to supply if the `RunningCovariance` will be
        carried by a `tf.while_loop`, so that broadcasting does not change the
        shape across loop iterations.
      dtype: Dtype of incoming samples and the resulting statistics.
        By default, the dtype is `tf.float32`. Any integer dtypes will be
        cast to corresponding floats (i.e. `tf.int32` will be cast to
        `tf.float32`), as intermediate calculations should be performing
        floating-point division.
      event_ndims:  Number of dimensions that specify the event shape, from
        the inner-most dimensions.  Specifying `None` returns all cross
        product terms (no batching) and is the default.
      name: Python `str` name prefixed to Ops created by this class.

    Returns:
      cov: An empty `RunningCovariance`, ready for incoming samples.

    Raises:
      ValueError: if `event_ndims` is greater than the rank of the intended
        incoming samples (operation is extraneous).
    """
    dtype = _float_dtype_like(dtype)
    event_ndims = _default_covariance_event_ndims(event_ndims, shape)
    if event_ndims == 0:
      extra_ndims_shape = ()
    else:
      # event_ndims cannot be None by this point
      extra_ndims_shape = shape[-event_ndims:]  # pylint: disable=invalid-unary-operand-type
    return cls(
        num_samples=tf.zeros((), dtype=dtype),
        mean=tf.zeros(shape, dtype=dtype),
        sum_squared_residuals=tf.zeros(
            ps.concat([shape, extra_ndims_shape], axis=0), dtype=dtype),
        event_ndims=event_ndims,
        name=name,
    )

  @classmethod
  def from_example(cls, example, event_ndims=None, name='RunningCovariance'):
    """Starts a `RunningCovariance` from an example.

    Args:
      example: A `Tensor`.  The `RunningCovariance` will accept samples
        of the same dtype and broadcast-compatible shape as the example.
      event_ndims:  Number of dimensions that specify the event shape, from
        the inner-most dimensions.  Specifying `None` returns all cross
        product terms (no batching) and is the default.
      name: Python `str` name prefixed to Ops created by this class.

    Returns:
      cov: An empty `RunningCovariance`, ready for incoming samples.  Note
        that by convention, the supplied example is used only for
        initialization, but not counted as a sample.

    Raises:
      ValueError: if `event_ndims` is greater than the rank of the example.
    """
    return cls.from_shape(
        ps.shape(example), example.dtype, event_ndims=event_ndims, name=name)

  def update(self, new_sample, axis=None):
    """Update the `RunningCovariance` with a new sample.

    The update formula is from Philippe Pebay (2008) [1]. This implementation
    supports both batched and chunked covariance computation. A "batch" is the
    usual parallel computation, namely a batch of size N implies N independent
    covariance computations, each stepping one sample (or chunk) at a time. A
    "chunk" of size M implies incorporating M samples into a single covariance
    computation at once, which is more efficient than one by one.

    To further illustrate the difference between batching and chunking, consider
    the following example:

    ```python
    # treat as 3 samples from each of 5 independent vector random variables of
    # shape (2,)
    sample = tf.ones((3, 5, 2))
    running_cov = tfp.experimental.stats.RunningCovariance.from_shape(
        (5, 2), event_ndims=1)
    running_cov = running_cov.update(sample, axis=0)
    final_cov = running_cov.covariance()
    final_cov.shape # (5, 2, 2)
    ```

    Args:
      new_sample: Incoming sample with shape and dtype compatible with those
        used to form this `RunningCovariance`.
      axis: If chunking is desired, this is an integer that specifies the axis
        with chunked samples. For individual samples, set this to `None`. By
        default, samples are not chunked (`axis` is None).

    Returns:
      cov: Newly allocated `RunningCovariance` updated to include `new_sample`.

    #### References
    [1]: Philippe Pebay. Formulas for Robust, One-Pass Parallel Computation of
         Covariances and Arbitrary-Order Statistical Moments. _Technical Report
         SAND2008-6212_, 2008.
         https://prod-ng.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf
    """
    with tf.name_scope((self.name or 'RunningCovariance') + '.update'):
      dtype = self.mean.dtype
      new_sample = tf.cast(new_sample, dtype=dtype)
      if axis is not None:
        chunk_n = tf.cast(ps.shape(new_sample)[axis], dtype=dtype)
        chunk_mean = tf.math.reduce_mean(new_sample, axis=axis)
        chunk_delta_mean = new_sample - tf.expand_dims(chunk_mean, axis=axis)
        chunk_sum_squared_residuals = tf.reduce_sum(
            _batch_outer_product(chunk_delta_mean, self.event_ndims),
            axis=axis
        )
      else:
        chunk_n = tf.ones((), dtype=dtype)
        chunk_mean = new_sample
        chunk_sum_squared_residuals = tf.zeros(
            ps.shape(self.sum_squared_residuals),
            dtype=dtype)

      new_n = self.num_samples + chunk_n
      delta_mean = chunk_mean - self.mean
      new_mean = self.mean + chunk_n * delta_mean / new_n
      all_pairwise_deltas = _batch_outer_product(
          delta_mean, self.event_ndims)
      adj_factor = self.num_samples * chunk_n / (self.num_samples + chunk_n)
      new_sum_squared_residuals = (self.sum_squared_residuals
                                   + chunk_sum_squared_residuals
                                   + adj_factor * all_pairwise_deltas)
      return type(self)(
          new_n, new_mean, new_sum_squared_residuals, self.event_ndims)

  def covariance(self, ddof=0):
    """Returns the covariance accumulated so far.

    Args:
      ddof: Requested dynamic degrees of freedom for the covariance calculation.
        For example, use `ddof=0` for population covariance and `ddof=1` for
        sample covariance. Defaults to the population covariance.

    Returns:
      covariance: An estimate of the covariance.
    """
    with tf.name_scope((self.name or 'RunningCovariance') + '.covariance'):
      ddof = tf.convert_to_tensor(ddof, dtype_hint=self.num_samples.dtype)
      return self.sum_squared_residuals / (self.num_samples - ddof)

  def __repr__(self):
    return ('RunningCovariance(\n'
            f'    num_samples={self.num_samples!r},\n'
            f'    mean={self.mean!r},\n'
            f'    sum_squared_residuals={self.sum_squared_residuals!r},\n'
            f'    event_ndims={self.event_ndims!r})')

def _default_covariance_event_ndims(event_ndims, shape):
  """Try to default `event_ndims` to 'full covariance' for the given `shape`."""
  shape_rank = tf.get_static_value(ps.rank_from_shape(shape))
  if event_ndims is None:
    if shape_rank is None:
      raise ValueError('Cannot default to computing all covariances for '
                       'samples of statically unknown rank.')
    else:
      event_ndims = shape_rank
  if shape_rank is not None and event_ndims > shape_rank:
    raise ValueError('Cannot calculate cross-products in {} dimensions for '
                     'samples of rank {}'.format(event_ndims, shape_rank))
  if event_ndims > 13:
    # This 13 is because we use an einsum to construct the needed outer product
    # in `_batch_outer_product`.  Each event dimension requires two distinct
    # characters to represent, and we don't want to rely on `tf.einsum`
    # supporting a larger alphabet than lower-case English letters.
    raise ValueError('`event_ndims` over 13 not supported')
  return event_ndims

def _batch_outer_product(target, event_ndims):
  """Calculates the batch outer product along `target`'s event dimensions.

  More precisely, A `tf.einsum` operation is used to calculate desired
  pairwise products as follows:

  For `event_ndims=0`, the return value is:
    `tf.einsum("...,...->...", target, target)`
  For `event_ndims=1`:
    `tf.einsum("...a,...b->...ab", target, target)`
  For `event_ndims=2`:
    `tf.einsum("...ab,...cd->...abcd", target, target)`
  ...

  Args:
    target: Target `Tensor` for the `tf.einsum` computation.
    event_ndims: Both the number of dimensions that specify the event
      shape and the desired number of dimensions for cross product
      terms.

  Returns:
    outer_product: A `Tensor` with shape B + E + E for all pairwise
      products of `target` in the event dimensions.
  """
  assign_indices = ''.join(list(
      map(chr, range(ord('a'), ord('a') + event_ndims * 2))))
  first_indices = assign_indices[:event_ndims]
  second_indices = assign_indices[event_ndims:]
  einsum_formula = '...{},...{}->...{}'.format(
      first_indices, second_indices, assign_indices)
  return tf.einsum(einsum_formula, target, target)

def _float_dtype_like(dtype):
  if dtype_util.as_numpy_dtype(dtype) == np.int64:
    return tf.float64
  if dtype_util.is_integer(dtype):
    return tf.float32
  return dtype

@ac_decorator(omit_kwargs='name')
class RunningVariance(RunningCovariance):
  """A running variance computation.

  This is just an alias for `RunningCovariance`, with the `event_ndims` set to 0
  to compute variances.

  `RunningVariance` is meant to serve general streaming variance needs.
  For a specialized version that fits streaming over MCMC samples, see
  `VarianceReducer` in `tfp.experimental.mcmc`.
  """

  @classmethod
  def from_shape(cls, shape=(), dtype=tf.float32):
    """Starts a `RunningVariance` from shape and dtype metadata.

    Args:
      shape: Python `Tuple` or `TensorShape` representing the shape of incoming
        samples.  This is useful to supply if the `RunningVariance` will be
        carried by a `tf.while_loop`, so that broadcasting does not change the
        shape across loop iterations.
      dtype: Dtype of incoming samples and the resulting statistics.
        By default, the dtype is `tf.float32`. Any integer dtypes will be
        cast to corresponding floats (i.e. `tf.int32` will be cast to
        `tf.float32`), as intermediate calculations should be performing
        floating-point division.

    Returns:
      var: An empty `RunningCovariance`, ready for incoming samples.
    """
    return super().from_shape(shape, dtype, event_ndims=0)

  @classmethod
  def from_example(cls, example):
    """Starts a `RunningVariance` from an example.

    Args:
      example: A `Tensor`.  The `RunningVariance` will accept samples
        of the same dtype and broadcast-compatible shape as the example.

    Returns:
      var: An empty `RunningVariance`, ready for incoming samples.  Note
        that by convention, the supplied example is used only for
        initialization, but not counted as a sample.
    """
    return super().from_example(example, event_ndims=0)

  def variance(self, ddof=0):
    """Returns the variance accumulated so far.

    Args:
      ddof: Requested dynamic degrees of freedom for the variance calculation.
        For example, use `ddof=0` for population variance and `ddof=1` for
        sample variance. Defaults to the population variance.

    Returns:
      variance: An estimate of the variance.
    """
    return self.covariance(ddof)

  @classmethod
  def from_stats(cls, num_samples, mean, variance):
    """Initialize a `RunningVariance` object with given stats.

    This allows the user to initialize knowing the mean, variance, and number
    of samples seen so far.

    Args:
      num_samples: Scalar `float` `Tensor`, for number of examples already seen.
      mean: `float` `Tensor`, for starting mean of estimate.
      variance: `float` `Tensor`, for starting estimate of the variance.

    Returns:
      `RunningVariance` object, with given mean and variance estimate.
    """
    # TODO(b/173736911): Add this to RunningCovariance
    num_samples = tf.convert_to_tensor(num_samples, name='num_samples')
    mean = tf.convert_to_tensor(mean, name='mean')
    variance = tf.convert_to_tensor(variance, name='variance')
    return cls(num_samples=num_samples,
               mean=mean,
               sum_squared_residuals=num_samples * variance,
               event_ndims=0)

  def __repr__(self):
    return ('RunningVariance(\n'
            f'    num_samples={self.num_samples!r},\n'
            f'    mean={self.mean!r},\n'
            f'    sum_squared_residuals={self.sum_squared_residuals!r})')

@ac_decorator(omit_kwargs='name')
class RunningMean(ACClass):
  """Computes a running mean.

  In computation, samples can be provided individually or in chunks. A
  "chunk" of size M implies incorporating M samples into a single expectation
  computation at once, which is more efficient than one by one.

  `RunningMean` is meant to serve general streaming expectations.
  For a specialized version that fits streaming over MCMC samples, see
  `ExpectationsReducer` in `tfp.experimental.mcmc`.
  """

  def __init__(self, num_samples, mean):
    """Instantiates a `RunningMean`.

    Support batch accumulation of multiple independent running means.

    Args:
      num_samples: A `Tensor` counting the number of samples
        accumulated so far.
      mean: A `Tensor` broadcast-compatible with `num_samples` giving the
        current mean.
    """
    self.num_samples = num_samples
    self.mean = mean

  def tree_flatten(self):
    return (self.num_samples, self.mean), ()

  @classmethod
  def tree_unflatten(cls, _, tensors):
    return cls(*tensors)

  @classmethod
  def from_shape(cls, shape, dtype=tf.float32):
    """Initialize an empty `RunningMean`.

    Args:
      shape: Python `Tuple` or `TensorShape` representing the shape of
        incoming samples.
      dtype: Dtype of incoming samples and the resulting statistics.
        By default, the dtype is `tf.float32`. Any integer dtypes will be
        cast to corresponding floats (i.e. `tf.int32` will be cast to
        `tf.float32`), as intermediate calculations should be performing
        floating-point division.

    Returns:
      state: `RunningMean` representing a stream of no inputs.
    """
    dtype = _float_dtype_like(dtype)
    return cls(
        num_samples=tf.zeros((), dtype=dtype),
        mean=tf.zeros(shape, dtype))

  @classmethod
  def from_example(cls, example):
    """Initialize an empty `RunningMean`.

    Args:
      example: A `Tensor`.  The `RunningMean` will accept samples
        of the same dtype and broadcast-compatible shape as the example.

    Returns:
      state: `RunningMean` representing a stream of no inputs.  Note
        that by convention, the supplied example is used only for
        initialization, but not counted as a sample.
    """
    return cls.from_shape(ps.shape(example), example.dtype)

  def update(self, new_sample, axis=None):
    """Update the `RunningMean` with a new sample.

    The update formula is from Philippe Pebay (2008) [1] and is identical to
    that used to calculate the intermediate mean in
    `tfp.experimental.stats.RunningCovariance` and
    `tfp.experimental.stats.RunningVariance`.

    Args:
      new_sample: Incoming `Tensor` sample with shape and dtype compatible with
        those used to form the `RunningMean`.
      axis: If chunking is desired, this is an integer that specifies the axis
        with chunked samples. For individual samples, set this to `None`. By
        default, samples are not chunked (`axis` is None).

    Returns:
      mean: `RunningMean` updated to the new sample.

    #### References
    [1]: Philippe Pebay. Formulas for Robust, One-Pass Parallel Computation of
         Covariances and Arbitrary-Order Statistical Moments. _Technical Report
         SAND2008-6212_, 2008.
         https://prod-ng.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf
    """
    dtype = self.mean.dtype
    new_sample = tf.nest.map_structure(
        lambda new_sample: tf.cast(new_sample, dtype=dtype),
        new_sample)
    if axis is None:
      chunk_n = tf.constant(1, dtype=dtype)
      chunk_mean = new_sample
    else:
      chunk_n = tf.cast(ps.shape(new_sample)[axis], dtype=dtype)
      chunk_mean = tf.math.reduce_mean(new_sample, axis=axis)
    new_n = self.num_samples + chunk_n
    delta_mean = chunk_mean - self.mean
    new_mean = self.mean + chunk_n * delta_mean / new_n
    return RunningMean(new_n, new_mean)

  def __repr__(self):
    return ('RunningMean(\n'
            f'    num_samples={self.num_samples!r},\n'
            f'    mean={self.mean!r})')

@ac_decorator()
class RunningCentralMoments(ACClass):
  """Computes running central moments.

  `RunningCentralMoments` will compute arbitrary central moments in
  streaming fashion following the formula proposed by Philippe Pebay
  (2008) [1]. For reference, the formula we refer to is the incremental
  version of arbitrary moments (equation 2.9). Since the algorithm computes
  moments as a function of lower ones, even if not requested, all lower
  moments will be computed as well. The moments that are actually returned
  is specified by the `moment` parameter at initialization. Note, while
  any arbitrarily high central moment is theoretically supported,
  `RunningCentralMoments` cannot guarantee numerical stability for all
  moments.

  #### References
  [1]: Philippe Pebay. Formulas for Robust, One-Pass Parallel Computation of
        Covariances and Arbitrary-Order Statistical Moments. _Technical Report
        SAND2008-6212_, 2008.
        https://prod-ng.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf
  """

  def __init__(self, mean_state, exponentiated_residuals, desired_moments):
    """Constructs a `RunningCentralMoments`.

    All moments up to the maximum of the desired moments will be computed.

    Args:
      mean_state:  A `RunningMean` carrying the running mean estimate.
      exponentiated_residuals: A `Tensor` representing the sum of exponentiated
        residuals. This is a `Tensor` of shape `[max_moment - 1] +
        mean_state.mean.shape`, which contains the sum of the residuals raised
        to the kth power, for all `2 <= k <= max_moment`.
      desired_moments: A Python list of integers giving the moments to return.
        The maximum element of this list gives the number of moments that
        will be computed.
    """
    self.mean_state = mean_state
    self.exponentiated_residuals = exponentiated_residuals
    self.desired_moments = desired_moments

  def tree_flatten(self):
    return (self.mean_state,
            self.exponentiated_residuals), (self.desired_moments,)

  @classmethod
  def tree_unflatten(cls, metadata, tensors):
    return cls(*tensors, *metadata)

  @classmethod
  def from_shape(cls, shape, moment, dtype=tf.float32):
    """Returns an empty `RunningCentralMoments`.

    Args:
      shape: Python `Tuple` or `TensorShape` representing the shape of
        incoming samples.
      moment: Integer or iterable of integers that represent the
        desired moments to return.
      dtype: Dtype of incoming samples and the resulting statistics.
        By default, the dtype is `tf.float32`. Any integer dtypes will be
        cast to corresponding floats (i.e. `tf.int32` will be cast to
        `tf.float32`), as intermediate calculations should be performing
        floating-point division.

    Returns:
      state: `RunningCentralMoments` representing a stream of no
        inputs.
    """
    if isinstance(moment, (tuple, list, np.ndarray)):
      # we want to support numpy arrays too, but must convert to a list to not
      # confuse `tf.nest.map_structure` in `finalize`
      desired_moments = list(moment)
      max_moment = max(desired_moments)
    else:
      desired_moments = [moment]
      max_moment = moment
    dtype = _float_dtype_like(dtype)
    return cls(
        mean_state=RunningMean.from_shape(shape, dtype),
        exponentiated_residuals=tf.zeros(
            ps.concat([(max_moment - 1,), shape], axis=0), dtype),
        desired_moments=desired_moments)

  @classmethod
  def from_example(cls, example, moment):
    """Initialize an empty `RunningCentralMoments`.

    Args:
      example: A `Tensor`.  The `RunningCentralMoments` will accept
        samples of the same dtype and broadcast-compatible shape as
        the example.
      moment: Integer or iterable of integers that represent the
        desired moments to return.

    Returns:
      state: `RunningCentralMoments` representing a stream of no
        inputs.  Note that by convention, the supplied example is used
        only for initialization, but not counted as a sample.
    """
    return cls.from_shape(ps.shape(example), moment, example.dtype)

  def update(self, new_sample):
    """Update with a new sample.

    Args:
      new_sample: Incoming `Tensor` sample with shape and dtype compatible with
        those used to form the `RunningCentralMoments`.

    Returns:
      state: `RunningCentralMoments` updated to include the new sample.
    """
    shape = self.mean_state.mean.shape
    dtype = self.mean_state.mean.dtype
    n_2 = 1
    n_1 = self.mean_state.num_samples
    n = tf.cast(n_1 + n_2, dtype=dtype)
    delta_mean = new_sample - self.mean_state.mean
    new_mean_state = self.mean_state.update(new_sample)
    # The sum of exponentiated residuals can be thought of as an estimation
    # of the central moment before dividing through by the number of samples.
    # Since the first central moment is always 0, it simplifies update
    # logic to prepend an appropriate structure of zeros.
    old_res = tf.concat([
        tf.zeros(ps.concat([(1,), shape], axis=0), dtype),
        self.exponentiated_residuals], axis=0)
    # Not storing said zeros in the carried state, though
    new_exponentiated_residuals = []

    # the following two nested for loops calculate equation 2.9 in Pebay's
    # 2008 paper from smallest moment to highest.
    max_moment = max(self.desired_moments)
    for p in range(2, max_moment + 1):
      summation = tf.zeros(shape, dtype)
      for k in range(1, p - 1):
        adjusted_old_res = ((-delta_mean / n) ** k) * old_res[p - k - 1]
        summation += _n_choose_k(p, k) * adjusted_old_res
      # the `adj_term` refers to the final term in equation 2.9 and is not
      # transcribed exactly; rather, it's simplified to avoid having a
      # `(n - 1)` denominator.
      adj_term = (((delta_mean / n) ** p) * (n - 1) *
                  ((n - 1) ** (p - 1) + (-1) ** p))
      new_pth_residual = old_res[p - 1] + summation + adj_term
      new_exponentiated_residuals.append(new_pth_residual)

    return RunningCentralMoments(
        new_mean_state,
        # The cast is needed in case new_exponentiated_residuals is the empty
        # list, which will happen if the user requested only the first moment.
        exponentiated_residuals=tf.cast(
            tf.stack(new_exponentiated_residuals, axis=0), dtype=dtype),
        desired_moments=self.desired_moments)

  def moments(self):
    """Returns the central moments represented by this `RunningCentralMoments`.

    Returns:
      all_moments: A `Tensor` representing estimates of the requested central
        moments. Its leading dimension indexes the moment, in order of those
        requested (i.e. in order of `self.desired_moments`).
    """
    # prepend a structure of zeros for the first moment
    shape = self.mean_state.mean.shape
    dtype = self.mean_state.mean.dtype
    all_unfinalized_moments = tf.concat([
        tf.zeros(ps.concat([(1,), shape], axis=0), dtype),
        self.exponentiated_residuals], axis=0)
    all_moments = all_unfinalized_moments / tf.cast(
        self.mean_state.num_samples, dtype)
    desired_moment_indices = tf.convert_to_tensor(
        self.desired_moments, dtype=tf.int32) - 1
    return tf.gather(all_moments, desired_moment_indices)

  def __repr__(self):
    return (
        'RunningCentralMoments('
        f'    mean_state={self.mean_state!r},\n'
        f'    exponentiated_residuals={self.exponentiated_residuals!r},\n'
        f'    desired_moments={self.desired_moments!r})')

def _n_choose_k(n, k):
  """Computes nCk."""
  return math.factorial(n) // math.factorial(k) // math.factorial(n - k)

@ac_decorator(omit_kwargs='name')
class RunningPotentialScaleReduction(ACClass):
  """A running R-hat diagnostic.

  `RunningPotentialScaleReduction` uses Gelman and Rubin (1992)'s potential
  scale reduction (also known as R-hat) for chain convergence [1].

  If multiple independent R-hat computations are desired across a latent
  state, one should use a (possibly nested) collection for initialization
  parameters `independent_chain_ndims` and `shape`. Subsequent chain states
  used to update the streaming R-hat should mimic their identical structure.

  `RunningPotentialScaleReduction` also assumes that incoming samples have shape
  `[Ci1, Ci2,...,CiD] + A`. Dimensions `0` through `D - 1` index the
  `Ci1 x ... x CiD` independent chains to be tested for convergence to the same
  target. The remaining dimensions, `A`, represent the event shape and hence,
  can have any shape (even empty, which implies scalar samples). The number of
  independent chain dimensions is defined by the `independent_chain_ndims`
  parameter at initialization.

  `RunningPotentialScaleReduction` is meant to serve general streaming R-hat.
  For a specialized version that fits streaming over MCMC samples, see
  `PotentialScaleReductionReducer` in `tfp.experimental.mcmc`.

  #### References

  [1]: Andrew Gelman and Donald B. Rubin. Inference from Iterative Simulation
       Using Multiple Sequences. _Statistical Science_, 7(4):457-472, 1992.
  """

  def __init__(self, chain_variances, independent_chain_ndims):
    """Construct a `RunningPotentialScaleReduction`.

    Args:
      chain_variances: A `RunningVariance` or nested structure of
        `RunningVariance`s, giving the variance estimates for the variables of
        interest.
      independent_chain_ndims: A Python `int` or structure of Python `ints`
        parallel to `chain_variances` giving the number of leading dimensions in
        `chain_variances` that index the independent chains over which the
        potential scale reduction factor should be computed.  Must be at least
        1.
    """
    self.chain_variances = chain_variances
    self.independent_chain_ndims = independent_chain_ndims

  def tree_flatten(self):
    return (self.chain_variances,), (self.independent_chain_ndims,)

  @classmethod
  def tree_unflatten(cls, metadata, tensors):
    return cls(*tensors, *metadata)

  @classmethod
  def from_shape(cls, shape=(), independent_chain_ndims=1, dtype=tf.float32):
    """Starts an empty `RunningPotentialScaleReduction` from metadata.

    Args:
      shape: Python `Tuple` or `TensorShape` representing the shape of incoming
        samples. Using a collection implies that future samples will mimic that
        exact structure. This is useful to supply if the
        `RunningPotentialScaleReduction` will be carried by a `tf.while_loop`,
        so that broadcasting does not change the shape across loop iterations.
      independent_chain_ndims: Integer or Integer type `Tensor` with value
        `>= 1` giving the number of leading dimensions holding independent
        chain results to be tested for convergence. Using a collection
        implies that future samples will mimic that exact structure.
      dtype: Dtype of incoming samples and the resulting statistics.
        By default, the dtype is `tf.float32`. Any integer dtypes will be
        cast to corresponding floats (i.e. `tf.int32` will be cast to
        `tf.float32`), as intermediate calculations should be performing
        floating-point division.

    Returns:
      state: `RunningPotentialScaleReduction` representing a stream
        of no inputs.
    """
    dtype = tf.nest.map_structure(_float_dtype_like, dtype)

    dtype = nest_util.broadcast_structure(independent_chain_ndims, dtype)
    chain_variances = nest.map_structure_up_to(
        independent_chain_ndims,
        RunningVariance.from_shape,
        shape,
        dtype,
        check_types=False)
    return cls(chain_variances, independent_chain_ndims)

  @classmethod
  def from_example(cls, example, independent_chain_ndims=1):
    """Starts an empty `RunningPotentialScaleReduction` from metadata.

    Args:
      example: A `Tensor`.  The `RunningPotentialScaleReduction` will
        accept samples of the same dtype and broadcast-compatible
        shape as the example.
      independent_chain_ndims: Integer or Integer type `Tensor` with value
        `>= 1` giving the number of leading dimensions holding independent
        chain results to be tested for convergence. Using a collection
        implies that future samples will mimic that exact structure.

    Returns:
      state: `RunningPotentialScaleReduction` representing a stream of
        no inputs.  Note that by convention, the supplied example is
        used only for initialization, but not counted as a sample.
    """
    return cls.from_shape(
        shape=ps.shape(example), dtype=example.dtype,
        independent_chain_ndims=independent_chain_ndims)

  def update(self, new_sample):
    """Update the `RunningPotentialScaleReduction` with a new sample.

    Args:
      new_sample: Incoming `Tensor` sample or (possibly nested) collection of
        `Tensor`s with shape and dtype compatible with those used to form the
        `RunningPotentialScaleReduction`.

    Returns:
      state: `RunningPotentialScaleReduction` updated to include the new sample.
    """
    def _update_for_one_state(chain_variances, new_sample):
      """Updates the running variance for one group of Markov chains."""
      # TODO(axch): chunking could be reasonably added here by accepting and
      # including the chunked axis to the running variance object
      return chain_variances.update(new_sample)
    updated_chain_variancess = tf.nest.map_structure(
        _update_for_one_state,
        self.chain_variances,
        new_sample,
        check_types=False
    )
    return type(self)(updated_chain_variancess, self.independent_chain_ndims)

  def potential_scale_reduction(self):
    """Computes the potential scale reduction for samples accumulated so far.

    Returns:
      rhat: An estimate of the R-hat.
    """
    def _finalize_for_one_state(chain_ndims, chain_variances):
      """Calculates R-hat for one group of Markov chains."""
      # using notation from Brooks and Gelman (1998),
      # n := num samples / chain; m := number of chains
      n = chain_variances.num_samples
      shape = chain_variances.mean.shape
      m = tf.cast(
          functools.reduce((lambda x, y: x * y), (shape[:chain_ndims])),
          n.dtype)

      # b/n is the between-chain variance (the variance of the chain means)
      b_div_n = diagnostic._reduce_variance(  # pylint:disable=protected-access
          tf.convert_to_tensor(chain_variances.mean),
          axis=ps.range(chain_ndims),
          biased=False)

      # W is the within sequence variance (the mean of the chain variances)
      sum_of_chain_squared_residuals = tf.reduce_sum(
          chain_variances.sum_squared_residuals, axis=ps.range(chain_ndims))
      w = sum_of_chain_squared_residuals / (m * (n - 1))

      # the `true_variance_estimate` is denoted as sigma^2_+ in the 1998 paper
      true_variance_estimate = ((n - 1) / n) * w + b_div_n
      return ((m + 1.) / m) * true_variance_estimate / w - (n - 1.) / (m * n)

    return tf.nest.map_structure(
        _finalize_for_one_state,
        self.independent_chain_ndims,
        self.chain_variances,
        check_types=False
    )

  def __repr__(self):
    return (
        'RunningPotentialScaleReduction(\n'
        f'    chain_variances={self.chain_variances!r},\n'
        f'    independent_chain_ndims={self.independent_chain_ndims!r})')

if JAX_MODE:
  from jax import tree_util  # pylint: disable=g-import-not-at-top
  tree_util.register_pytree_node_class(RunningCentralMoments)
  tree_util.register_pytree_node_class(RunningCovariance)
  tree_util.register_pytree_node_class(RunningVariance)
  tree_util.register_pytree_node_class(RunningMean)
  tree_util.register_pytree_node_class(RunningPotentialScaleReduction)


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

namespace BrickPi.Uwp.Sensors
{
    public sealed class I2CData
    {
        public int Setting { get; set; }
        public int Address { get; set; }

        public int WriteBytes { get; set; }
        public int ReadBytes { get; set; }

        public byte[] ReadData = new byte[16];
        public byte[] WriteData = new byte[16];
    }

    public class I2CDataCollection : List<I2CData>
    {
        public I2CDataCollection() : this(8)
        {

        }

        public I2CDataCollection(int size)
        {
            for (int i = 0; i < size; i++)
            {
                this.Add(new I2CData());
            }
        }
    }

}


text:
import { compileHelp } from '../src/cli.js';
import * as utils from '../src/utils.js';
import * as log from '../src/log.js';
import { setConfigDirs } from '../src/store.js';
import allCommands from '../src/commands/index.js';

setConfigDirs('/path/to/.overcast');

utils.eachObject(allCommands, ({ commands }, name) => {
  utils.eachObject(commands, (subcommand) => {
    if (subcommand.alias === true) {
      return;
    }
    const subcommandName = subcommand.name && name !== subcommand.name ?
      ' ' + subcommand.name : '';
    console.log('### overcast ' + name + subcommandName);
    log.br();
    console.log('```');
    compileHelp(subcommand, true);
    console.log('```');
    log.br();
  });
});


text:
package com.marklogic.quickstart.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
    private static final long serialVersionUID = 4082892689428870767L;
}


text:
function g = runICPSelection(obj, p, g, PC, VH)

msg('S', {g.procICP{:} 'SELECTION'}, 'LogLevel', 'basic');

% List of query point clouds
PCQueryList = sort(unique(p.PairList(:,1)));

for i = 1:numel(PCQueryList)

    % Index of actual query point cloud
    idxPCQuery = PCQueryList(i);

    % Load point cloud?
    if p.SubsetRadius > 0, PC{idxPCQuery} = obj.loadPC(idxPCQuery); end

    % Uniform sampling
    if p.UniformSamplingDistance(idxPCQuery) ~= 0, % if voxel size is zero, no uniform sampling
        PC{idxPCQuery}.select('UniformSampling', p.UniformSamplingDistance(idxPCQuery));
    end

    % Normals needed?
    if p.NormalSubsampling(idxPCQuery) || p.MaxLeverageSubsampling(idxPCQuery)

        if ~isfield(PC{idxPCQuery}.A, 'nx') % calculate normals only if not already present

            % Estimate normals
            PC{idxPCQuery}.normals(p.PlaneSearchRadius);

            % Deactivate points where normal computation was not successful
            PC{idxPCQuery}.act(isnan(PC{idxPCQuery}.A.nx)) = false;

        end

    end

    % Save activated points
    actOrig = PC{idxPCQuery}.act;

    % List of all search point clouds for actual query point cloud
    PCSearchList = p.PairList(p.PairList(:,1) == idxPCQuery,2);
    PCSearchList = sort(unique(PCSearchList));

    for s = 1:numel(PCSearchList)

        % Index of actual search point cloud
        idxPCSearch = PCSearchList(s);

        % Index of actual pair
        actPair = p.PairList(:,1) == idxPCQuery & p.PairList(:,2) == idxPCSearch;

        % Consider overlap
        % PC{idxPCQuery}.select('RangeSearch', VH{idxPCSearch}(:, 4:6), sqrt(3)*p.HullVoxelSize);
        PC{idxPCQuery}.select('InVoxelHull', VH{idxPCSearch}(:, 1:3), p.HullVoxelSize);

        if p.RandomSubsampling(idxPCQuery)     , PC{idxPCQuery}.select('RandomSampling'     , p.SubsamplingPercentPoi); end
        if p.NormalSubsampling(idxPCQuery)     , PC{idxPCQuery}.select('NormalSampling'     , p.SubsamplingPercentPoi); end
        if p.MaxLeverageSubsampling(idxPCQuery), PC{idxPCQuery}.select('MaxLeverageSampling', p.SubsamplingPercentPoi); end

        % Logical vector with query points for actual pair
        g.qp{actPair,1} = PC{idxPCQuery}.act;

        % Query point coordinates for selection of subsets
        if p.SubsetRadius > 0, g.qpX{actPair,1} = PC{idxPCQuery}.X(PC{idxPCQuery}.act,:); end

        % Restore activated points
        PC{idxPCQuery}.act = actOrig;

    end

    % Delete point cloud again?
    if p.SubsetRadius > 0, PC{idxPCQuery} = []; end

end

msg('E', {g.procICP{:} 'SELECTION'}, 'LogLevel', 'basic');

end


text:
function free(c::Constraint)
    ccall(dlsym(libchipmunk, :cpConstraintFree), Void, (Ptr{Void},), c.ptr)
end

function get_space(c::Constraint)
    Space(ccall(dlsym(libchipmunk, :cpConstraintGetSpace), Ptr{Void}, (Ptr{Void},), c.ptr))
end

function get_bodyA(c::Constraint)
    Body(ccall(dlsym(libchipmunk, :cpConstraintGetBodyA), Ptr{Void}, (Ptr{Void},), c.ptr))
end

function get_bodyB(c::Constraint)
    Body(ccall(dlsym(libchipmunk, :cpConstraintGetBodyB), Ptr{Void}, (Ptr{Void},), c.ptr))
end

function get_max_force(c::Constraint)
    ccall(dlsym(libchipmunk, :cpConstraintGetMaxForce), Cdouble, (Ptr{Void},), c.ptr)
end

function set_max_force(c::Constraint, max_force::Real)
    ccall(dlsym(libchipmunk, :cpConstraintSetMaxForce), Void, (Ptr{Void}, Cdouble,), c.ptr, max_force)
end

function get_error_bias(c::Constraint)
    ccall(dlsym(libchipmunk, :cpConstraintGetErrorBias), Cdouble, (Ptr{Void},), c.ptr)
end

function set_error_bias(c::Constraint, error_bias::Real)
    ccall(dlsym(libchipmunk, :cpConstraintSetErrorBias), Void, (Ptr{Void}, Cdouble,), c.ptr, error_bias)
end

function get_max_bias(c::Constraint)
    ccall(dlsym(libchipmunk, :cpConstraintGetMaxBias), Cdouble, (Ptr{Void},), c.ptr)
end

function set_max_bias(c::Constraint, max_bias::Real)
    ccall(dlsym(libchipmunk, :cpConstraintSetMaxBias), Void, (Ptr{Void}, Cdouble,), c.ptr, max_bias)
end

function get_collide_bodies(c::Constraint)
    ccall(dlsym(libchipmunk, :cpConstraintGetCollideBodies), Bool, (Ptr{Void},), c.ptr)
end

function set_collide_bodies(c::Constraint, collide_bodies::Bool)
    ccall(dlsym(libchipmunk, :cpConstraintSetCollideBodies), Void, (Ptr{Void}, Int32,), c.ptr, collide_bodies)
end

function get_userdata(c::Constraint)
    ccall(dlsym(libchipmunk, :cpConstraintGetUserData), Ptr{Void}, (Ptr{Void},), c.ptr)
end

function set_userdata(c::Constraint, userdata::Ptr{Void})
    ccall(dlsym(libchipmunk, :cpConstraintSetUserData), Void, (Ptr{Void}, Ptr{Void},), c.ptr, userdata)
end

function get_impulse(c::Constraint)
    ccall(dlsym(libchipmunk, :cpConstraintGetImpulse), Cdouble, (Ptr{Void},), c.ptr)
end

export free, get_space, get_bodyA, get_bodyB, get_max_force, set_max_force, get_error_bias,
set_error_bias, get_max_bias, set_max_bias, get_collide_bodies, set_collide_bodies, get_userdata,
set_userdata, get_impulse


text:
import unittest

from rpaas import plan, storage

class MongoDBStorageTestCase(unittest.TestCase):

    def setUp(self):
        self.storage = storage.MongoDBStorage()
        self.storage.db[self.storage.quota_collection].remove()
        self.storage.db[self.storage.plans_collection].remove()
        self.storage.db[self.storage.plans_collection].insert(
            {"_id": "small",
             "description": "some cool plan",
             "config": {"serviceofferingid": "abcdef123456"}}
        )
        self.storage.db[self.storage.plans_collection].insert(
            {"_id": "huge",
             "description": "some cool huge plan",
             "config": {"serviceofferingid": "abcdef123459"}}
        )

    def test_set_team_quota(self):
        q = self.storage.set_team_quota("myteam", 8)
        used, quota = self.storage.find_team_quota("myteam")
        self.assertEqual([], used)
        self.assertEqual(8, quota)
        self.assertEqual(used, q["used"])
        self.assertEqual(quota, q["quota"])

    def test_list_plans(self):
        plans = self.storage.list_plans()
        expected = [
            {"name": "small", "description": "some cool plan",
             "config": {"serviceofferingid": "abcdef123456"}},
            {"name": "huge", "description": "some cool huge plan",
             "config": {"serviceofferingid": "abcdef123459"}},
        ]
        self.assertEqual(expected, [p.to_dict() for p in plans])

    def test_find_plan(self):
        plan = self.storage.find_plan("small")
        expected = {"name": "small", "description": "some cool plan",
                    "config": {"serviceofferingid": "abcdef123456"}}
        self.assertEqual(expected, plan.to_dict())
        with self.assertRaises(storage.PlanNotFoundError):
            self.storage.find_plan("something that doesn't exist")

    def test_store_plan(self):
        p = plan.Plan(name="super_huge", description="very huge thing",
                      config={"serviceofferingid": "abcdef123"})
        self.storage.store_plan(p)
        got_plan = self.storage.find_plan(p.name)
        self.assertEqual(p.to_dict(), got_plan.to_dict())

    def test_store_plan_duplicate(self):
        p = plan.Plan(name="small", description="small thing",
                      config={"serviceofferingid": "abcdef123"})
        with self.assertRaises(storage.DuplicateError):
            self.storage.store_plan(p)

    def test_update_plan(self):
        p = plan.Plan(name="super_huge", description="very huge thing",
                      config={"serviceofferingid": "abcdef123"})
        self.storage.store_plan(p)
        self.storage.update_plan(p.name, description="wat?",
                                 config={"serviceofferingid": "abcdef123459"})
        p = self.storage.find_plan(p.name)
        self.assertEqual("super_huge", p.name)
        self.assertEqual("wat?", p.description)
        self.assertEqual({"serviceofferingid": "abcdef123459"}, p.config)

    def test_update_plan_partial(self):
        p = plan.Plan(name="super_huge", description="very huge thing",
                      config={"serviceofferingid": "abcdef123"})
        self.storage.store_plan(p)
        self.storage.update_plan(p.name, config={"serviceofferingid": "abcdef123459"})
        p = self.storage.find_plan(p.name)
        self.assertEqual("super_huge", p.name)
        self.assertEqual("very huge thing", p.description)
        self.assertEqual({"serviceofferingid": "abcdef123459"}, p.config)

    def test_update_plan_not_found(self):
        with self.assertRaises(storage.PlanNotFoundError):
            self.storage.update_plan("my_plan", description="woot")

    def test_delete_plan(self):
        p = plan.Plan(name="super_huge", description="very huge thing",
                      config={"serviceofferingid": "abcdef123"})
        self.storage.store_plan(p)
        self.storage.delete_plan(p.name)
        with self.assertRaises(storage.PlanNotFoundError):
            self.storage.find_plan(p.name)

    def test_delete_plan_not_found(self):
        with self.assertRaises(storage.PlanNotFoundError):
            self.storage.delete_plan("super_huge")

    def test_instance_metadata_storage(self):
        self.storage.store_instance_metadata("myinstance", plan="small")
        inst_metadata = self.storage.find_instance_metadata("myinstance")
        self.assertEqual({"_id": "myinstance",
                          "plan": "small"}, inst_metadata)
        self.storage.store_instance_metadata("myinstance", plan="medium")
        inst_metadata = self.storage.find_instance_metadata("myinstance")
        self.assertEqual({"_id": "myinstance", "plan": "medium"}, inst_metadata)
        self.storage.remove_instance_metadata("myinstance")
        inst_metadata = self.storage.find_instance_metadata("myinstance")
        self.assertIsNone(inst_metadata)


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

<!--
  Description:  Multiple Attribution elements
  Expect:       DuplicateElement{element:Attribution}
-->

<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
  <ShortName>Web Search</ShortName>
  <Attribution>John Smith</Attribution>
  <Attribution>Jane Doe</Attribution>
  <Description>Use Example.com to search the Web.</Description>
  <Tags>example web</Tags>
  <Contact>admin@example.com</Contact>
  <Url type="application/rss+xml"
       template="http://example.com/?q={searchTerms}&pw={startPage?}&format=rss"/>
</OpenSearchDescription>


text:
package org.ehcache.impl.internal.copy;

import org.ehcache.impl.copy.SerializingCopier;
import org.ehcache.spi.serialization.Serializer;
import org.junit.Test;

import java.nio.ByteBuffer;

import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Created by alsu on 20/08/15.
 */
public class SerializingCopierTest {

  @Test
  public void testCopy() throws Exception {
    @SuppressWarnings("unchecked")
    Serializer<String> serializer = mock(Serializer.class);
    String in = new String("foo");
    ByteBuffer buff = mock(ByteBuffer.class);
    when(serializer.serialize(in)).thenReturn(buff);
    when(serializer.read(buff)).thenReturn(new String("foo"));

    SerializingCopier<String> serializingCopier = new SerializingCopier<String>(serializer);
    String copied = serializingCopier.copy("foo");
    assertNotSame(in, copied);
    assertEquals(in, copied);
  }

  @Test(expected = NullPointerException.class)
  public void testThrowsNPEWhenNoSerializerPassedToConstructor() {
    new SerializingCopier<Object>(null);
  }
}


text:
package com.siyeh.ig.threading;

import com.intellij.psi.*;
import com.intellij.psi.controlFlow.ControlFlowUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.ParenthesesUtils;
import com.siyeh.ig.psiutils.SynchronizationUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class NonAtomicOperationOnVolatileFieldInspection extends BaseInspection {

  @Override
  @NotNull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message("non.atomic.operation.on.volatile.field.display.name");
  }

  @Override
  @NotNull
  protected String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message("non.atomic.operation.on.volatile.field.problem.descriptor");
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new NonAtomicOperationOnVolatileFieldVisitor();
  }

  private static class NonAtomicOperationOnVolatileFieldVisitor extends BaseInspectionVisitor {

    @Override
    public void visitAssignmentExpression(@NotNull PsiAssignmentExpression expression) {
      super.visitAssignmentExpression(expression);
      final PsiExpression rhs = ParenthesesUtils.stripParentheses(expression.getRExpression());
      if (rhs == null) {
        return;
      }
      final PsiExpression lhs = expression.getLExpression();
      final PsiField volatileField = findNonSynchronizedVolatileField(lhs);
      if (volatileField == null) {
        return;
      }
      final IElementType tokenType = expression.getOperationTokenType();
      if (tokenType.equals(JavaTokenType.PLUSEQ) ||
          tokenType.equals(JavaTokenType.MINUSEQ) ||
          tokenType.equals(JavaTokenType.ASTERISKEQ) ||
          tokenType.equals(JavaTokenType.DIVEQ) ||
          tokenType.equals(JavaTokenType.ANDEQ) ||
          tokenType.equals(JavaTokenType.OREQ) ||
          tokenType.equals(JavaTokenType.XOREQ) ||
          tokenType.equals(JavaTokenType.PERCEQ) ||
          tokenType.equals(JavaTokenType.LTLTEQ) ||
          tokenType.equals(JavaTokenType.GTGTEQ) ||
          tokenType.equals(JavaTokenType.GTGTGTEQ)) {
        registerError(lhs);
        return;
      }
      if (isOnTheFly() && !volatileField.hasModifierProperty(PsiModifier.PRIVATE)) {
        return;
      }
      rhs.accept(new JavaRecursiveElementWalkingVisitor() {
        @Override
        public void visitReferenceExpression(PsiReferenceExpression reference) {
          if (reference.isReferenceTo(volatileField) && ControlFlowUtil.isUnqualified(reference)) {
            stopWalking();
            final PsiElement referenceNameElement = ((PsiJavaCodeReferenceElement)lhs).getReferenceNameElement();
            if (referenceNameElement != null) {
              registerError(referenceNameElement);
            }
            return;
          }
          super.visitReferenceExpression(reference);
        }
      });
    }

    @Override
    public void visitUnaryExpression(PsiUnaryExpression expression) {
      super.visitUnaryExpression(expression);
      if (!PsiUtil.isIncrementDecrementOperation(expression)) {
        return;
      }
      final PsiExpression operand = expression.getOperand();
      if (operand == null) {
        return;
      }
      final PsiField volatileField = findNonSynchronizedVolatileField(operand);
      if (volatileField == null) {
        return;
      }
      registerError(operand);
    }

    @Nullable
    private static PsiField findNonSynchronizedVolatileField(PsiExpression expression) {
      if (!(expression instanceof PsiReferenceExpression)) {
        return null;
      }
      final PsiReferenceExpression reference = (PsiReferenceExpression)expression;
      if (!ControlFlowUtil.isUnqualified(reference)) {
        return null;
      }
      final PsiElement referent = reference.resolve();
      if (!(referent instanceof PsiField)) {
        return null;
      }
      final PsiField field = (PsiField)referent;
      if (!field.hasModifierProperty(PsiModifier.VOLATILE)) {
        return null;
      }
      if (SynchronizationUtil.isInSynchronizedContext(reference)) {
        return null;
      }
      return field;
    }
  }
}


text:
module Amanuensis
  class Push
    extend Interchange.new(:run)
  end
end


text:
<%= ob.polyT('wallet.receiveMoney.btnCancel') %>

<%= ob.polyT('wallet.receiveMoney.title') %>

  <div class="rowLg <% if (ob.fetching) print('invisible') %>">
    <img src="<%= ob.qrDataUri %>">

  <div class="rowMd receiveAddressWrap <% if (ob.fetching) print('invisible') %>">

Copied

    <%= ob.address %>

  <div class="spinnerWrap <% if (!ob.fetching) print('hide') %>">
    <%= ob.spinner() %>

      <% if (ob.currencyMod.getServerCurrency().canShapeShiftIntoWallet) { %>
      <button class="btn btnThin clrP clrBr clrSh2 flexNoShrink js-fundViaShapeshift">

        <%= ob.polyT('wallet.receiveMoney.btnFundViaShapeshift') %>
      </button>
      <% } %>

        <% serverCur = ob.currencyMod.getServerCurrency() %>
        <% if (serverCur.needCoinLink) { %>
          <%= ob.crypto.cryptoIcon({ className: 'margRSm'}) %>
          <a href="<%= serverCur.needCoinLink %>" class="clrT txB txU">
            <%= ob.polyT('wallet.receiveMoney.needCoinLink', { cur: serverCur.name }) %>

        <% } %>