text:
package com.ge.protein.util;

import retrofit2.Response;

/**
 * Page link class to be used to determine the links to other pages of request
 * responses encoded in the current response. These will be present if the
 * result set size exceeds the per page limit.
 */
public class PageLinks {

    private static final String DELIM_LINKS = ","; //$NON-NLS-1$

    private static final String DELIM_LINK_PARAM = ";"; //$NON-NLS-1$

    private static final String HEAD_LINK = "Link";

    private static final String META_REL = "rel"; //$NON-NLS-1$
    private static final String META_NEXT = "next"; //$NON-NLS-1$
    private static final String META_PREV = "prev"; //$NON-NLS-1$

    private String next;
    private String prev;

    /**
     * Parse links from executed method
     */
    public PageLinks(Response response) {
        String linkHeader = response.headers().get(HEAD_LINK);
        if (linkHeader != null) {
            String[] links = linkHeader.split(DELIM_LINKS);
            for (String link : links) {
                String[] segments = link.split(DELIM_LINK_PARAM);
                if (segments.length < 2) {
                    continue;
                }

                String linkPart = segments[0].trim();
                if (!linkPart.startsWith("<") || !linkPart.endsWith(
                        ">")) //$NON-NLS-1$ //$NON-NLS-2$
                {
                    continue;
                }
                linkPart = linkPart.substring(1, linkPart.length() - 1);

                for (int i = 1; i < segments.length; i++) {
                    String[] rel = segments[i].trim().split("="); //$NON-NLS-1$
                    if (rel.length < 2 || !META_REL.equals(rel[0])) {
                        continue;
                    }

                    String relValue = rel[1];
                    if (relValue.startsWith("\"") && relValue.endsWith(
                            "\"")) //$NON-NLS-1$ //$NON-NLS-2$
                    {
                        relValue = relValue.substring(1, relValue.length() - 1);
                    }

                    if (META_NEXT.equals(relValue)) {
                        next = linkPart;
                    } else if (META_PREV.equals(relValue)) {
                        prev = linkPart;
                    }
                }
            }
        }
    }

    /**
     * @return next
     */
    public String getNext() {
        return next;
    }

    /**
     * @return prev
     */
    public String getPrev() {
        return prev;
    }
}


text:
{-# LANGUAGE RecordWildCards, NegativeLiterals, DeriveDataTypeable #-}
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}

-- | A toy module to implement fullscreen effects.
--
-- This works by rendering to a texture with a shader, and then rendering again
-- to another, same sized texture with another shader, using the first texture
-- as source data.
--
-- You can implement interesting visual effects such as Conway's Game of Life
-- in GPU and see the results with this module.
--

module Caramia.Extras.ShaderEffects
    ( newShaderEffects
    , stepShaderEffects
    , ShaderEffects() )
    where

import Caramia.Prelude
import Caramia
import Caramia.Extras.MonotonicTime
import qualified Data.Text as T
import qualified Data.IntMap.Strict as IM
import Foreign.Marshal.Array
import Foreign.C.Types
import Foreign.Storable
import Foreign
import System.Random

-- | Creates new shader effects.
--
-- You need to give a fragment shader source code to this function.
--
-- Several uniform values are provided if they are defined in the shader:
--
-- @
--     resolution           ivec2     Gives the current size of the texture.
--     pixel_size           vec2      Size of one pixel.
--     monotonic_time       float     Gives the current time in seconds
--     previous             sampler2D The texture of the previous iteration
-- @
--
-- Also, some attributes that can be used:
--
-- @
--     xy           vec2              The xy coordinates of the current
--                                    fragment.
--     uv           vec2              The uv coordinates of the current
--                                    fragment.
-- @
--
-- The texture used is a 32-bit floating point texture with all RGBA channels
-- available.
--
-- Initially the textures are filled with uniformily random data.
--
-- Write the results to attribute location 0.
newShaderEffects :: T.Text -> Int -> Int -> IO ShaderEffects
newShaderEffects shader_code w h = do
    fs <- newShader shader_code Fragment
    fs_unload <- newShader unloadFragmentCode Fragment
    vs <- newShader quadVertexCode Vertex
    pl <- newPipeline [fs, vs]
    pl_unload <- newPipeline [fs_unload, vs]

    tex_loc <- getUniformLocation "tex" pl_unload
    setUniform (0::Int) tex_loc pl_unload

    res_loc <- getUniformLocation "resolution" pl
    res_unload_loc <- getUniformLocation "resolution" pl_unload
    mon_loc <- getUniformLocation "monotonic_time" pl
    previous_loc <- getUniformLocation "previous" pl
    psize_loc <- getUniformLocation "pixel_size" pl

    tex  <- makeTex
    tex2 <- makeTex

    noise <- allocaArray (w*h*4) $ \noises_ptr -> do
        for_ [0..(w*h*4) - 1] $ \idx -> do
            rnd <- randomRIO (0, 1)
            pokeElemOff noises_ptr idx (rnd :: Float)

        newBuffer defaultBufferCreation
                        { accessHints = (Static, Draw)
                        , size = bytes_used
                        , initialData = Just (castPtr noises_ptr)
                        , accessFlags = NoAccess }

    uploadToTexture (uploading2D noise w h FFloat URGBA) tex
    uploadToTexture (uploading2D noise w h FFloat URGBA) tex2

    fbuf1 <- newFramebuffer [(ColorAttachment 0, frontTextureTarget tex)]
    fbuf2 <- newFramebuffer [(ColorAttachment 0, frontTextureTarget tex2)]
    ref <- newIORef ((tex2, fbuf1), (tex, fbuf2))

    setUniform (0::Int) previous_loc pl
    setUniform (w, h) res_loc pl
    setUniform ( 1.0/fromIntegral w :: Float
               , 1.0/fromIntegral h :: Float) psize_loc pl
    setUniform (w, h) res_unload_loc pl_unload

    vao <- newQuadVAO

    return ShaderEffects {
        resolutionLoc = res_loc
      , unloadResolutionLoc = res_unload_loc
      , monotonicLoc = mon_loc
      , pixelSizeLoc = psize_loc
      , texes = ref
      , vao = vao
      , sePipeline = pl
      , unloadPipeline = pl_unload }
  where
    bytes_used = w*h*4*4

    makeTex = newTexture textureSpecification {
                  mipmapLevels = 1
                , imageFormat = RGBA32F
                , topology = Tex2D { width2D = w
                                   , height2D = h }
                }

newQuadVAO :: IO VAO
newQuadVAO = do
    buf <- withArray
                [ -128, -128
                ,  127, -128
                , -128,  127 :: Int8
                ,  127,  127 ] $ \ptr ->
        newBuffer defaultBufferCreation {
                accessHints = (Static, Draw)
                , size = sizeOf (undefined :: Int8) * 8
                , initialData = Just (castPtr ptr)
                , accessFlags = NoAccess }

    vao <- newVAO
    sourceVertexData buf defaultSourcing
        { components = 2
        , attributeIndex = 0
        , normalize = True
        , integerMapping = False
        , sourceType = SInt8 }
        vao
    return vao

stepShaderEffects :: ShaderEffects -> IO ()
stepShaderEffects (ShaderEffects {..}) = do
    tm <- getMonotonicTime
    ((tex_src, fbuf), (tex_dst, _)) <- atomicModifyIORef' texes $ \(t1, t2) ->
        ( (t2, t1), (t1, t2) )

    setUniform (tm :: Float) monotonicLoc sePipeline
    draw drawCommand
         { primitiveType = TriangleStrip
         , primitivesVAO = vao
         , numIndices = 4
         , sourceData = Primitives { firstIndex = 0 } }
         defaultDrawParams
         { pipeline = sePipeline
         , blending = nopBlend
         , targetFramebuffer = fbuf
         , bindTextures = IM.fromList [(0, tex_src)] }
    draw drawCommand
         { primitiveType = TriangleStrip
         , primitivesVAO = vao
         , numIndices = 4
         , sourceData = Primitives { firstIndex = 0 } }
         defaultDrawParams
         { pipeline = unloadPipeline
         , blending = nopBlend
         , bindTextures = IM.fromList [(0, tex_dst)] }

data ShaderEffects = ShaderEffects
    { resolutionLoc :: !UniformLocation
    , unloadResolutionLoc :: !UniformLocation
    , monotonicLoc  :: !UniformLocation
    , pixelSizeLoc  :: !UniformLocation
    , texes         :: !(IORef ((Texture, Framebuffer)
                        , (Texture, Framebuffer)))
    , vao           :: !VAO
    , sePipeline      :: !Pipeline
    , unloadPipeline :: !Pipeline }
    deriving ( Eq, Typeable )

unloadFragmentCode :: T.Text
unloadFragmentCode =
    "#version 330\n" <>
    "uniform sampler2D tex;\n" <>
    "in vec2 uv;\n" <>
    "layout (location = 0) out vec4 color;\n" <>
    "void main() {\n" <>
    "    color = texture(tex, uv);\n" <>
    "}\n"

quadVertexCode :: T.Text
quadVertexCode =
    "#version 330\n" <>
    "layout (location = 0) in vec2 pos;\n" <>
    "uniform ivec2 resolution;\n" <>
    "out vec2 xy;\n" <>
    "out vec2 uv;\n" <>
    "void main() {\n" <>
    "    uv = ((pos + vec2(1.0))*0.5);\n" <>
    "    xy = uv * vec2(resolution);\n" <>
    "    gl_Position = vec4(pos, 0.0, 1.0);\n" <>
    "}\n"

redpajama_set_name: RedPajamaGithub


text:
package sune.ssp.secure;

import java.security.Key;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLSocket;

import sune.ssp.ServerClient;
import sune.ssp.data.Data;
import sune.ssp.data.PublicKeyData;
import sune.ssp.etc.Identificator;
import sune.ssp.event.ServerEvent;
import sune.ssp.util.Serialization;
import sune.util.crypt.CryptMethod;

public class SecureServerClient extends ServerClient {

	private PublicKey publicKey;
	private SymmetricKey symmetricKey;
	private volatile boolean publicKeySent;
	private volatile boolean useCrypt;

	private List<DataHolder> cannotCrypt;
	private static class DataHolder {
		public final Data data;
		public final Identificator identificator;
		public final String receiver;

		public DataHolder(Data data,
				Identificator identificator, String receiver) {
			this.data 		   = data;
			this.identificator = identificator;
			this.receiver 	   = receiver;
		}
	}

	private CryptMethod cryptMethod;

	protected SecureServerClient(SecureServer server, SSLSocket socket) {
		super(server, socket);
		cannotCrypt = new ArrayList<>();
		cryptMethod = server.getCryptMethod();
		server.addListener(ServerEvent.CLIENT_INFO_RECEIVED, (info) -> {
			if(getIdentificator().equals(info.getUUID())) {
				useCrypt = true;
			}
		});
	}

	@Override
	protected Data preProcessData(Data data) {
		if(data instanceof CryptedData) {
			CryptedData cdata = (CryptedData) data;
			Key encryptionKey = cdata.getKey();
			if(encryptionKey instanceof PublicKey) {
				SecureServer sserver = (SecureServer) server;
				String decrypted = sserver.getSession().decrypt(cdata.getData());
				Object object 	 = Serialization.deserializeFromString(decrypted);
				symmetricKey 	 = new SymmetricKey((String) object);
				// Add the symmetric key to the known server keys
				((SecureServer) server).addSymmetricKey(
					getIP(), symmetricKey);
				// Send all the data that could not have been encryted.
				for(DataHolder holder : cannotCrypt) {
					addDataToSend(holder.data,
								  holder.identificator,
								  holder.receiver);
				}
				cannotCrypt.clear();
				cannotCrypt = null;
			} else if(encryptionKey instanceof SymmetricKey) {
				return Serialization.<Data>deserializeFromString(
					cryptMethod.decrypt(cdata.getData(),
						symmetricKey.getKey()));
			}
		}
		return super.preProcessData(data);
	}

	@Override
	protected boolean onDataReceived(Data data) {
		if(data instanceof PublicKeyData) {
			SecureServer sserver = (SecureServer) server;
			PublicKeyData pkdata = (PublicKeyData) data;
			publicKey 			 = pkdata.getPublicKey();
			sserver.addPublicKey(getIP(), publicKey);
			new Thread(() -> {
				// Send the public key of the server to the client
				sendWait(new PublicKeyData(sserver.getPublicKey()));
				publicKeySent = true;
			}).start();
			return false;
		}
		return super.onDataReceived(data);
	}

	@Override
	protected void addDataToSend(Data data, Identificator identificator, String receiver) {
		if(useCrypt) {
			// We have to use the encryption but we do not have the key
			// that is used to encrypt the data, so we have to wait till
			// the key is delivered.
			if(symmetricKey == null && cannotCrypt != null) {
				cannotCrypt.add(new DataHolder(
					data, identificator, receiver));
				return;
			}
			// Encrypt the data using client's symmetric key
			data = new CryptedData(symmetricKey, data, cryptMethod);
		}
		super.addDataToSend(data, identificator, receiver);
	}

	public SymmetricKey getSymmetricKey() {
		return symmetricKey;
	}

	public PublicKey getPublicKey() {
		return publicKey;
	}

	public boolean isPublicKeySent() {
		return publicKeySent;
	}

	@Override
	public boolean isSecure() {
		return true;
	}
}


text:
class PdrClient::PdrClientController < PdrClient::ApplicationController
  def index
  end
end


text:
<?php
return array (
  '{userName} created a new note {noteName}.' => '{userName} Oprettede et nyt notat {noteName}.',
);


text:
require 'base64'

module Aws
  module S3
    module EncryptionV2
      # @api private
      class KmsCipherProvider

        def initialize(options = {})
          @kms_key_id = validate_kms_key(options[:kms_key_id])
          @kms_client = options[:kms_client]
          @key_wrap_schema = validate_key_wrap(
            options[:key_wrap_schema]
          )
          @content_encryption_schema = validate_cek(
            options[:content_encryption_schema]
          )
        end

        # @return [Array<Hash,Cipher>] Creates and returns a new encryption
        #   envelope and encryption cipher.
        def encryption_cipher(options = {})
          validate_key_for_encryption
          encryption_context = build_encryption_context(@content_encryption_schema, options)
          key_data = @kms_client.generate_data_key(
            key_id: @kms_key_id,
            encryption_context: encryption_context,
            key_spec: 'AES_256'
          )
          cipher = Utils.aes_encryption_cipher(:GCM)
          cipher.key = key_data.plaintext
          envelope = {
            'x-amz-key-v2' => encode64(key_data.ciphertext_blob),
            'x-amz-iv' => encode64(cipher.iv = cipher.random_iv),
            'x-amz-cek-alg' => @content_encryption_schema,
            'x-amz-tag-len' => (AES_GCM_TAG_LEN_BYTES * 8).to_s,
            'x-amz-wrap-alg' => @key_wrap_schema,
            'x-amz-matdesc' => Json.dump(encryption_context)
          }
          cipher.auth_data = '' # auth_data must be set after key and iv
          [envelope, cipher]
        end

        # @return [Cipher] Given an encryption envelope, returns a
        #   decryption cipher.
        def decryption_cipher(envelope, options = {})
          encryption_context = Json.load(envelope['x-amz-matdesc'])
          cek_alg = envelope['x-amz-cek-alg']

          case envelope['x-amz-wrap-alg']
          when 'kms'
            unless options[:security_profile] == :v2_and_legacy
              raise Errors::LegacyDecryptionError
            end
          when 'kms+context'
            if cek_alg != encryption_context['aws:x-amz-cek-alg']
              raise Errors::CEKAlgMismatchError
            end

            if encryption_context != build_encryption_context(cek_alg, options)
              raise Errors::DecryptionError, 'Value of encryption context from'\
                ' envelope does not match the provided encryption context'
            end
          when 'AES/GCM'
            raise ArgumentError, 'Key mismatch - Client is configured' \
                    ' with a KMS key and the x-amz-wrap-alg is AES/GCM.'
          when 'RSA-OAEP-SHA1'
            raise ArgumentError, 'Key mismatch - Client is configured' \
                    ' with a KMS key and the x-amz-wrap-alg is RSA-OAEP-SHA1.'
          else
            raise ArgumentError, 'Unsupported wrap-alg: ' \
                "#{envelope['x-amz-wrap-alg']}"
          end

          any_cmk_mode = false || options[:kms_allow_decrypt_with_any_cmk]
          decrypt_options = {
            ciphertext_blob: decode64(envelope['x-amz-key-v2']),
            encryption_context: encryption_context
          }
          unless any_cmk_mode
            decrypt_options[:key_id] = @kms_key_id
          end

          key = @kms_client.decrypt(decrypt_options).plaintext
          iv = decode64(envelope['x-amz-iv'])
          block_mode =
            case cek_alg
            when 'AES/CBC/PKCS5Padding'
              :CBC
            when 'AES/CBC/PKCS7Padding'
              :CBC
            when 'AES/GCM/NoPadding'
              :GCM
            else
              type = envelope['x-amz-cek-alg'].inspect
              msg = "unsupported content encrypting key (cek) format: #{type}"
              raise Errors::DecryptionError, msg
            end
          Utils.aes_decryption_cipher(block_mode, key, iv)
        end

        private

        def validate_key_wrap(key_wrap_schema)
          case key_wrap_schema
          when :kms_context then 'kms+context'
          else
            raise ArgumentError, "Unsupported key_wrap_schema: #{key_wrap_schema}"
          end
        end

        def validate_cek(content_encryption_schema)
          case content_encryption_schema
          when :aes_gcm_no_padding
            "AES/GCM/NoPadding"
          else
            raise ArgumentError, "Unsupported content_encryption_schema: #{content_encryption_schema}"
          end
        end

        def validate_kms_key(kms_key_id)
          if kms_key_id.nil? || kms_key_id.length.zero?
            raise ArgumentError, 'KMS CMK ID was not specified. ' \
              'Please specify a CMK ID, ' \
              'or set kms_key_id: :kms_allow_decrypt_with_any_cmk to use ' \
              'any valid CMK from the object.'
          end

          if kms_key_id.is_a?(Symbol) && kms_key_id != :kms_allow_decrypt_with_any_cmk
            raise ArgumentError, 'kms_key_id must be a valid KMS CMK or be ' \
              'set to :kms_allow_decrypt_with_any_cmk'
          end
          kms_key_id
        end

        def build_encryption_context(cek_alg, options = {})
          kms_context = (options[:kms_encryption_context] || {})
            .each_with_object({}) { |(k, v), h| h[k.to_s] = v }
          if kms_context.include? 'aws:x-amz-cek-alg'
            raise ArgumentError, 'Conflict in reserved KMS Encryption Context ' \
              'key aws:x-amz-cek-alg. This value is reserved for the S3 ' \
              'Encryption Client and cannot be set by the user.'
          end
          {
            'aws:x-amz-cek-alg' => cek_alg
          }.merge(kms_context)
        end

        def encode64(str)
          Base64.encode64(str).split("\n") * ""
        end

        def decode64(str)
          Base64.decode64(str)
        end

        def validate_key_for_encryption
          if @kms_key_id == :kms_allow_decrypt_with_any_cmk
            raise ArgumentError, 'Unable to encrypt/write objects with '\
              'kms_key_id = :kms_allow_decrypt_with_any_cmk.  Provide ' \
              'a valid kms_key_id on client construction.'
          end
        end
      end
    end
  end
end


text:
[![CircleCI](https://img.shields.io/circleci/project/github/ORGANIZATION/<%= kebabCaseName %>/master.svg)](https://circleci.com/gh/ORGANIZATION/<%= kebabCaseName %>)
[![npm](https://img.shields.io/npm/v/<%= kebabCaseName %>.svg)](https://www.npmjs.com/package/<%= kebabCaseName %>)

## Usage

### Installation

## Examples

## API

## Upgrade Considerations / Changelog

See [Releases](https://github.com/palantir/react-mosaic/releases)

## License
[MIT](./LICENSE)


text:
#ifndef QWT_ROUND_SCALE_DRAW_H
#define QWT_ROUND_SCALE_DRAW_H

#include "qwt_global.h"
#include "qwt_abstract_scale_draw.h"

#include <qpoint.h>

/*!
  \brief A class for drawing round scales

  QwtRoundScaleDraw can be used to draw round scales.
  The circle segment can be adjusted by setAngleRange().
  The geometry of the scale can be specified with
  moveCenter() and setRadius().

  After a scale division has been specified as a QwtScaleDiv object
  using QwtAbstractScaleDraw::setScaleDiv(const QwtScaleDiv &s),
  the scale can be drawn with the QwtAbstractScaleDraw::draw() member.
*/

class QWT_EXPORT QwtRoundScaleDraw: public QwtAbstractScaleDraw
{
public:
    QwtRoundScaleDraw();
    virtual ~QwtRoundScaleDraw();

    void setRadius( double radius );
    double radius() const;

    void moveCenter( double x, double y );
    void moveCenter( const QPointF & );
    QPointF center() const;

    void setAngleRange( double angle1, double angle2 );

    void setSplitValue( double value );

    virtual double extent( const QFont & ) const QWT_OVERRIDE;

protected:
    virtual void drawTick( QPainter *,
        double value, double len ) const QWT_OVERRIDE;

    virtual void drawBackbone(
        QPainter * ) const QWT_OVERRIDE;

    virtual void drawLabel(
        QPainter *, double value ) const QWT_OVERRIDE;

private:
    class PrivateData;
    PrivateData *d_data;
};

//! Move the center of the scale draw, leaving the radius unchanged
inline void QwtRoundScaleDraw::moveCenter( double x, double y )
{
    moveCenter( QPointF( x, y ) );
}

#endif


text:
<?php

namespace Electro\Service;

use Electro\Repository\NoteRepository;
use Electro\Query\GetActiveNotesQuery;
use Electro\Result\GetActiveNotesResult;

class GetActiveNotesService {

    const PER_PAGE = 5;

    protected $repo;

    public function __construct(NoteRepository $repo) {
        $this->repo = $repo;
    }

    public function handle(GetActiveNotesQuery $query) {

        $limit = self::PER_PAGE;
        $offset = $query->page() * self::PER_PAGE;

        $notes = $this->repo->retrieveActive($limit, $offset);
        $pages = (int)ceil($this->repo->countActive()/self::PER_PAGE) -1;

        return new GetActiveNotesResult($notes, $pages);
    }

}


text:
package metrics

import (
	"errors"
	"fmt"
	"sort"
	"strconv"
	"strings"
	"sync"
)

// Map implements a key-value store where keys are of type string and values
// are of type NumValue.
// It satisfies the Value interface.
type Map struct {
	MapName string // Map key name
	mu      sync.RWMutex
	m       map[string]NumValue
	keys    []string

	// total is only used to figure out if counter is moving up or down (reset).
	total NumValue

	// We use this to initialize new keys
	defaultKeyValue NumValue
}

// NewMap returns a new Map
func NewMap(mapName string, defaultValue NumValue) *Map {
	return &Map{
		MapName:         mapName,
		defaultKeyValue: defaultValue,
		m:               make(map[string]NumValue),
		total:           defaultValue.Clone().(NumValue),
	}
}

// GetKey returns the given key's value.
func (m *Map) GetKey(key string) NumValue {
	m.mu.RLock()
	defer m.mu.RUnlock()
	return m.m[key]
}

// Clone creates a clone of the Map. Clone makes sure that underlying data
// storage is properly cloned.
func (m *Map) Clone() Value {
	m.mu.RLock()
	defer m.mu.RUnlock()
	newMap := &Map{
		MapName:         m.MapName,
		defaultKeyValue: m.defaultKeyValue.Clone().(NumValue),
		m:               make(map[string]NumValue),
		total:           m.total.Clone().(NumValue),
	}
	newMap.keys = make([]string, len(m.keys))
	for i, k := range m.keys {
		newMap.m[k] = m.m[k].Clone().(NumValue)
		newMap.keys[i] = m.keys[i]
	}
	return newMap
}

// Keys returns the list of keys
func (m *Map) Keys() []string {
	m.mu.RLock()
	defer m.mu.RUnlock()
	return append([]string{}, m.keys...)
}

// newKey adds a new key to the map, with its value set to defaultKeyValue
// This is an unsafe function, callers should take care of protecting the map
// from race conditions.
func (m *Map) newKey(key string) {
	m.keys = append(m.keys, key)
	sort.Strings(m.keys)
	m.m[key] = m.defaultKeyValue.Clone().(NumValue)
	m.total.IncBy(m.defaultKeyValue)
}

// IncKey increments the given key's value by one.
func (m *Map) IncKey(key string) {
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.m[key] == nil {
		m.newKey(key)
	}
	m.m[key].Inc()
	m.total.Inc()
}

// IncKeyBy increments the given key's value by NumValue.
func (m *Map) IncKeyBy(key string, delta NumValue) {
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.m[key] == nil {
		m.newKey(key)
	}
	m.m[key].IncBy(delta)
	m.total.IncBy(delta)
}

// Add adds a value (type Value) to the receiver Map. A non-Map value returns
// an error. This is part of the Value interface.
func (m *Map) Add(val Value) error {
	_, err := m.addOrSubtract(val, false)
	return err
}

// SubtractCounter subtracts the provided "lastVal", assuming that value
// represents a counter, i.e. if "value" is less than "lastVal", we assume that
// counter has been reset and don't subtract.
func (m *Map) SubtractCounter(lastVal Value) (bool, error) {
	return m.addOrSubtract(lastVal, true)
}

func (m *Map) addOrSubtract(val Value, subtract bool) (bool, error) {
	delta, ok := val.(*Map)
	if !ok {
		return false, errors.New("incompatible value to add or subtract")
	}

	m.mu.Lock()
	defer m.mu.Unlock()
	delta.mu.RLock()
	defer delta.mu.RUnlock()

	if subtract && (m.total.Float64() < delta.total.Float64()) {
		return true, nil
	}

	var sortRequired bool
	for k, v := range delta.m {
		if subtract {
			// If a key is there in delta (lastVal) but not in the current val,
			// assume metric has been reset.
			if m.m[k] == nil {
				return true, nil
			}
			m.m[k].SubtractCounter(v)
		} else {
			if m.m[k] == nil {
				sortRequired = true
				m.keys = append(m.keys, k)
				m.m[k] = v
				continue
			}
			m.m[k].Add(v)
		}
	}
	if sortRequired {
		sort.Strings(m.keys)
	}
	return false, nil
}

// AddInt64 generates a panic for the Map type. This is added only to satisfy
// the Value interface.
func (m *Map) AddInt64(i int64) {
	panic("Map type doesn't implement AddInt64()")
}

// AddFloat64 generates a panic for the Map type. This is added only to
// satisfy the Value interface.
func (m *Map) AddFloat64(f float64) {
	panic("Map type doesn't implement AddFloat64()")
}

// String returns the string representation of the receiver Map.
// This is part of the Value interface.
// map:key,k1:v1,k2:v2
func (m *Map) String() string {
	m.mu.RLock()
	defer m.mu.RUnlock()

	var b strings.Builder
	b.Grow(64)

	b.WriteString("map:")
	b.WriteString(m.MapName)

	for _, k := range m.keys {
		b.WriteByte(',')
		b.WriteString(k)
		b.WriteByte(':')
		b.WriteString(m.m[k].String())
	}
	return b.String()
}

// ParseMapFromString parses a map value string into a map object.
// Note that the values are always parsed as floats, so even a map with integer
// values will become a float map.
// For example:
// "map:code,200:10123,404:21" will be parsed as:
// "map:code 200:10123.000 404:21.000".
func ParseMapFromString(mapValue string) (*Map, error) {
	tokens := strings.Split(mapValue, ",")
	if len(tokens) < 1 {
		return nil, errors.New("bad map value")
	}

	kv := strings.Split(tokens[0], ":")
	if kv[0] != "map" {
		return nil, errors.New("map value doesn't start with map:<key>")
	}

	m := NewMap(kv[1], NewFloat(0))

	for _, tok := range tokens[1:] {
		kv := strings.Split(tok, ":")
		if len(kv) != 2 {
			return nil, errors.New("bad map value token: " + tok)
		}
		f, err := strconv.ParseFloat(kv[1], 64)
		if err != nil {
			return nil, fmt.Errorf("could not convert map key value %s to a float: %v", kv[1], err)
		}
		m.IncKeyBy(kv[0], NewFloat(f))
	}

	return m, nil
}


text:
.class public interface abstract Lorg/simpleframework/xml/stream/InputNode;
.super Ljava/lang/Object;
.source "InputNode.java"

# interfaces
.implements Lorg/simpleframework/xml/stream/Node;

# virtual methods
.method public abstract getAttribute(Ljava/lang/String;)Lorg/simpleframework/xml/stream/InputNode;
.end method

.method public abstract getAttributes()Lorg/simpleframework/xml/stream/NodeMap;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Lorg/simpleframework/xml/stream/NodeMap",
            "<",
            "Lorg/simpleframework/xml/stream/InputNode;",
            ">;"
        }
    .end annotation
.end method

.method public abstract getNext()Lorg/simpleframework/xml/stream/InputNode;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/Exception;
        }
    .end annotation
.end method

.method public abstract getNext(Ljava/lang/String;)Lorg/simpleframework/xml/stream/InputNode;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/Exception;
        }
    .end annotation
.end method

.method public abstract getParent()Lorg/simpleframework/xml/stream/InputNode;
.end method

.method public abstract getPosition()Lorg/simpleframework/xml/stream/Position;
.end method

.method public abstract getPrefix()Ljava/lang/String;
.end method

.method public abstract getReference()Ljava/lang/String;
.end method

.method public abstract getSource()Ljava/lang/Object;
.end method

.method public abstract isElement()Z
.end method

.method public abstract isEmpty()Z
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/Exception;
        }
    .end annotation
.end method

.method public abstract isRoot()Z
.end method

.method public abstract skip()V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/Exception;
        }
    .end annotation
.end method


text:
Python program to access ping functionality present in Linux Based Systems using subprocess module and popen().

The output is used to extract values and show Netowrk parameters like Latency, Packet Loss
and Jitter.


text:
import React from "react"

export default class Greeting extends React.Component {

  constructor(props) {
    super(props)
  }

  render() {
    return (
      <h1 className="greeting">
        Rendered: {this.props.time}!
      </h1>
    )
  }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Foundatio.Parsers.LuceneQueries.Extensions;

namespace Foundatio.Parsers.LuceneQueries.Nodes {
    public class MissingNode : QueryNodeBase, IFieldQueryNode {
        public bool? IsNegated { get; set; }
        public string Prefix { get; set; }
        public string Field { get; set; }
        public string UnescapedField => Field?.Unescape();

        public MissingNode CopyTo(MissingNode target) {
            if (IsNegated.HasValue)
                target.IsNegated = IsNegated;

            if (Prefix != null)
                target.Prefix = Prefix;

            if (Field != null)
                target.Field = Field;

            foreach (var kvp in Data)
                target.Data.Add(kvp.Key, kvp.Value);

            return target;
        }

        public override IQueryNode Clone() {
            var clone = new MissingNode();
            CopyTo(clone);
            return clone;
        }

        public override string ToString() {
            var builder = new StringBuilder();

            if (IsNegated.HasValue && IsNegated.Value)
                builder.Append("NOT ");

            builder.Append(Prefix);
            builder.Append("_missing_");
            builder.Append(":");
            builder.Append(this.Field);

            return builder.ToString();
        }

        public override IEnumerable<IQueryNode> Children => EmptyNodeList;
    }
}


text:
namespace test_shell {

// Suppresses all error dialogs when present.
const wchar_t kNoErrorDialogs[]                = L"noerrdialogs";

// Causes the test_shell to run using stdin and stdout for URLs and output,
// respectively, and interferes with interactive use of the UI.
const wchar_t kLayoutTests[] = L"layout-tests";
const wchar_t kCrashDumps[] = L"crash-dumps";  // Enable crash dumps

// Command line flags that control the tests when layout-tests is specified.
const wchar_t kNoTree[] = L"notree";  // Don't dump the render tree.
const wchar_t kDumpPixels[] = L"pixel-tests";  // Enable pixel tests.
// Optional command line switch that specifies timeout time for page load when
// running file tests in layout test mode, in ms.
const wchar_t kTestShellTimeOut[] = L"time-out-ms";

const wchar_t kStartupDialog[] = L"testshell-startup-dialog";

// Enable the Windows dialogs for GP faults in the test shell. This allows makes
// it possible to attach a crashed test shell to a debugger.
const wchar_t kGPFaultErrorBox[] = L"gp-fault-error-box";

// JavaScript flags passed to engine.
const wchar_t kJavaScriptFlags[] = L"js-flags";

// Run the http cache in record mode.
const wchar_t kRecordMode[] = L"record-mode";

// Run the http cache in playback mode.
const wchar_t kPlaybackMode[] = L"playback-mode";

// Don't record/playback events when using record & playback.
const wchar_t kNoEvents[] = L"no-events";

// Dump stats table on exit.
const wchar_t kDumpStatsTable[] = L"stats";

// Use a specified cache directory.
const wchar_t kCacheDir[] = L"cache-dir";

// Temparary option for new ftp implemetation.
const wchar_t kNewFtp[] = L"new-ftp";

// When being run through a memory profiler, trigger memory in use dumps at
// startup and just prior to shutdown.
const wchar_t kDebugMemoryInUse[] = L"debug-memory-in-use";

// Enable cookies on the file:// scheme.  --layout-tests also enables this.
const wchar_t kEnableFileCookies[] = L"enable-file-cookies";

// Enable tracing events (see base/trace_event.h)
const wchar_t kEnableTracing[] = L"enable-tracing";

// Allow scripts to close windows in all cases.
const wchar_t kAllowScriptsToCloseWindows[] = L"allow-scripts-to-close-windows";

// Test the system dependencies (themes, fonts, ...). When this flag is
// specified, the test shell will exit immediately with either 0 (success) or
// 1 (failure). Combining with other flags has no effect.
extern const wchar_t kCheckLayoutTestSystemDeps[] =
    L"check-layout-test-sys-deps";

// If set, we are running under GDB so allow a certain class of errors
// to happen even if in layout test mode.
extern const wchar_t kGDB[] = L"gdb";

// Make functions of the Profiler class available in javascript
extern const wchar_t kProfiler[] = L"profiler";

}  // namespace test_shell


text:
Triniti Schemas

../
collect-article-stats/
remove-article-slotting/
sync-facebook-instant-article/


text:
"""Support for SimpliSafe alarm systems."""
import asyncio
import logging
from datetime import timedelta

from simplipy import API
from simplipy.errors import InvalidCredentialsError, SimplipyError
import voluptuous as vol

from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import (
    CONF_CODE,
    CONF_PASSWORD,
    CONF_SCAN_INTERVAL,
    CONF_TOKEN,
    CONF_USERNAME,
)
from homeassistant.core import callback
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import (
    aiohttp_client,
    config_validation as cv,
    device_registry as dr,
)
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.service import verify_domain_control

from .config_flow import configured_instances
from .const import DATA_CLIENT, DEFAULT_SCAN_INTERVAL, DOMAIN, TOPIC_UPDATE

_LOGGER = logging.getLogger(__name__)

ATTR_PIN_LABEL = "label"
ATTR_PIN_LABEL_OR_VALUE = "label_or_pin"
ATTR_PIN_VALUE = "pin"
ATTR_SYSTEM_ID = "system_id"

CONF_ACCOUNTS = "accounts"

DATA_LISTENER = "listener"

SERVICE_REMOVE_PIN_SCHEMA = vol.Schema(
    {
        vol.Required(ATTR_SYSTEM_ID): cv.string,
        vol.Required(ATTR_PIN_LABEL_OR_VALUE): cv.string,
    }
)

SERVICE_SET_PIN_SCHEMA = vol.Schema(
    {
        vol.Required(ATTR_SYSTEM_ID): cv.string,
        vol.Required(ATTR_PIN_LABEL): cv.string,
        vol.Required(ATTR_PIN_VALUE): cv.string,
    }
)

ACCOUNT_CONFIG_SCHEMA = vol.Schema(
    {
        vol.Required(CONF_USERNAME): cv.string,
        vol.Required(CONF_PASSWORD): cv.string,
        vol.Optional(CONF_CODE): cv.string,
        vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): cv.time_period,
    }
)

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: vol.Schema(
            {
                vol.Optional(CONF_ACCOUNTS): vol.All(
                    cv.ensure_list, [ACCOUNT_CONFIG_SCHEMA]
                )
            }
        )
    },
    extra=vol.ALLOW_EXTRA,
)

@callback
def _async_save_refresh_token(hass, config_entry, token):
    hass.config_entries.async_update_entry(
        config_entry, data={**config_entry.data, CONF_TOKEN: token}
    )

async def async_register_base_station(hass, system, config_entry_id):
    """Register a new bridge."""
    device_registry = await dr.async_get_registry(hass)
    device_registry.async_get_or_create(
        config_entry_id=config_entry_id,
        identifiers={(DOMAIN, system.serial)},
        manufacturer="SimpliSafe",
        model=system.version,
        name=system.address,
    )

async def async_setup(hass, config):
    """Set up the SimpliSafe component."""
    hass.data[DOMAIN] = {}
    hass.data[DOMAIN][DATA_CLIENT] = {}
    hass.data[DOMAIN][DATA_LISTENER] = {}

    if DOMAIN not in config:
        return True

    conf = config[DOMAIN]

    for account in conf[CONF_ACCOUNTS]:
        if account[CONF_USERNAME] in configured_instances(hass):
            continue

        hass.async_create_task(
            hass.config_entries.flow.async_init(
                DOMAIN,
                context={"source": SOURCE_IMPORT},
                data={
                    CONF_USERNAME: account[CONF_USERNAME],
                    CONF_PASSWORD: account[CONF_PASSWORD],
                    CONF_CODE: account.get(CONF_CODE),
                    CONF_SCAN_INTERVAL: account[CONF_SCAN_INTERVAL],
                },
            )
        )

    return True

async def async_setup_entry(hass, config_entry):
    """Set up SimpliSafe as config entry."""
    _verify_domain_control = verify_domain_control(hass, DOMAIN)

    websession = aiohttp_client.async_get_clientsession(hass)

    try:
        api = await API.login_via_token(config_entry.data[CONF_TOKEN], websession)
    except InvalidCredentialsError:
        _LOGGER.error("Invalid credentials provided")
        return False
    except SimplipyError as err:
        _LOGGER.error("Config entry failed: %s", err)
        raise ConfigEntryNotReady

    _async_save_refresh_token(hass, config_entry, api.refresh_token)

    systems = await api.get_systems()
    simplisafe = SimpliSafe(hass, config_entry, systems)
    await simplisafe.async_update()
    hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id] = simplisafe

    hass.async_create_task(
        hass.config_entries.async_forward_entry_setup(
            config_entry, "alarm_control_panel"
        )
    )

    async def refresh(event_time):
        """Refresh data from the SimpliSafe account."""
        await simplisafe.async_update()
        _LOGGER.debug("Updated data for all SimpliSafe systems")
        async_dispatcher_send(hass, TOPIC_UPDATE)

    hass.data[DOMAIN][DATA_LISTENER][config_entry.entry_id] = async_track_time_interval(
        hass, refresh, timedelta(seconds=config_entry.data[CONF_SCAN_INTERVAL])
    )

    # Register the base station for each system:
    for system in systems.values():
        hass.async_create_task(
            async_register_base_station(hass, system, config_entry.entry_id)
        )

    @_verify_domain_control
    async def remove_pin(call):
        """Remove a PIN."""
        system = systems[int(call.data[ATTR_SYSTEM_ID])]
        await system.remove_pin(call.data[ATTR_PIN_LABEL_OR_VALUE])

    @_verify_domain_control
    async def set_pin(call):
        """Set a PIN."""
        system = systems[int(call.data[ATTR_SYSTEM_ID])]
        await system.set_pin(call.data[ATTR_PIN_LABEL], call.data[ATTR_PIN_VALUE])

    for service, method, schema in [
        ("remove_pin", remove_pin, SERVICE_REMOVE_PIN_SCHEMA),
        ("set_pin", set_pin, SERVICE_SET_PIN_SCHEMA),
    ]:
        hass.services.async_register(DOMAIN, service, method, schema=schema)

    return True

async def async_unload_entry(hass, entry):
    """Unload a SimpliSafe config entry."""
    await hass.config_entries.async_forward_entry_unload(entry, "alarm_control_panel")

    hass.data[DOMAIN][DATA_CLIENT].pop(entry.entry_id)
    remove_listener = hass.data[DOMAIN][DATA_LISTENER].pop(entry.entry_id)
    remove_listener()

    return True

class SimpliSafe:
    """Define a SimpliSafe API object."""

    def __init__(self, hass, config_entry, systems):
        """Initialize."""
        self._config_entry = config_entry
        self._hass = hass
        self.last_event_data = {}
        self.systems = systems

    async def _update_system(self, system):
        """Update a system."""
        try:
            await system.update()
            latest_event = await system.get_latest_event()
        except SimplipyError as err:
            _LOGGER.error(
                'SimpliSafe error while updating "%s": %s', system.address, err
            )
            return
        except Exception as err:  # pylint: disable=broad-except
            _LOGGER.error('Unknown error while updating "%s": %s', system.address, err)
            return

        self.last_event_data[system.system_id] = latest_event

        if system.api.refresh_token_dirty:
            _async_save_refresh_token(
                self._hass, self._config_entry, system.api.refresh_token
            )

    async def async_update(self):
        """Get updated data from SimpliSafe."""
        tasks = [self._update_system(system) for system in self.systems.values()]

        await asyncio.gather(*tasks)


text:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@class QJADocument;

extern NSString *const JSONAPIClientErrorDomain;

typedef enum JSONAPIErrorCodes{

    kMimetypeError = 415,
    kMalformedContentError = 400

}JSONAPIErrorCodes;

/**
 Objective-C client for basic http requests using the jsonapi specification. For any further information please visit http://jsonapi.org
 */
@interface QJAClient : NSObject <NSURLSessionDataDelegate, NSURLSessionTaskDelegate>

/**
 @brief the endpoint url string
 @discussion use this property to set the url of your endpoint as a string.
 */
@property (strong, nonatomic) NSString *endpoint;

/**
 @brief the NSURLSessionConfiguration used by the client, [NSURLSessionConfiguration defaultSessionConfiguration] is used by default.
 @discussion inject your custom session configuration if you prefer to use a different one.
 */
@property (strong, nonatomic) NSURLSessionConfiguration *sessionConfiguration;

/**
  the NSURLCredential for auth challenges
 */
@property (strong, nonatomic) NSURLCredential *sessionCredential;

/**
 @brief use this method to append any additional HTTP headers in addition to the standard jsonapi HTTP headers.
 @param additionalHeaders a dictionary containing your additional headers.
 */
- (void) appendAdditionalHTTPHeaders: (NSDictionary *) additionalHeaders;

/**
 @brief use this method to download a JsonApi Document wrapped in a QJADocument
 @param path the path of the resource on the server
 @param completionHandler the completion handler to be invoked upon completion, "jsonApiDocument" is the returned document, "statusCode" is the returned status code, "error" is the returned error (if any).
 */
- (void) getJSONAPIDocumentWithPath: (NSString *) path completionHandler: (void(^)(QJADocument *jsonApiDocument, NSInteger statusCode, NSError *error)) completionHandler;

/**
 @brief use this method to GET a JsonApi Document wrapped in a QJADocument, by including its linked resources
 @param path the path of the resource on the server
 @param includedResourceTypes an array containing the type of the resources to include in the Jsonapi Document
 @param completionHandler the completion handler to be invoked upon completion, "jsonApiDocument" is the returned document, "statusCode" is the returned status code, "error" is the returned error (if any).
 */
- (void) getJSONAPIDocumentWithPath: (NSString *) path includedResourceTypes: (NSArray *) includedResourceTypes completionHandler: (void(^)(QJADocument *jsonApiDocument, NSInteger statusCode, NSError *error)) completionHandler;

/**
 @brief use this method to POST a JsonApi Document wrapped in a QJADocument
 @param documentToPost the Jsonapi Document to be POSTed
 @param path the path of the document on the server
 @param completionHandler the completion handler to be invoked upon completion, "jsonApiDocument" is the returned document, "statusCode" is the returned status code, "error" is the returned error (if any).
 */
- (void) postJSONAPIDocument: (QJADocument *) documentToPost withPath: (NSString *) path completionHandler: (void(^)(QJADocument *jsonApiDocument, NSInteger statusCode, NSError *error)) completionHandler;

/**
 @brief use this method to POST a JsonApi Document wrapped in a QJADocument
 @param documentToPost the Jsonapi Document to be POSTed
 @param path the path of the document on the server
 @param includedResourceTypes an array specifying the type of the resources included in the Jsonapi Document
 @param completionHandler the completion handler to be invoked upon completion, "jsonApiDocument" is the returned document, "statusCode" is the returned status code, "error" is the returned error (if any).
 */
- (void) postJSONAPIDocument: (QJADocument *) documentToPost withPath: (NSString *) path includedResources: (NSArray *) includedResourceTypes completionHandler: (void(^)(QJADocument *jsonApiDocument, NSInteger statusCode, NSError *error)) completionHandler;

/**
 @brief use this method to DELETE a JsonApi Document wrapped in a QJADocument
 @param documentToPost the Jsonapi Document to be POSTed
 @param path the path of the document on the server
 @param completionHandler the completion handler to be invoked upon completion, "jsonApiDocument" is the returned document, "statusCode" is the returned status code, "error" is the returned error (if any).
 */
- (void) deleteJSONAPIResourceWithPath: (NSString *) path completionHandler: (void(^)(QJADocument *jsonApiDocument, NSInteger statusCode, NSError *error)) completionHandler;

/**
 @brief use this method to append a query parameters to your HTTP call
 @param queryParameters a dictionary containing your query parameters
 */
- (void) appendQueryParameters: (NSDictionary <NSString *, NSString *> *) queryParameters;

/**
 @brief use this method to append a BODY to your HTTP call
 @param BODY an NSString containing your HTTP body
 */
- (void) appendRequestBody: (NSString *) body;

/**
 @brief use this method to extend (sperimental) the JsonApi allowed content types and accepts
 @param contentTypeExtensions the content type extensions as NSStrings Array
 @param acceptExtensions the accept extensions as NSStrings Array
 @discussion this feature is sperimental, it's not offically accepted by the JsonApi specification
 */
- (void) setContentTypeExtension: (NSArray <NSString *> *) contentTypeExtensions acceptExtensions: (NSArray <NSString *> *) acceptExtensions;

/**
 @brief use this method to perform a generic HTTP operation
 @param httpMethod the HTTP method to use
 @param path the path of the document on the server
 @param completionHandler the completion handler to be invoked upon completion, "retrievedData" is the returned raw data, "statusCode" is the returned status code, "error" is the returned error (if any).
 */
- (void) genericRequestWithHTTPMethod: (NSString *) httpMethod resourcePath: (NSString *) path completionHandler: (void(^)(NSData *retrievedData, NSInteger statusCode, NSError *error)) completionHandler;

@end


text:
  Saulgé est
       un village
       géographiquement positionné dans le département de Vienne en Poitou-Charentes. Elle comptait 967 habitants en 2008.

Le nombre d'habitations, à Saulgé, se décomposait en 2011 en onze appartements et 569 maisons soit
 un marché plutôt équilibré.

À coté de Saulgé sont situées les communes de
Lussac-les-Châteaux localisée à 11 km, 2 381 habitants,
Sillars localisée à 9 km, 593 habitants,
Journet à 11 km, 378 habitants,
Lathus-Saint-Rémy localisée à 8 km, 1 216 habitants,
Saint-Léomer située à 11 km, 179 habitants,
Moulismes située à 7 km, 406 habitants,
 entre autres. De plus, Saulgé est située à seulement 27 km de Chauvigny.

La commune compte quelques  aménagements, elle dispose, entre autres, de un terrain de tennis, un terrain de sport et un équipement de roller/skate.

Si vous pensez venir habiter à Saulgé, vous pourrez facilement trouver une maison à vendre.

À Saulgé, la valeur moyenne à la vente d'un appartement s'évalue à zero € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 728 € du m². À la location la valeur moyenne se situe à 4,96 € du m² par mois.


text:
require 'spec_helper'
require 'fileutils'

module EySecrets
  describe Git do
    describe '.repository' do
      include FileUtils

      describe '.remotes' do
        it 'returns repository uris' do
          in_sandbox do
            create_bare_repo('origin_repo', ['file'])
            clone_repo('origin_repo', 'repo')

            remotes = Git.repository('repo').remotes

            expect(remotes).to eq([File.expand_path('origin_repo')])
          end
        end
      end

      describe '.files' do
        it 'returns paths relative to CWD' do
          in_sandbox do
            create_bare_repo('origin_repo', ['file', 'some/file'])
            clone_repo('origin_repo', 'repo')

            files = Git.repository('repo').files

            expect(files.sort).to eq(['repo/file', 'repo/some', 'repo/some/file'])
          end
        end

        it 'removes leading dot' do
          in_sandbox do
            create_bare_repo('origin_repo', ['file'])
            clone_repo('origin_repo', 'repo')

            files = Dir.chdir('repo') do
              Git.repository('.').files
            end

            expect(files).to eq(['file'])
          end
        end
      end

      describe '.ready_for_update?' do
        it 'is true after clone' do
          in_sandbox do
            create_bare_repo('origin_repo', ['file'])
            clone_repo('origin_repo', 'repo')

            repository = Git.repository('repo')

            expect(repository).to be_ready_for_update
          end
        end

        it 'is false if repo has untracked files' do
          in_sandbox do
            create_bare_repo('origin_repo', ['file'])
            clone_repo('origin_repo', 'repo')
            `touch repo/other`

            repository = Git.repository('repo')

            expect(repository).not_to be_ready_for_update
          end
        end

        it 'is false if repo has modified files' do
          in_sandbox do
            create_bare_repo('origin_repo', ['file'])
            clone_repo('origin_repo', 'repo')
            `echo "change" > repo/file`

            repository = Git.repository('repo')

            expect(repository).not_to be_ready_for_update
          end
        end

        it 'is false if repo has unpushed commits' do
          in_sandbox do
            create_bare_repo('origin_repo', ['file'])
            clone_repo('origin_repo', 'repo')
            `(cd repo; echo "change" > file; git add .; git commit -m "change")`

            repository = Git.repository('repo')

            expect(repository).not_to be_ready_for_update
          end
        end

        it 'is true if all commits have been pushed' do
          in_sandbox do
            create_bare_repo('origin_repo', ['file'])
            clone_repo('origin_repo', 'repo')
            `(cd repo; echo "change" > file; git add .; git commit -m "change"; git push origin master 2> /dev/null)`

            repository = Git.repository('repo')

            expect(repository).to be_ready_for_update
          end
        end
      end

      def clone_repo(from, to)
        `git clone #{from} #{to} 2> /dev/null`
        Dir.chdir(to) { configure_git_user }
      end

      def create_bare_repo(name, files = {})
        mkdir('original_repo')
        Dir.chdir('original_repo') do
          `git init`
          configure_git_user
          files.each do |file|
            mkdir_p(File.dirname(file))
            touch(file)
          end
          `git add .; git commit -m "initial commit"`
        end
        `git clone --bare original_repo #{name} 2> /dev/null`
      end

      def configure_git_user
        `git config user.email spec@example.com`
        `git config user.name "EySecrets Spec"`
      end

      def in_sandbox(&block)
        rm_rf(sandbox_path)
        mkdir_p(sandbox_path)
        Dir.chdir(sandbox_path, &block)
      end

      def sandbox_path
        File.join(PROJECT_ROOT, 'spec', 'tmp')
      end
    end
  end
end


text:
class RayTracer :
	public Renderer
{
public:
	RayTracer(const Scene* scene, const Camera* camera, Image* image, int depth, int shadowSamples) :
		Renderer(scene, camera, image), m_numShadowSamples(shadowSamples) { m_rng = rng_uniform(); m_depth = depth; };
	~RayTracer();

private:
	int m_numShadowSamples;
	bool trace(const Ray& ray, Color3& l_o, int depth) const override;

	bool RayTracer::calculateIndirectLight(Ray const& ray, const SurfaceElement& surfel, const float fresnelReflective, const float cosI, const float sinT2, const float n, Color3& L_o, int depth) const;
};


text:
import { CSSProperties, ElementType, ReactNode, forwardRef, useState } from 'react';

import { generateUID } from '../../helpers';
import { useCombinedRefs } from '../../hooks';
import { usePopperAnchor } from '../popper';
import Dropdown from './Dropdown';
import DropdownButton, { DropdownButtonProps } from './DropdownButton';

interface OwnProps {
    hasCaret?: boolean;
    content?: ReactNode;
    children?: ReactNode;
    originalPlacement?: string;
    autoClose?: boolean;
    dropdownClassName?: string;
    dropdownStyle?: CSSProperties;
    disableDefaultArrowNavigation?: boolean;
    onClick?: () => void;
}

export type Props<T extends ElementType> = OwnProps & DropdownButtonProps<T>;

const SimpleDropdownBase = <E extends ElementType>(
    {
        content,
        children,
        originalPlacement,
        autoClose,
        hasCaret = true,
        dropdownClassName,
        dropdownStyle,
        disableDefaultArrowNavigation = false,
        onClick,
        ...rest
    }: Props<E>,
    ref: typeof rest.ref
) => {
    const [uid] = useState(generateUID('dropdown'));

    const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>();

    const handleClick = !!onClick
        ? () => {
              onClick();
              toggle();
          }
        : toggle;

    return (
        <>
            <DropdownButton
                {...rest}
                ref={useCombinedRefs(ref, anchorRef)}
                isOpen={isOpen}
                onClick={handleClick}
                hasCaret={hasCaret}
            >
                {content}
            </DropdownButton>
            <Dropdown
                id={uid}
                originalPlacement={originalPlacement}
                autoClose={autoClose}
                isOpen={isOpen}
                anchorRef={anchorRef}
                onClose={close}
                className={dropdownClassName}
                style={dropdownStyle}
                disableDefaultArrowNavigation={disableDefaultArrowNavigation}
            >
                {children}
            </Dropdown>
        </>
    );
};

const SimpleDropdown = forwardRef(SimpleDropdownBase);

export default SimpleDropdown;