text:
#include <itkImageRegistrationMethod.h>
#include <xip/inventor/itk/SoItkUtils.h>
#include "SoItkImageRegistrationMethod.h"

SO_ENGINE_SOURCE( SoItkImageRegistrationMethod );

SoItkImageRegistrationMethod::SoItkImageRegistrationMethod()
{
	SO_ENGINE_CONSTRUCTOR( SoItkImageRegistrationMethod );

	SO_ENGINE_ADD_INPUT( InitialTransformParameters, (0) );
	InitialTransformParameters.setNum(0);
	SO_ENGINE_ADD_INPUT( Transform, (0) );
	SO_ENGINE_ADD_INPUT( FixedImage, (0) );
	SO_ENGINE_ADD_INPUT( MovingImage, (0) );
	SO_ENGINE_ADD_INPUT( Interpolator, (0) );
	SO_ENGINE_ADD_INPUT( Metric, (0) );
	SO_ENGINE_ADD_INPUT( FixedImageRegion, (0) );
	FixedImageRegion.setNum(0);
	SO_ENGINE_ADD_INPUT( Optimizer, (0) );

	SO_ENGINE_ADD_INPUT( Start, () );

	SO_ENGINE_ADD_OUTPUT( OutputOptimizer, SoItkSFDataOptimizer );
	SO_ENGINE_ADD_OUTPUT( LastTransformParameters, SoMFFloat );

	mStartRegistration = false;
	mOptimizer = 0;
}

SoItkImageRegistrationMethod::~SoItkImageRegistrationMethod()
{
	if( mOptimizer )
	{
		mOptimizer->unref();
		mOptimizer = 0;
	}
}

void
SoItkImageRegistrationMethod::initClass()
{
	SO_ENGINE_INIT_CLASS( SoItkImageRegistrationMethod, SoItkProcessObject, "SoItkProcessObject" );
}

bool
SoItkImageRegistrationMethod::checkInput()
{
	switch( FixedImage.getValue()->getType() )
	{
		case SoItkDataImage::FLOAT:
		{
			switch( FixedImage.getValue()->getNumDimension() )
			{
				case 2:
				{
					return true;
				}
				break ;
				case 3:
				{
					return true;
				}
				break ;
			}
		}
		break ;
		case SoItkDataImage::UNSIGNED_SHORT:
		{
			switch( MovingImage.getValue()->getNumDimension() )
			{
				case 2:
				{
					return true;
				}
				break ;
				case 3:
				{
					return true;
				}
				break ;
			}
		}
		break ;
	}

	return false;
}

void
SoItkImageRegistrationMethod::evaluate()
{
	if( !mStartRegistration )
		return ;

	if( mOptimizer )
	{
		mOptimizer->unref();
		mOptimizer = 0;
		SO_ENGINE_OUTPUT( OutputOptimizer, SoItkSFDataOptimizer, setValue( 0 ) );
	}

	SO_ENGINE_OUTPUT( LastTransformParameters, SoMFFloat, setNum( 0 ) );

	if( !checkInput() )
	{
		SoDebugError::post( __FILE__, "Invalid Input Types" );
		return ;
	}

	try
	{
		switch( FixedImage.getValue()->getType() )
		{
			case SoItkDataImage::FLOAT:
			{
				switch( MovingImage.getValue()->getNumDimension() )
				{
					case 2:
					{
						typedef itk::Image< float, 2 > InputImageType;
						typedef itk::Image< float, 2 > OutputImageType;
						typedef itk::Image< float, 2 > InputImageType;
						typedef itk::Image< float, 2 > OutputImageType;
						typedef itk::Array< double > ArrayType;
						typedef itk::ImageToImageMetric< InputImageType, OutputImageType > MetricType;
						typedef itk::SingleValuedNonLinearOptimizer OptimizerType;
						typedef double CoordinateRepresentationType;
						typedef itk::Transform< CoordinateRepresentationType, 2, 2 > TransformType;
						typedef itk::Image< float, 2 > InputImageType;
						typedef double CoordinateRepresentationType;
						typedef itk::InterpolateImageFunction< InputImageType, CoordinateRepresentationType > InterpolatorType;
						typedef itk::ImageRegistrationMethod< InputImageType, OutputImageType > FilterType;

						FilterType::Pointer filter = FilterType::New();

						SO_ITK_SET_FIELD_ARRAY( filter, InitialTransformParameters, double );
						SO_ITK_SET_FIELD_DATA( filter, FixedImage, InputImageType );
						SO_ITK_SET_FIELD_DATA( filter, MovingImage, InputImageType );
						SO_ITK_SET_FIELD_IMAGE_REGION( filter, FixedImageRegion, 2 );
						SO_ITK_SET_FIELD_DATA( filter, Interpolator, InterpolatorType );
						SO_ITK_SET_FIELD_DATA( filter, Metric, MetricType );
						SO_ITK_SET_FIELD_DATA( filter, Transform, TransformType );
						SO_ITK_SET_FIELD_DATA( filter, Optimizer, OptimizerType );

						// Start processing the ouputs
						filter->StartRegistration();

						// Retrieve the filter's outputs
						ArrayType lastParameters = filter->GetLastTransformParameters();
						unsigned int numberOfParameters = lastParameters.size();
						float* parameters = new float[ numberOfParameters ];
						for( unsigned int i = 0; i < numberOfParameters; ++ i )
							parameters[i] = lastParameters( i );

                        SO_ENGINE_OUTPUT( LastTransformParameters, SoMFFloat, setValues( 0, numberOfParameters, parameters ) );
						delete [] parameters;

						filter->GetOptimizer()->Register();

						mOptimizer = new SoItkDataOptimizer();
						mOptimizer->ref();
						mOptimizer->setPointer( filter->GetOptimizer() );

						SO_ENGINE_OUTPUT( OutputOptimizer, SoItkSFDataOptimizer, setValue( mOptimizer ) );

						SoDebugError::post( __FILE__, "Registration Done (FLOAT 2)" );
					}
					break ;
					case 3:
					{
						typedef itk::Image< float, 3 > InputImageType;
						typedef itk::Image< float, 3 > OutputImageType;
						typedef itk::Image< float, 3 > InputImageType;
						typedef itk::Image< float, 3 > OutputImageType;
						typedef itk::Array< double > ArrayType;
						typedef itk::ImageToImageMetric< InputImageType, OutputImageType > MetricType;
						typedef itk::SingleValuedNonLinearOptimizer OptimizerType;
						typedef double CoordinateRepresentationType;
						typedef itk::Transform< CoordinateRepresentationType, 3, 3 > TransformType;
						typedef itk::Image< float, 3 > InputImageType;
						typedef double CoordinateRepresentationType;
						typedef itk::InterpolateImageFunction< InputImageType, CoordinateRepresentationType > InterpolatorType;
						typedef itk::ImageRegistrationMethod< InputImageType, OutputImageType > FilterType;

						FilterType::Pointer filter = FilterType::New();

						SO_ITK_SET_FIELD_ARRAY( filter, InitialTransformParameters, double );
						SO_ITK_SET_FIELD_DATA( filter, FixedImage, InputImageType );
						SO_ITK_SET_FIELD_DATA( filter, MovingImage, InputImageType );
						SO_ITK_SET_FIELD_IMAGE_REGION( filter, FixedImageRegion, 3 );
						SO_ITK_SET_FIELD_DATA( filter, Interpolator, InterpolatorType );
						SO_ITK_SET_FIELD_DATA( filter, Metric, MetricType );
						SO_ITK_SET_FIELD_DATA( filter, Transform, TransformType );
						SO_ITK_SET_FIELD_DATA( filter, Optimizer, OptimizerType );
						// Start processing the ouputs
						filter->StartRegistration();

						// Retrieve the filter's outputs
						ArrayType lastParameters = filter->GetLastTransformParameters();
						unsigned int numberOfParameters = lastParameters.size();
						float* parameters = new float[ numberOfParameters ];
						for( unsigned int i = 0; i < numberOfParameters; ++ i )
							parameters[i] = lastParameters( i );

                        SO_ENGINE_OUTPUT( LastTransformParameters, SoMFFloat, setValues( 0, numberOfParameters, parameters ) );
						delete [] parameters;

						filter->GetOptimizer()->Register();

						mOptimizer = new SoItkDataOptimizer();
						mOptimizer->ref();
						mOptimizer->setPointer( filter->GetOptimizer() );

						SO_ENGINE_OUTPUT( OutputOptimizer, SoItkSFDataOptimizer, setValue( mOptimizer ) );

						SoDebugError::post( __FILE__, "Registration Done (FLOAT 3)" );
					}
					break ;
				}
			}
			break ;
			case SoItkDataImage::UNSIGNED_SHORT:
			{
				switch( MovingImage.getValue()->getNumDimension() )
				{
					case 2:
					{
						typedef itk::Image< unsigned short, 2 > InputImageType;
						typedef itk::Image< unsigned short, 2 > OutputImageType;
						typedef itk::Image< unsigned short, 2 > InputImageType;
						typedef itk::Image< unsigned short, 2 > OutputImageType;
						typedef itk::Array< double > ArrayType;
						typedef itk::ImageToImageMetric< InputImageType, OutputImageType > MetricType;
						typedef itk::SingleValuedNonLinearOptimizer OptimizerType;
						typedef double CoordinateRepresentationType;
						typedef itk::Transform< CoordinateRepresentationType, 2, 2 > TransformType;
						typedef itk::Image< unsigned short, 2 > InputImageType;
						typedef double CoordinateRepresentationType;
						typedef itk::InterpolateImageFunction< InputImageType, CoordinateRepresentationType > InterpolatorType;
						typedef itk::ImageRegistrationMethod< InputImageType, OutputImageType > FilterType;

						FilterType::Pointer filter = FilterType::New();

						SO_ITK_SET_FIELD_ARRAY( filter, InitialTransformParameters, double );
						SO_ITK_SET_FIELD_DATA( filter, FixedImage, InputImageType );
						SO_ITK_SET_FIELD_DATA( filter, MovingImage, InputImageType );
						SO_ITK_SET_FIELD_IMAGE_REGION( filter, FixedImageRegion, 2 );
						SO_ITK_SET_FIELD_DATA( filter, Interpolator, InterpolatorType );
						SO_ITK_SET_FIELD_DATA( filter, Metric, MetricType );
						SO_ITK_SET_FIELD_DATA( filter, Transform, TransformType );
						SO_ITK_SET_FIELD_DATA( filter, Optimizer, OptimizerType );

						// Start processing the ouputs
						filter->StartRegistration();

						// Retrieve the filter's outputs
						ArrayType lastParameters = filter->GetLastTransformParameters();
						unsigned int numberOfParameters = lastParameters.size();
						float* parameters = new float[ numberOfParameters ];
						for( unsigned int i = 0; i < numberOfParameters; ++ i )
							parameters[i] = lastParameters( i );

                        SO_ENGINE_OUTPUT( LastTransformParameters, SoMFFloat, setValues( 0, numberOfParameters, parameters ) );
						delete [] parameters;

						filter->GetOptimizer()->Register();

						mOptimizer = new SoItkDataOptimizer();
						mOptimizer->ref();
						mOptimizer->setPointer( filter->GetOptimizer() );

						SO_ENGINE_OUTPUT( OutputOptimizer, SoItkSFDataOptimizer, setValue( mOptimizer ) );

						SoDebugError::post( __FILE__, "Registration Done (US 2)" );
					}
					break ;
					case 3:
					{
						typedef itk::Image< unsigned short, 3 > InputImageType;
						typedef itk::Image< unsigned short, 3 > OutputImageType;
						typedef itk::Image< unsigned short, 3 > InputImageType;
						typedef itk::Image< unsigned short, 3 > OutputImageType;
						typedef itk::Array< double > ArrayType;
						typedef itk::ImageToImageMetric< InputImageType, OutputImageType > MetricType;
						typedef itk::SingleValuedNonLinearOptimizer OptimizerType;
						typedef double CoordinateRepresentationType;
						typedef itk::Transform< CoordinateRepresentationType, 3, 3 > TransformType;
						typedef itk::Image< unsigned short, 3 > InputImageType;
						typedef double CoordinateRepresentationType;
						typedef itk::InterpolateImageFunction< InputImageType, CoordinateRepresentationType > InterpolatorType;
						typedef itk::ImageRegistrationMethod< InputImageType, OutputImageType > FilterType;

						FilterType::Pointer filter = FilterType::New();

						SO_ITK_SET_FIELD_ARRAY( filter, InitialTransformParameters, double );
						SO_ITK_SET_FIELD_DATA( filter, FixedImage, InputImageType );
						SO_ITK_SET_FIELD_DATA( filter, MovingImage, InputImageType );
						SO_ITK_SET_FIELD_IMAGE_REGION( filter, FixedImageRegion, 3 );
						SO_ITK_SET_FIELD_DATA( filter, Interpolator, InterpolatorType );
						SO_ITK_SET_FIELD_DATA( filter, Metric, MetricType );
						SO_ITK_SET_FIELD_DATA( filter, Transform, TransformType );
						SO_ITK_SET_FIELD_DATA( filter, Optimizer, OptimizerType );

						// Start processing the ouputs
						filter->StartRegistration();

						// Retrieve the filter's outputs
						ArrayType lastParameters = filter->GetLastTransformParameters();
						unsigned int numberOfParameters = lastParameters.size();
						float* parameters = new float[ numberOfParameters ];
						for( unsigned int i = 0; i < numberOfParameters; ++ i )
							parameters[i] = lastParameters( i );

                        SO_ENGINE_OUTPUT( LastTransformParameters, SoMFFloat, setValues( 0, numberOfParameters, parameters ) );
						delete [] parameters;

						filter->GetOptimizer()->Register();

						mOptimizer = new SoItkDataOptimizer();
						mOptimizer->ref();
						mOptimizer->setPointer( filter->GetOptimizer() );

						SO_ENGINE_OUTPUT( OutputOptimizer, SoItkSFDataOptimizer, setValue( mOptimizer ) );

						SoDebugError::post( __FILE__, "Registration Done (US 3)" );
					}
					break ;
				}
			}
			break ;
		}
	}
	catch( itk::ExceptionObject& e )
	{
		SoDebugError::post( e.GetFile(), "line %d: %s", e.GetLine(), e.GetDescription() );
	}
	catch(...)
	{
		SoDebugError::post( __FILE__, "Unknown Exception" );
	}

	mStartRegistration = false;
}

void
SoItkImageRegistrationMethod::inputChanged( SoField* whichInput )
{
	if( whichInput == &Start )
	{
		mStartRegistration = true;
	}
}


text:
from __future__ import unicode_literals

import datetime
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('imager_images', '0004_auto_20170122_1510'),
    ]

    operations = [
        migrations.AlterField(
            model_name='album',
            name='cover_photo',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cover', to='imager_images.Photo'),
        ),
        migrations.AlterField(
            model_name='album',
            name='date_modified',
            field=models.DateField(auto_now_add=True, default='2017-01-24'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='album',
            name='date_published',
            field=models.DateField(auto_now_add=True, default=datetime.datetime(2017, 1, 24, 16, 44, 29, 561654)),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='album',
            name='published',
            field=models.CharField(blank=True, choices=[('PRIVATE', 'Private'), ('SHARED', 'Shared'), ('PUBLIC', 'Public'), ('', 'Select who can view')], max_length=255, null=True),
        ),
        migrations.AlterField(
            model_name='photo',
            name='date_published',
            field=models.DateField(auto_now_add=True, default=datetime.datetime(2017, 1, 24, 16, 44, 56, 344508)),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='photo',
            name='published',
            field=models.CharField(blank=True, choices=[('PRIVATE', 'Private'), ('SHARED', 'Shared'), ('PUBLIC', 'Public'), ('', 'Select who can view')], max_length=255, null=True),
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
import sys
import os
import numpy as np
import nibabel as nib

USAGE = """
USAGE :
  dropout.py <fmap mag nifti> <fmap nifti> <TE>

ARGS :
  <fmap mag nifti> - Nifti-1 fieldmap magnitude image filename
  <fmap nifti>     - Nifti-1 fieldmap (in rad/s) image filename
  <TE>             - new effective TE in ms for dropout calculation [30 ms]
"""

# Main function
def main():

  # Command line args
  if len(sys.argv) < 3:
    print(USAGE)
    sys.exit()
  else:
    fmap_mag_file = sys.argv[1]
    fmap_file = sys.argv[2]

  # Simulated echo time in seconds
  if len(sys.argv) < 5:
    TE = 30.0
  else:
    TE = float(sys.argv[3]) / 1000.0

  # Isolate file stub in presence of .nii.gz or .nii extensions
  if '.nii.gz' in fmap_mag_file:
    dropout_file = fmap_mag_file[:-7]
  else:
    if '.nii' in fmap_mag_file:
      dropout_file = fmap_mag_file[:-4]
    else:
      dropout_file = fmap_mag_file

  # Complete output filename
  dropout_file = dropout_file + '_dropout.nii.gz'

  # Report arguments
  print('')
  print('Gradient Echo Dropout Simulator')
  print('-------------------------------')
  print('Fieldmap magnitude : ' + fmap_mag_file)
  print('Fieldmap phase     : ' + fmap_file)
  print('Simulated TE       : ' + str(TE) + ' ms')
  print('Adjusted mag image : ' + dropout_file)
  print('')
  print('Simulating intravoxel dephasing')

  # Load fmap_mag and fmap volumes
  # See http://niftilib.sourceforge.net/pynifti/examples.html for examples

  print('  Loading phase image from ' + fmap_file)
  try:
    nim_phi = nib.load(fmap_file)
  except:
    sys.exit()

  # Get phase data from Niftidd object
  phi = nim_phi.get_data()

  # Calculate grad(phi). Returns numpy array
  print('  Calculating grad(phi)')
  Gz, Gy, Gx = np.gradient(phi)

  # Calculate absolute gradient magnitude and scale to Hz/voxel
  print('  Calculating scaled absolute gradient')
  aG = np.sqrt(Gx*Gx + Gy*Gy + Gz*Gz) / (2 * np.pi)

  # Weighting function estimates additional signal loss from intravoxel
  # dephasing assuming spherical voxel and local linear gradient.
  # TODO: account for imaging x susceptibility gradient interactions
  print('  Calculating intravoxel dephasing weight')
  w = np.abs(np.sinc(TE / 1000.0 * aG))

  print('  Loading magnitude image from ' + fmap_mag_file)
  try:
    nim_M = nib.load(fmap_mag_file)
  except:
    sys.exit()

  # Get mag data from Nifti object
  M = nim_M.get_data()

  # Create signal mask from mag data
  # Use 10% of 99th percentile as threshold
  p99 = np.percentile(M, 99)
  M_mask = (M > p99 * 0.1).astype(int)

  # Adjust TE of magnitude image
  print('  Applying weight to magnitude image')
  M_dropout = M * w

  # Create signal masked dropout weight image
  w_mask = w * M_mask

  # Construct TE-adjusted mag output image - same affine transform as original mag image
  nim_M_dropout = nib.Nifti1Image(M_dropout, nim_M.get_affine())

  # Save TE-adjusted mag image
  print('  Saving TE adjusted magnitude image to ' + dropout_file)
  nim_M_dropout.to_filename(dropout_file)

  print('Done')
  print('')

# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
    main()


text:
<?php

namespace DoL\LdapBundle\Model;

/**
 * User interface.
 * Ldap users must implement this interface.
 *
 * @author DarwinOnLine
 * @author Maks3w
 *
 * @see https://github.com/DarwinOnLine/DoLLdapBundle
 */
interface LdapUserInterface
{
    /**
     * Set Ldap Distinguished Name.
     *
     * @param string $dn Distinguished Name
     */
    public function setDn($dn);

    /**
     * Get Ldap Distinguished Name.
     *
     * @return string Distinguished Name
     */
    public function getDn();
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class players.SLPlayer
</TITLE>

<META NAME="date" CONTENT="2011-08-11">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
players.SLPlayer

Packages that use SLPlayer

lizardSpock

players

Uses of SLPlayer in lizardSpock

Fields in lizardSpock declared as SLPlayer

(package private)  SLPlayer
SLArena.SoundTestListener.player

private  SLPlayer
PlayerCanvas.player

          The player to be drawn on this canvas

protected  SLPlayer
SLArena.player1

          A player

protected  SLPlayer
SLArena.player2

          A player

Constructors in lizardSpock with parameters of type SLPlayer

PlayerCanvas(SLPlayer player)

          Loads the player so it can call the draw method.

SLArena.SoundTestListener(SLPlayer player)

          Constructor.

Uses of SLPlayer in players

Subclasses of SLPlayer in players

 class
CopyCat

          Rock-scissors-paper player that always copies the opponent's last move.

 class
DrSequence

          This player repeats a randomly generated sequence of moves

 class
MrPredictable

          Rock-scissors-paper player that always uses the same sequence.

 class
MsRandom

          Rock-scissors-paper player that plays randomly.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
import numpy as np
import gnumpy as gnp

from act_functions import Softmax, ReLU
from datetime import datetime

class DNN(object):
    learning_rate = None
    batch_size = 0
    epochs = 0
    verbose = 0
    hidden_function = ReLU
    output_function = Softmax

    def __init__(self, layer_sizes, scale=0.05, verbose=1, l2=0.0001,
                 momentum=0.9, epochs=20, batch_size=256,dropouts=0.0,
                 learning_rate=0.01, learning_rate_decays=0.9):

        self.layer_sizes = layer_sizes
        self.scale = scale
        self.verbose = 1
        self.l2 = l2
        self.momentum = momentum

        self.epochs = epochs
        self.batch_size = batch_size
        self.dropouts = [dropouts for l in range(len(layer_sizes)-1)]

        self.learning_rate = learning_rate
        self.learning_rate_decays = learning_rate_decays

        shapes = [(layer_sizes[i-1], layer_sizes[i])
                  for i in range(1, len(layer_sizes))]

        self.biases = init_biases_matrix(layer_sizes)
        self.weights = init_weights_matrix(shapes, scale)
        self.rms_limits = [None for i in range(len(self.weights))]

        self.hidden_functions = [self.hidden_function for i in range(len(self.weights) - 1)]

        self.weight_grads = [gnp.zeros(weight.shape) for weight in self.weights]
        self.bias_grads = [gnp.zeros(bias.shape) for bias in self.biases]

    def _onehot_encode(self, y):
        if len(y.shape) == 1:
            num_classes = y.max() + 1
            y_new = np.zeros((y.shape[0], num_classes), dtype=np.int)
            for index, label in enumerate(y):
                y_new[index][label] = 1
                y = y_new
        return y

    def _minibatches(self, X, y=None):
        X = np.array(X) if not isinstance(X, np.ndarray) else X
        y = np.array(y) if not isinstance(y, np.ndarray) else y
        while True:
            idx = np.random.randint(X.shape[0], size=(self.batch_size,))
            X_batch = X[idx]
            if y is not None:
                yield (X_batch, y[idx])
            else:
                yield X_batch

    def _adjust_learning_rate(self):
        self.learning_rate *= self.learning_rate_decays

    def _counter_num_mistakes(self, targets, predictions):
        if hasattr(targets, 'as_numpy_array'):
            targets = targets.as_numpy_array()
        if hasattr(predictions, 'as_numpy_array'):
            predictions = predictions.as_numpy_array()
        return np.sum(predictions.argmax(1) != targets.argmax(1))

    def save_weights(self, path):
        weights_path = "{0}_w".format(path)
        biases_path = "{0}_b".format(path)
        np.save(weights_path, self.weights)
        np.save(biases_path, self.biases)

    def load_weights(self, path):
        weights_path = "{0}_w".format(path)
        biases_path = "{0_b}".format(path)
        self.weights = np.load(weights_path)
        self.biases = np.load(biases_path)

    def fit(self, X, y, val_X=None, val_y=None):
        X = np.array(X)
        y = np.array(y)
        y = self._onehot_encode(y)
        iters_per_epoch = X.shape[0] / self.batch_size
        for epoch, err in enumerate(
            self.fine_tune(self._minibatches(X, y), iters_per_epoch, self.epochs)
        ):
            if epoch % 5 and val_y and val_X:
                print "val_score:{0}".format(self.score(val_X, val_y))
            print"epoch:{0}    ein:{1}".format(epoch, err)
            self._adjust_learning_rate()

    def predict_proba(self, X):
        prob_result = []
        for _input in np.array_split(X, 100):
            if _input is not isinstance(_input, gnp.garray):
                _input = gnp.garray(_input)
                output = self.feed_forward(_input)
                prob_result.append(output)
        return np.concatenate(prob_result)

    def predict(self, X):
        return np.argmax(self.predict_proba(X), axis=1)

    def score(self, X, y):
        predictions = self.predict(X)
        error_count = 0
        for i, y_p in enumerate(y):
            if y_p != predictions[i]:
                error_count += 1
        return error_count / float(X.shape[0])

    def fine_tune(self, mini_batch, iters_per_epoch, epochs):
        s_time = datetime.now()
        for epoch in range(epochs):
            total_errors = 0
            total_inputs = 0
            for i in range(iters_per_epoch):
                X, y = mini_batch.next()
                err, y_pred = self.epoch_update(X, y)
                total_inputs += X.shape[0]
                total_errors += self._counter_num_mistakes(y, y_pred)
            print datetime.now() - s_time
            yield total_errors / float(total_inputs)

    def scale_gradient(self, scale):
        for i in range(len(self.weights)):
            self.weight_grads[i] *= scale
            self.bias_grads[i] *= scale

    def feed_forward(self, input_batch):
        if not isinstance(input_batch, gnp.garray):
            input_batch = gnp.garray(input_batch)
        weights_to_stop = len(self.weights)
        self.state = [input_batch * (gnp.rand(*input_batch.shape) > self.dropouts[0])]

        for i in range(min(len(self.weights) -1, weights_to_stop)):
            do_factor = 1.0 / (1.0-self.dropouts[i])
            linear_outputs = gnp.dot(self.state[-1]*do_factor, self.weights[i]) + self.biases[i]
            act_outputs = self.hidden_functions[i].activate(linear_outputs)
            self.state.append(act_outputs*(gnp.rand(*act_outputs.shape) > self.dropouts[i+1]))

        if weights_to_stop >= len(self.weights):
            do_factor = 1.0 / (1.0-self.dropouts[-1])
            self.state.append(gnp.dot(self.state[-1]*do_factor, self.weights[-1]) + self.biases[-1])
            self.acts = self.output_function.activate(self.state[-1])
            return self.acts

        return self.state[weights_to_stop]

    def back_propagation(self, output_residual):
        feed_forward_state = self.state
        error_residual = [None for i in range(len(self.weights))]
        error_residual[-1] = output_residual
        for i in reversed(range(len(self.weights) -1)):
            residual = gnp.dot(error_residual[i+1], self.weights[i+1].T) * self.hidden_functions[i].residual(feed_forward_state[i+1])
            error_residual[i] = residual
        return error_residual

    def gradients(self, feed_forward_state, error_residual):
        for i in range(len(self.weights)):
            a = (gnp.dot(feed_forward_state[i].T, error_residual[i]),
                   error_residual[i].sum(axis=0))
            yield a

    def feed_back(self, input_batch, target_batch):
        output_result = self.feed_forward(input_batch)
        output_residual = -self.output_function.residual(target_batch, self.state[-1], output_result)
        error = self.output_function.error(target_batch, self.state[-1], output_result)
        error_residual = self.back_propagation(output_residual)
        return error_residual, output_result, error

    def epoch_update(self, input_batch, output_batch):
        this_batch_size = input_batch.shape[0]

        if not isinstance(input_batch, gnp.garray):
            input_batch = gnp.garray(input_batch)
        if not isinstance(output_batch, gnp.garray):
            output_batch = gnp.garray(output_batch)

        origin_weights = [w.copy() for w in self.weights]
        origin_biases = [b.copy() for b in self.biases]

        self.scale_gradient(self.momentum)
        self.update_weights(self.weights, self.biases, origin_weights,
                            origin_biases, self.weight_grads, self.bias_grads)

        error_residual, output_result, error = self.feed_back(input_batch, output_batch)

        w_factor = 1
        b_factor = 1
        for i, (w_grad, b_grad) in enumerate(self.gradients(self.state, error_residual)):
            self.weight_grads[i] += self.learning_rate * w_factor * (
                w_grad/this_batch_size - self.l2*self.weights[i])
            self.bias_grads[i] += (self.learning_rate*b_factor/this_batch_size) * b_grad

        self.update_weights(self.weights, self.biases, origin_weights,
                            origin_biases, self.weight_grads, self.bias_grads)
        self.constrain_weights()
        return error, output_result

    def update_weights(self, new_weights, new_biases, origin_weights, origin_biases,
                       weight_grads, bias_grads):
        for i in range(len(new_weights)):
            new_weights[i] = origin_weights[i] + weight_grads[i]
            new_biases[i] = origin_biases[i] + bias_grads[i]

    def constrain_weights(self):
        for i, rms_limit in enumerate(self.rms_limits):
            if not rms_limit:
                continue
            W = self.weights[i]
            rms_scale = rms_limit / gnp.sqrt(gnp.mean(W*W, axis=0))
            limit_rms = W * (1+(rms_scale < 1) * (rms_scale - 1))
            self.weights[i] = limit_rms

def init_weights_matrix(shapes, scale):
    weights = []
    for shape in shapes:
        fan_in = shape[0]
        W = scale * np.random.randn(*shape)
        for i in range(shape[1]):
            perm = np.random.permutation(shape[0])
            W[perm[fan_in:], i] *= 0
        weights.append(gnp.garray(W))
    return weights

def init_biases_matrix(layer_sizes):
    return [gnp.garray(0*np.random.rand(1, layer_sizes[i]))
            for i in range(1, len(layer_sizes))]


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

namespace Ack.Infrastructure.Loggers
{
    public class AggreagateLogger : ILogger
    {
        private IEnumerable<ILogger> Loggers { get; set; }

        public AggreagateLogger(IEnumerable<ILogger> loggers)
        {
            if (loggers == null)
            {
                throw new ArgumentNullException("loggers");
            }

            Loggers = loggers;
        }

        public void Log(string message)
        {
            foreach (var logger in Loggers)
            {
                try
                {
                    logger.Log(message);
                }
                catch { }
            }
        }
    }
}


text:
import { createStore, applyMiddleware, compose } from 'redux'
import thunkMiddleware from 'redux-thunk'
import { persistStore, persistReducer } from 'redux-persist'

import rootReducer from 'modules'
import persistConfig from 'configs/persistConfig'

const persistedReducer = persistReducer(persistConfig, rootReducer)
const middleware = compose(applyMiddleware(thunkMiddleware))

export default () => {
	const store = createStore(persistedReducer, middleware)
	const persistor = persistStore(store)
	return { store, persistor }
}


text:
/**
 * @fileoverview Implementation of {@link NavigationService} that is bound to {@link goog.History}.
 *
 * @author lvlcek@redhat.com (Lukas Vlcek)
 */

goog.provide('org.jboss.core.service.navigation.NavigationServiceHistory');

goog.require('goog.Disposable');
goog.require('goog.History');
goog.require('goog.events');
goog.require('goog.history.Event');
goog.require('goog.history.EventType');
goog.require('org.jboss.core.service.navigation.NavigationService');

/**
 * @param {!org.jboss.core.service.navigation.NavigationServiceDispatcher} dispatcher
 * @param {!goog.History} history
 * @constructor
 * @implements {org.jboss.core.service.navigation.NavigationService}
 * @extends {goog.Disposable}
 */
org.jboss.core.service.navigation.NavigationServiceHistory = function(dispatcher, history) {
  goog.Disposable.call(this);

  /**
   * @type {!org.jboss.core.service.navigation.NavigationServiceDispatcher}
   * @private
   */
  this.dispatcher_ = dispatcher;

  /**
   * @type {!goog.History}
   * @private
   */
  this.history_ = history;

  this.historyListenerKey_ = goog.events.listen(
      this.history_,
      goog.history.EventType.NAVIGATE,
      function(e) {
        var event = /** @type {goog.history.Event} */ (e);
        this.dispatcher_.dispatchNewNavigation(event.token);
      }, false, this
      );
};
goog.inherits(org.jboss.core.service.navigation.NavigationServiceHistory, goog.Disposable);

/** @inheritDoc */
org.jboss.core.service.navigation.NavigationServiceHistory.prototype.disposeInternal = function() {
  org.jboss.core.service.navigation.NavigationServiceHistory.superClass_.disposeInternal.call(this);
  goog.events.unlistenByKey(this.historyListenerKey_);
  delete this.dispatcher_;
  delete this.history_;
};

/** @inheritDoc */
org.jboss.core.service.navigation.NavigationServiceHistory.prototype.navigate = function(token) {
  this.history_.setToken(token);
};

/** @inheritDoc */
org.jboss.core.service.navigation.NavigationServiceHistory.prototype.setEnable = function(flag) {
  this.history_.setEnabled(flag);
};


text:
class CallbackForm < TransForms::FormBase
  attr_reader :user1, :user2, :i_was_called

  attribute :name1,      String
  attribute :name2,      String

  validates :name1, presence: true
  validates :name2, presence: true

  after_save_on_error :call_me

  transaction do
    @user1 = User.create!(name: name1)
    @user2 = User.create!(name: name2)
  end

protected
  def call_me(error)
    @i_was_called = true
  end

end


text:
module AntiSmoker
  module MemcacheModule
    VERSION = "0.0.2git"
  end
end


text:
package org.openspaces.persistency.hibernate;

import com.gigaspaces.datasource.BulkItem;
import com.gigaspaces.datasource.DataIterator;
import com.gigaspaces.datasource.DataSourceException;
import com.gigaspaces.datasource.ManagedDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.entity.AbstractEntityPersister;
import org.openspaces.persistency.hibernate.iterator.HibernateProxyRemoverIterator;
import org.openspaces.persistency.patterns.ManagedDataSourceEntriesProvider;
import org.openspaces.persistency.support.ConcurrentMultiDataIterator;

import java.util.*;

/**
 * A base class for Hibernate based external data source implementations.
 *
 *
See the different setters for more information and the {@link #init(java.util.Properties)}.
 *
 * @author kimchy
 * @deprecated since 9.5 - use {@link AbstractHibernateSpaceDataSource} or {@link AbstractHibernateSpaceSynchronizationEndpoint} instead.
 */
@Deprecated
public abstract class AbstractHibernateExternalDataSource implements ManagedDataSource, ManagedDataSourceEntriesProvider {

    protected final Log logger = LogFactory.getLog(getClass());

    public static final String HIBERNATE_CFG_PROPERTY = "hibernate-config-file";

    private SessionFactory sessionFactory;

    private Set<String> managedEntries;

    private String[] initialLoadEntries;

    private int fetchSize = 100;

    private int initialLoadThreadPoolSize = 10;

    private int initialLoadChunkSize = 100000;

    private boolean performOrderById = true;

    private boolean createdSessionFactory = true;

    private boolean useScrollableResultSet = true;

    /**
     * Injects the Hibernate SessionFactory to be used with this external data source.
     */
    public void setSessionFactory(SessionFactory sessionFactory) {
        createdSessionFactory = false;
        this.sessionFactory = sessionFactory;
    }

    /**
     * Returns the Hibernate session factory.
     */
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * Sets all the entries this Hibernate data source will work with. By default, will use Hibernate meta
     * data API in order to get the list of all the given entities it handles.
     *
     *
This list is used to filter out entities when performing all data source operations exception for
     * the {@link #initialLoad()} operation.
     *
     *
Usually, there is no need to explicitly set this.
     */
    public void setManagedEntries(String... entries) {
        this.managedEntries = new HashSet<String>();
        this.managedEntries.addAll(Arrays.asList(entries));
    }

    /**
     * Returns all the entries this Hibernate data source will work with. By default, will use Hibernate meta
     * data API in order to get the list of all the given entities it handles.
     *
     *
This list is used to filter out entities when performing all data source operations exception for
     * the {@link #initialLoad()} operation.
     */
    public String[] getManagedEntries() {
        return managedEntries.toArray(new String[managedEntries.size()]);
    }

    /**
     * Returns if the given entity name is part of the {@link #getManagedEntries()} list.
     */
    protected boolean isManagedEntry(String entityName) {
        return managedEntries.contains(entityName);
    }

    /**
     * Filter from the input map the unmapped field of this entity
     *
     * @param entityName
     * @param itemValues map of properties to filter
     *
     */
    protected Map<String, Object> filterItemValue( String entityName, Map<String, Object> itemValues){
        ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityName);
        String[] propertyNames = classMetadata.getPropertyNames();
        List<String> names = Arrays.asList(propertyNames);
        Iterator<String> iterator = itemValues.keySet().iterator();
        while(iterator.hasNext()){
            if(!names.contains(iterator.next()))
                iterator.remove();
        }
        return itemValues;
    }

    /**
     * Sets the fetch size that will be used when working with scrollable results. Defaults to
     * 100.
     *
     * @see org.hibernate.Criteria#setFetchSize(int)
     */
    public void setFetchSize(int fetchSize) {
        this.fetchSize = fetchSize;
    }

    /**
     * Returns the fetch size that will be used when working with scrollable results. Defaults to
     * 100.
     *
     * @see org.hibernate.Criteria#setFetchSize(int)
     */
    protected int getFetchSize() {
        return fetchSize;
    }

    /**
     * When performing initial load, this flag indicates if the generated query will order to results by
     * the id. By default set to true as it most times results in better initial load performance.
     */
    public void setPerformOrderById(boolean performOrderById) {
        this.performOrderById = performOrderById;
    }

    /**
     * When performing initial load, this flag indicates if the generated query will order to results by
     * the id. By default set to true as it most times results in better initial load performance.
     */
    protected boolean isPerformOrderById() {
        return performOrderById;
    }

    /**
     * Sets a list of entries that will be used to perform the {@link #initialLoad()} operation. By default, will
     * try and build a sensible list based on Hibernate meta data.
     *
     *
Note, sometimes an explicit list should be provided. For example, if we have a class A and class B, and
     * A has a relationship to B which is not component. If in the space, we only wish to have A, and have B just
     * as a field in A (and not as an Entry), then we need to explicitly set the list just to A. By default, if
     * we won't set it, it will result in two entries existing in the Space, A and B, with A having a field of B
     * as well.
     */
    public void setInitialLoadEntries(String... initialLoadEntries) {
        this.initialLoadEntries = initialLoadEntries;
    }

    /**
     * Returns a list of entries that will be used to perform the {@link #initialLoad()} operation. By default, will
     * try and build a sensible list based on Hibernate meta data.
     *
     *
Note, sometimes an explicit list should be provided. For example, if we have a class A and class B, and
     * A has a relationship to B which is not component. If in the space, we only wish to have A, and have B just
     * as a field in A (and not as an Entry), then we need to explicitly set the list just to A. By default, if
     * we won't set it, it will result in two entries existing in the Space, A and B, with A having a field of B
     * as well.
     */
    public String[] getInitialLoadEntries() {
        return initialLoadEntries;
    }

    /**
     * The initial load operation uses the {@link org.openspaces.persistency.support.ConcurrentMultiDataIterator}.
     * This property allows to control the thread pool size of the concurrent multi data iterator. Defaults to
     * 10.
     *
     *
Note, this usually will map one to one to the number of open connections / cursors against the database.
     */
    public void setInitialLoadThreadPoolSize(int initialLoadThreadPoolSize) {
        this.initialLoadThreadPoolSize = initialLoadThreadPoolSize;
    }

    /**
     * By default, the initial load process will chunk large tables and will iterate over the table (entity) per
     * chunk (concurrently). This setting allows to control the chunk size to split the table by. By default, set
     * to 100,000. Batching can be disabled by setting -1.
     */
    public void setInitialLoadChunkSize(int initalLoadChunkSize) {
        this.initialLoadChunkSize = initalLoadChunkSize;
    }

    /**
     * By default, the initial load process will chunk large tables and will iterate over the table (entity) per
     * chunk (concurrently). This setting allows to control the chunk size to split the table by. By default, set
     * to 100,000. Batching can be disabled by setting -1.
     */
    protected int getInitialLoadChunkSize() {
        return initialLoadChunkSize;
    }

    /**
     * Controls if scrollable resultsets will be used with initial load operation. Defaults to true.
     */
    protected boolean isUseScrollableResultSet() {
        return useScrollableResultSet;
    }

    /**
     * Controls if scrollable resultsets will be used with initial load operation. Defaults to true.
     */
    public void setUseScrollableResultSet(boolean useScrollableResultSet) {
        this.useScrollableResultSet = useScrollableResultSet;
    }

    /**
     * Initializes the hibernate data source. Called by the Space.
     *
     *
If the session factory was not injected using {@link #setSessionFactory(org.hibernate.SessionFactory)}, will
     * try can create it from the Properties file expecting to find a property called hibernate-config-file
     * with the location of the Hibernate config file.
     *
     *
Initializes the {@link #setManagedEntries(String...)} if they were not set explicitly by iterating over all
     * the mapped classes in Hibernate and adding them.
     *
     *
Also initializes the {@link #setInitialLoadEntries(String...)} if not set explicitly.
     */
    public void init(Properties properties) throws DataSourceException {
        if (logger.isDebugEnabled()) {
            logger.debug("Using initialLoadChunkSize [" + initialLoadChunkSize + "], fetchSize [" + fetchSize + "], initialLoadThreadPoolSize [" + initialLoadThreadPoolSize + "], performOrderById [" + performOrderById + "]");
        }
        if (sessionFactory == null) {
            createdSessionFactory = true;
            String hibernateFile = properties.getProperty(HIBERNATE_CFG_PROPERTY);
            if (hibernateFile == null) {
                logger.error("No session factory injected, and [" + HIBERNATE_CFG_PROPERTY + "] is not provided in the properties file, can't create session factory");
            }
            try {
                sessionFactory = SessionFactoryBuilder.getFactory(hibernateFile);
            } catch (Exception e) {
                throw new DataSourceException("Failed to create session factory from properties file [" + hibernateFile + "]",e);
            }
        }
        if (managedEntries == null) {
            managedEntries = new HashSet<String>();
            // try and derive the managedEntries
            Map<String, ClassMetadata> allClassMetaData = sessionFactory.getAllClassMetadata();
            for (String entityname : allClassMetaData.keySet()) {
                managedEntries.add(entityname);
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Using Hibernate managedEntries [" + managedEntries + "]");
        }
        if (initialLoadEntries == null) {
            Set<String> initialLoadEntries = new HashSet<String>();
            // try and derive the managedEntries
            Map<String, ClassMetadata> allClassMetaData = sessionFactory.getAllClassMetadata();
            for (Map.Entry<String, ClassMetadata> entry : allClassMetaData.entrySet()) {
                String entityname = entry.getKey();
                ClassMetadata classMetadata = entry.getValue();
                if (classMetadata.isInherited()) {
                    String superClassEntityName = ((AbstractEntityPersister) classMetadata).getMappedSuperclass();
                    ClassMetadata superClassMetadata = allClassMetaData.get(superClassEntityName);
                    Class superClass = superClassMetadata.getMappedClass();
                    // only filter out classes that their super class has mappings
                    if (superClass != null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Entity [" + entityname + "] is inherited and has a super class ["
                                    + superClass + "] filtering it out for initial load managedEntries");
                        }
                        continue;
                    }
                }
                initialLoadEntries.add(entityname);
            }
            this.initialLoadEntries = initialLoadEntries.toArray(new String[initialLoadEntries.size()]);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Using Hibernate initial load managedEntries [" + Arrays.toString(initialLoadEntries) + "]");
        }
    }

    /**
     * Shuts down the data source. If the session factory was created by this data source, will close it.
     */
    public void shutdown() throws DataSourceException {
        if (createdSessionFactory) {
            if (sessionFactory != null && !sessionFactory.isClosed()) {
                try {
                    sessionFactory.close();
                } finally {
                    sessionFactory = null;
                }
            }
        }
    }

    /**
     * A helper method that creates the initial load iterator using the {@link org.openspaces.persistency.support.ConcurrentMultiDataIterator}
     * with the provided {@link #setInitialLoadThreadPoolSize(int)} thread pool size.
     */
    protected DataIterator createInitialLoadIterator(DataIterator[] iterators) {
        return new HibernateProxyRemoverIterator(new ConcurrentMultiDataIterator(iterators, initialLoadThreadPoolSize));
    }

    protected boolean isManaged(BulkItem bulkItem) {

        String  typeName = bulkItem.getTypeName();
        if (!isManagedEntry(typeName)) {
            if (logger.isTraceEnabled()) {
                logger.trace("Entry [" + typeName + ":" + bulkItem+ "] is not managed, filtering it out");
            }
            return false;
        }

        return true;
    }

    protected String getPartialUpdateHQL(BulkItem updateBulkItem, Map<String, Object> updatedValues) {

        final StringBuilder updateQueryBuilder = new StringBuilder("update ");
        updateQueryBuilder.append(updateBulkItem.getTypeName() ).append(" set ");

        int i  = 0;
        for (Map.Entry<String, Object> updateEntry : updatedValues.entrySet()) {
            updateQueryBuilder.append(updateEntry.getKey()).append("=:").append(updateEntry.getKey());
            if(i < updatedValues.size()-1)
                updateQueryBuilder.append(',');
            i++;
        }

        updateQueryBuilder.append( " where ").append(updateBulkItem.getIdPropertyName())
        .append("=:id_"). append(updateBulkItem.getIdPropertyName());
        String hql = updateQueryBuilder.toString();
        if (logger.isTraceEnabled()) {
            logger.trace("Partial Update HQL [" + hql + ']');
        }
        return hql;
    }

}


text:
/*
 * This file is part of GLShaderDev.
 *
 * GLShaderDev is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GLShaderDev is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GLShaderDev.  If not, see <http://www.gnu.org/licenses/>
 */

#include "precompiled.hpp"
#include "QsciLexerGLSL.h"

#include <Qsci/qsciscintilla.h>

QsciLexerGLSL::QsciLexerGLSL(QObject* parent) noexcept
  : QsciLexerCustom(parent) {
  _defaultFont.setFamily("Monospace");
  _defaultFont.setPointSize(9);
  QFont ft(_defaultFont);

  ft.setBold(true);

  _styles[Default] = QsciStyle(Default);
  _styles[Default].setDescription("Default");
  // _styles[Default].setFont(defaultFont(0));

  _styles[Comment] = QsciStyle(Comment);
  _styles[Comment].setDescription("Comment");
  _styles[Comment].setColor("#888888");
  // _styles[Comment].setFont(defaultFont(0));

  _styles[Keyword] = QsciStyle(Keyword);
  _styles[Keyword].setDescription("Keyword");
  _styles[Keyword].setColor("#22ff55");
  // _styles[Keyword].setFont(ft);

  _styles[Operator] = QsciStyle(Operator);
  _styles[Operator].setDescription("Operator");
  _styles[Operator].setColor("#2288ff");
  // _styles[Operator].setFont(ft);

  _styles[Macro] = QsciStyle(Macro);
  _styles[Macro].setDescription("Macro");
  _styles[Macro].setColor("#001100");
  // _styles[Macro].setFont(ft);
}

QsciLexerGLSL::~QsciLexerGLSL() {}

const char* QsciLexerGLSL::language() const noexcept {
  return "GLSL";
}

QStringList QsciLexerGLSL::autoCompletionWordSeparators() const noexcept {
  return {"."};
}

const char* QsciLexerGLSL::blockStartKeyword(int* style) const noexcept {
  if (style) {
    *style = Keyword;
  }

  return ("case catch class default do else for if while");
}

const char* QsciLexerGLSL::blockStart(int* style) const noexcept {
  if (style) {
    *style = Operator;
  }

  return ("{");
}

const char* QsciLexerGLSL::blockEnd(int* style) const noexcept {
  if (style) {
    *style = Operator;
  }

  return ("}");
}

int QsciLexerGLSL::braceStyle() const noexcept {
  return (Operator);
}

void QsciLexerGLSL::styleText(int start, int end) noexcept {
  std::vector<char> range(end - start + 1, '\0');
  editor()->SendScintilla(
    QsciScintilla::SCI_GETTEXTRANGE, start, end, range.data());
  QString text(range.data());

  startStyling(start);
  QStringList lines = text.split('\n');

  for (int i = 0; i < lines.size(); i++) {
    int style = Default;

    if (lines.at(i).startsWith("//")) {
      style = Comment;
    }

    if (lines.at(i).startsWith("#")) {
      style = Macro;
    }

    setStyling(lines.at(i).size(), style);

    if (Q_LIKELY(i < lines.size() - 1)) {
      setStyling(1, Default);
    }
  }
}

QString QsciLexerGLSL::description(int style) const noexcept {
  if (style < 0 || style >= Count) {
    style = 0;
  }

  return (_styles.at(style).description());
}

QFont QsciLexerGLSL::defaultFont(int style) const noexcept {
  if (style < 0 || style >= Count) {
    style = 0;
  }

  return (_styles.at(style).font());
}

QColor QsciLexerGLSL::defaultColor(int style) const noexcept {
  if (style < 0 || style >= Count) {
    style = 0;
  }

  return (_styles.at(style).color());
}

QColor QsciLexerGLSL::defaultPaper(int style) const noexcept {
  return QsciLexer::defaultPaper(style);
}

bool QsciLexerGLSL::defaultEolFill(int style) const noexcept {
  return QsciLexer::defaultEolFill(style);
}

const char* QsciLexerGLSL::keywords(int set) const noexcept {
  if (set == 1) {
    return ("in out varying uniform");
  }

  return (0);
}

const char* QsciLexerGLSL::wordCharacters() const noexcept {
  return ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_");
}

void QsciLexerGLSL::styleLine(const QString& line, int size) noexcept {
  setStyling(size, Default);
  qDebug() << "styleLine(" + line;
}


text:
             —

Start

             —

Duration

          Runtime Arguments

            <button class="btn btn-blue"
                 ng-if="TopPanelCtrl.runPlayer.action === 'STARTING'"
                 ng-disabled="!TopPanelCtrl.isValidToStartOrSchedule()"
                 ng-click="TopPanelCtrl.startPipeline()">
              Start Now
            </button>
            <button class="btn btn-blue"
                 ng-if="TopPanelCtrl.runPlayer.action === 'SCHEDULING'"
                 ng-disabled="!TopPanelCtrl.isValidToStartOrSchedule()"
                 ng-click="TopPanelCtrl.schedulePipeline()">
              Schedule
            </button>

    <div class="btn"
      uib-tooltip="Delete"
      tooltip-placement="left"
      tooltip-append-to-body="true"
      tooltip-class="toppanel-tooltip"
      ng-click="caskConfirm()"
      cask-confirmable="TopPanelCtrl.do('Delete')"
      data-confirmable-content="Are you sure you want to delete the pipeline '{{TopPanelCtrl.app.name}}'?">

    <my-log-viewer
      namespace-id="{{LogsCtrl.params.namespace}}"
      app-id="{{LogsCtrl.params.appId}}"
      program-type="{{LogsCtrl.params.programType}}"
      program-id="{{LogsCtrl.params.programId}}"
      run-id="{{LogsCtrl.params.runId}}">
    </my-log-viewer>


text:
<?php
/**
 * Body1
 *
 * PHP version 5
 *
 * @category Class
 * @package  SendinBlue\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * SendinBlue API
 *
 * SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to :   - Manage your campaigns and get the statistics   - Manage your contacts   - Send transactional Emails and SMS   - and much more...  You can download our wrappers at https://github.com/orgs/sendinblue  **Possible responses**   | Code | Message |   | :-------------: | ------------- |   | 200  | OK. Successful Request  |   | 201  | OK. Successful Creation |   | 202  | OK. Request accepted |   | 204  | OK. Successful Update/Deletion  |   | 400  | Error. Bad Request  |   | 401  | Error. Authentication Needed  |   | 402  | Error. Not enough credit, plan upgrade needed  |   | 403  | Error. Permission denied  |   | 404  | Error. Object does not exist |   | 405  | Error. Method not allowed  |   | 406  | Error. Not Acceptable  |
 *
 * OpenAPI spec version: 3.0.0
 * Contact: contact@sendinblue.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.19
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace SendinBlue\Client\Model;

use \ArrayAccess;
use \SendinBlue\Client\ObjectSerializer;

/**
 * Body1 Class Doc Comment
 *
 * @category Class
 * @package  SendinBlue\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class Body1 implements ModelInterface, ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      *
      * @var string
      */
    protected static $swaggerModelName = 'body_1';

    /**
      * Array of property to type mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerTypes = [
        'name' => 'string',
        'duration' => 'int',
        'taskTypeId' => 'string',
        'date' => '\DateTime',
        'notes' => 'string',
        'done' => 'bool',
        'assignToId' => 'string',
        'contactsIds' => 'int[]',
        'dealsIds' => 'string[]',
        'companiesIds' => 'string[]',
        'reminder' => '\SendinBlue\Client\Model\TaskReminder'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerFormats = [
        'name' => null,
        'duration' => null,
        'taskTypeId' => null,
        'date' => 'date-time',
        'notes' => null,
        'done' => null,
        'assignToId' => null,
        'contactsIds' => null,
        'dealsIds' => null,
        'companiesIds' => null,
        'reminder' => null
    ];

    /**
     * Array of property to type mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    /**
     * Array of property to format mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @var string[]
     */
    protected static $attributeMap = [
        'name' => 'name',
        'duration' => 'duration',
        'taskTypeId' => 'taskTypeId',
        'date' => 'date',
        'notes' => 'notes',
        'done' => 'done',
        'assignToId' => 'assignToId',
        'contactsIds' => 'contactsIds',
        'dealsIds' => 'dealsIds',
        'companiesIds' => 'companiesIds',
        'reminder' => 'reminder'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @var string[]
     */
    protected static $setters = [
        'name' => 'setName',
        'duration' => 'setDuration',
        'taskTypeId' => 'setTaskTypeId',
        'date' => 'setDate',
        'notes' => 'setNotes',
        'done' => 'setDone',
        'assignToId' => 'setAssignToId',
        'contactsIds' => 'setContactsIds',
        'dealsIds' => 'setDealsIds',
        'companiesIds' => 'setCompaniesIds',
        'reminder' => 'setReminder'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @var string[]
     */
    protected static $getters = [
        'name' => 'getName',
        'duration' => 'getDuration',
        'taskTypeId' => 'getTaskTypeId',
        'date' => 'getDate',
        'notes' => 'getNotes',
        'done' => 'getDone',
        'assignToId' => 'getAssignToId',
        'contactsIds' => 'getContactsIds',
        'dealsIds' => 'getDealsIds',
        'companiesIds' => 'getCompaniesIds',
        'reminder' => 'getReminder'
    ];

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @return array
     */
    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @return array
     */
    public static function setters()
    {
        return self::$setters;
    }

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @return array
     */
    public static function getters()
    {
        return self::$getters;
    }

    /**
     * The original name of the model.
     *
     * @return string
     */
    public function getModelName()
    {
        return self::$swaggerModelName;
    }

    /**
     * Associative array for storing property values
     *
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     *
     * @param mixed[] $data Associated array of property values
     *                      initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['name'] = isset($data['name']) ? $data['name'] : null;
        $this->container['duration'] = isset($data['duration']) ? $data['duration'] : null;
        $this->container['taskTypeId'] = isset($data['taskTypeId']) ? $data['taskTypeId'] : null;
        $this->container['date'] = isset($data['date']) ? $data['date'] : null;
        $this->container['notes'] = isset($data['notes']) ? $data['notes'] : null;
        $this->container['done'] = isset($data['done']) ? $data['done'] : null;
        $this->container['assignToId'] = isset($data['assignToId']) ? $data['assignToId'] : null;
        $this->container['contactsIds'] = isset($data['contactsIds']) ? $data['contactsIds'] : null;
        $this->container['dealsIds'] = isset($data['dealsIds']) ? $data['dealsIds'] : null;
        $this->container['companiesIds'] = isset($data['companiesIds']) ? $data['companiesIds'] : null;
        $this->container['reminder'] = isset($data['reminder']) ? $data['reminder'] : null;
    }

    /**
     * Show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalidProperties = [];

        if ($this->container['name'] === null) {
            $invalidProperties[] = "'name' can't be null";
        }
        if ($this->container['taskTypeId'] === null) {
            $invalidProperties[] = "'taskTypeId' can't be null";
        }
        if ($this->container['date'] === null) {
            $invalidProperties[] = "'date' can't be null";
        }
        return $invalidProperties;
    }

    /**
     * Validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {
        return count($this->listInvalidProperties()) === 0;
    }

    /**
     * Gets name
     *
     * @return string
     */
    public function getName()
    {
        return $this->container['name'];
    }

    /**
     * Sets name
     *
     * @param string $name Name of task
     *
     * @return $this
     */
    public function setName($name)
    {
        $this->container['name'] = $name;

        return $this;
    }

    /**
     * Gets duration
     *
     * @return int
     */
    public function getDuration()
    {
        return $this->container['duration'];
    }

    /**
     * Sets duration
     *
     * @param int $duration Duration of task in milliseconds [1 minute = 60000 ms]
     *
     * @return $this
     */
    public function setDuration($duration)
    {
        $this->container['duration'] = $duration;

        return $this;
    }

    /**
     * Gets taskTypeId
     *
     * @return string
     */
    public function getTaskTypeId()
    {
        return $this->container['taskTypeId'];
    }

    /**
     * Sets taskTypeId
     *
     * @param string $taskTypeId Id for type of task e.g Call / Email / Meeting etc.
     *
     * @return $this
     */
    public function setTaskTypeId($taskTypeId)
    {
        $this->container['taskTypeId'] = $taskTypeId;

        return $this;
    }

    /**
     * Gets date
     *
     * @return \DateTime
     */
    public function getDate()
    {
        return $this->container['date'];
    }

    /**
     * Sets date
     *
     * @param \DateTime $date Task date/time
     *
     * @return $this
     */
    public function setDate($date)
    {
        $this->container['date'] = $date;

        return $this;
    }

    /**
     * Gets notes
     *
     * @return string
     */
    public function getNotes()
    {
        return $this->container['notes'];
    }

    /**
     * Sets notes
     *
     * @param string $notes Notes added to a task
     *
     * @return $this
     */
    public function setNotes($notes)
    {
        $this->container['notes'] = $notes;

        return $this;
    }

    /**
     * Gets done
     *
     * @return bool
     */
    public function getDone()
    {
        return $this->container['done'];
    }

    /**
     * Sets done
     *
     * @param bool $done Task marked as done
     *
     * @return $this
     */
    public function setDone($done)
    {
        $this->container['done'] = $done;

        return $this;
    }

    /**
     * Gets assignToId
     *
     * @return string
     */
    public function getAssignToId()
    {
        return $this->container['assignToId'];
    }

    /**
     * Sets assignToId
     *
     * @param string $assignToId User id to whom task is assigned
     *
     * @return $this
     */
    public function setAssignToId($assignToId)
    {
        $this->container['assignToId'] = $assignToId;

        return $this;
    }

    /**
     * Gets contactsIds
     *
     * @return int[]
     */
    public function getContactsIds()
    {
        return $this->container['contactsIds'];
    }

    /**
     * Sets contactsIds
     *
     * @param int[] $contactsIds Contact ids for contacts linked to this task
     *
     * @return $this
     */
    public function setContactsIds($contactsIds)
    {
        $this->container['contactsIds'] = $contactsIds;

        return $this;
    }

    /**
     * Gets dealsIds
     *
     * @return string[]
     */
    public function getDealsIds()
    {
        return $this->container['dealsIds'];
    }

    /**
     * Sets dealsIds
     *
     * @param string[] $dealsIds Deal ids for deals a task is linked to
     *
     * @return $this
     */
    public function setDealsIds($dealsIds)
    {
        $this->container['dealsIds'] = $dealsIds;

        return $this;
    }

    /**
     * Gets companiesIds
     *
     * @return string[]
     */
    public function getCompaniesIds()
    {
        return $this->container['companiesIds'];
    }

    /**
     * Sets companiesIds
     *
     * @param string[] $companiesIds Companies ids for companies a task is linked to
     *
     * @return $this
     */
    public function setCompaniesIds($companiesIds)
    {
        $this->container['companiesIds'] = $companiesIds;

        return $this;
    }

    /**
     * Gets reminder
     *
     * @return \SendinBlue\Client\Model\TaskReminder
     */
    public function getReminder()
    {
        return $this->container['reminder'];
    }

    /**
     * Sets reminder
     *
     * @param \SendinBlue\Client\Model\TaskReminder $reminder reminder
     *
     * @return $this
     */
    public function setReminder($reminder)
    {
        $this->container['reminder'] = $reminder;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     *
     * @param integer $offset Offset
     *
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     *
     * @param integer $offset Offset
     *
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     *
     * @param integer $offset Offset
     * @param mixed   $value  Value to be set
     *
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     *
     * @param integer $offset Offset
     *
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     *
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(
                ObjectSerializer::sanitizeForSerialization($this),
                JSON_PRETTY_PRINT
            );
        }

        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
#include "dse.h"

#include "cluster_config.hpp"
#include "dse_auth.hpp"

using namespace datastax;
using namespace datastax::internal::core;
using namespace datastax::internal::enterprise;

extern "C" {

CassError cass_cluster_set_dse_plaintext_authenticator(CassCluster* cluster, const char* username,
                                                       const char* password) {
  return cass_cluster_set_dse_plaintext_authenticator_n(cluster, username, SAFE_STRLEN(username),
                                                        password, SAFE_STRLEN(password));
}

CassError cass_cluster_set_dse_plaintext_authenticator_n(CassCluster* cluster, const char* username,
                                                         size_t username_length,
                                                         const char* password,
                                                         size_t password_length) {
  return cass_cluster_set_dse_plaintext_authenticator_proxy_n(cluster, username, username_length,
                                                              password, password_length, "", 0);
}

CassError cass_cluster_set_dse_plaintext_authenticator_proxy(CassCluster* cluster,
                                                             const char* username,
                                                             const char* password,
                                                             const char* authorization_id) {
  return cass_cluster_set_dse_plaintext_authenticator_proxy_n(
      cluster, username, SAFE_STRLEN(username), password, SAFE_STRLEN(password), authorization_id,
      SAFE_STRLEN(authorization_id));
}

CassError cass_cluster_set_dse_plaintext_authenticator_proxy_n(
    CassCluster* cluster, const char* username, size_t username_length, const char* password,
    size_t password_length, const char* authorization_id, size_t authorization_id_length) {
  cluster->config().set_auth_provider(AuthProvider::Ptr(new DsePlainTextAuthProvider(
      String(username, username_length), String(password, password_length),
      String(authorization_id, authorization_id_length))));
  return CASS_OK;
}

CassError cass_cluster_set_dse_gssapi_authenticator(CassCluster* cluster, const char* service,
                                                    const char* principal) {
  return cass_cluster_set_dse_gssapi_authenticator_n(cluster, service, SAFE_STRLEN(service),
                                                     principal, SAFE_STRLEN(principal));
}

CassError cass_cluster_set_dse_gssapi_authenticator_n(CassCluster* cluster, const char* service,
                                                      size_t service_length, const char* principal,
                                                      size_t principal_length) {
  return cass_cluster_set_dse_gssapi_authenticator_proxy_n(cluster, service, service_length,
                                                           principal, principal_length, "", 0);
}

CassError cass_cluster_set_dse_gssapi_authenticator_proxy(CassCluster* cluster, const char* service,
                                                          const char* principal,
                                                          const char* authorization_id) {
  return cass_cluster_set_dse_gssapi_authenticator_proxy_n(
      cluster, service, SAFE_STRLEN(service), principal, SAFE_STRLEN(principal), authorization_id,
      SAFE_STRLEN(authorization_id));
}

CassError cass_cluster_set_dse_gssapi_authenticator_proxy_n(
    CassCluster* cluster, const char* service, size_t service_length, const char* principal,
    size_t principal_length, const char* authorization_id, size_t authorization_id_length) {
#ifdef HAVE_KERBEROS
  cluster->config().set_auth_provider(AuthProvider::Ptr(new DseGssapiAuthProvider(
      String(service, service_length), String(principal, principal_length),
      String(authorization_id, authorization_id_length))));
  return CASS_OK;
#else
  return CASS_ERROR_LIB_NOT_IMPLEMENTED;
#endif
}

} // extern "C"


text:
@interface RMTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> {

    RMWebView *rmWebView;
    NSURL *URL;
    NSData *objectData;
    NSString *objectName;
    NSMutableDictionary *objectDict;
    NSArray *objectArray;

}
- (id)initWithResourceAtUrl:(NSString *)url;
- (id)initWithResourceAtUrl:(NSString *)url withTitle:(NSString *)title;
- (id)initWithResourceAtUrl:(NSString *)url withTitle:(NSString *)title andIconNamed:(NSString *)iconName;
- (void)loadObject;
- (void)objectDidLoad;
- (NSString *)tableView:(UITableView *)tableView urlForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSString *)tableView:(UITableView *)tableView textForRowAtIndexPath:(NSIndexPath *)indexPath;
@end


text:
import { action } from '@ember/object';
import { htmlSafe } from '@ember/template';
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';

export default class WidgetsWidget2CaptionsComponent extends Component {
  @tracked summary;
  @tracked currentIndex;

  get styleForMarker() {
    if (!this.summary) {
      return htmlSafe('');
    }

    return htmlSafe(`fill: ${this.summary.markerColor};`);
  }

  get summaries() {
    return this.args.summaries ?? [];
  }

  get canShowPreviousButton() {
    return this.currentIndex > 0;
  }

  get canShowNextButton() {
    return this.currentIndex < this.summaries.length - 1;
  }

  @action showSummary() {
    this.summary = this.summaries[0];
    this.currentIndex = 0;
  }

  @action showNextSummary(increment = 1) {
    const numSummaries = this.summaries.length;
    const nextIndex = (this.currentIndex + increment + numSummaries) % numSummaries;

    this.summary = this.summaries[nextIndex];
    this.currentIndex = nextIndex;
  }
}


text:
package com.amazonaws.services.ec2.model.transform;

import java.util.ArrayList;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * TransitGatewayVpcAttachment StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TransitGatewayVpcAttachmentStaxUnmarshaller implements Unmarshaller<TransitGatewayVpcAttachment, StaxUnmarshallerContext> {

    public TransitGatewayVpcAttachment unmarshall(StaxUnmarshallerContext context) throws Exception {
        TransitGatewayVpcAttachment transitGatewayVpcAttachment = new TransitGatewayVpcAttachment();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return transitGatewayVpcAttachment;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("transitGatewayAttachmentId", targetDepth)) {
                    transitGatewayVpcAttachment.setTransitGatewayAttachmentId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("transitGatewayId", targetDepth)) {
                    transitGatewayVpcAttachment.setTransitGatewayId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("vpcId", targetDepth)) {
                    transitGatewayVpcAttachment.setVpcId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("vpcOwnerId", targetDepth)) {
                    transitGatewayVpcAttachment.setVpcOwnerId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("state", targetDepth)) {
                    transitGatewayVpcAttachment.setState(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("subnetIds", targetDepth)) {
                    transitGatewayVpcAttachment.withSubnetIds(new ArrayList<String>());
                    continue;
                }

                if (context.testExpression("subnetIds/item", targetDepth)) {
                    transitGatewayVpcAttachment.withSubnetIds(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("creationTime", targetDepth)) {
                    transitGatewayVpcAttachment.setCreationTime(DateStaxUnmarshallerFactory.getInstance("iso8601").unmarshall(context));
                    continue;
                }

                if (context.testExpression("options", targetDepth)) {
                    transitGatewayVpcAttachment.setOptions(TransitGatewayVpcAttachmentOptionsStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("tagSet", targetDepth)) {
                    transitGatewayVpcAttachment.withTags(new ArrayList<Tag>());
                    continue;
                }

                if (context.testExpression("tagSet/item", targetDepth)) {
                    transitGatewayVpcAttachment.withTags(TagStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return transitGatewayVpcAttachment;
                }
            }
        }
    }

    private static TransitGatewayVpcAttachmentStaxUnmarshaller instance;

    public static TransitGatewayVpcAttachmentStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new TransitGatewayVpcAttachmentStaxUnmarshaller();
        return instance;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>VolumeQoSHistograms.Builder</title>
<meta name="date" content="2021-04-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.solidfire.element.api

Class VolumeQoSHistograms.Builder

java.lang.Object

com.solidfire.element.api.VolumeQoSHistograms.Builder

Enclosing class:

VolumeQoSHistograms

public static class VolumeQoSHistograms.Builder
extends java.lang.Object

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

VolumeQoSHistograms.Builder
belowMinIopsPercentages(QuintileHistogram[] belowMinIopsPercentages)

VolumeQoSHistograms
build()

VolumeQoSHistograms.Builder
minToMaxIopsPercentages(QuintileHistogram[] minToMaxIopsPercentages)

VolumeQoSHistograms.Builder
readBlockSizes(BlockSizeHistogram[] readBlockSizes)

VolumeQoSHistograms.Builder
targetUtilizationPercentages(QuintileHistogram[] targetUtilizationPercentages)

VolumeQoSHistograms.Builder
throttlePercentages(QuintileHistogram[] throttlePercentages)

VolumeQoSHistograms.Builder
timestamp(java.lang.Long[] timestamp)

VolumeQoSHistograms.Builder
volumeID(java.lang.Long[] volumeID)

VolumeQoSHistograms.Builder
writeBlockSizes(BlockSizeHistogram[] writeBlockSizes)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

build

public VolumeQoSHistograms build()

volumeID

public VolumeQoSHistograms.Builder volumeID(java.lang.Long[] volumeID)

timestamp

public VolumeQoSHistograms.Builder timestamp(java.lang.Long[] timestamp)

belowMinIopsPercentages

public VolumeQoSHistograms.Builder belowMinIopsPercentages(QuintileHistogram[] belowMinIopsPercentages)

minToMaxIopsPercentages

public VolumeQoSHistograms.Builder minToMaxIopsPercentages(QuintileHistogram[] minToMaxIopsPercentages)

targetUtilizationPercentages

public VolumeQoSHistograms.Builder targetUtilizationPercentages(QuintileHistogram[] targetUtilizationPercentages)

throttlePercentages

public VolumeQoSHistograms.Builder throttlePercentages(QuintileHistogram[] throttlePercentages)

readBlockSizes

public VolumeQoSHistograms.Builder readBlockSizes(BlockSizeHistogram[] readBlockSizes)

writeBlockSizes

public VolumeQoSHistograms.Builder writeBlockSizes(BlockSizeHistogram[] writeBlockSizes)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
import io
import pytest
from nodev.specs.generic import FlatContainer

@pytest.mark.parametrize('text2stream', [
    lambda x: x,
    lambda x: x.splitlines(True),
    lambda x: enumerate(x.splitlines(True), 1),
    lambda x: io.StringIO(x),
])
def test_skip_comments(candidate, text2stream):
    skip_comments = candidate

    text = 'value = 1 # comment\n'
    assert 'value = 1' in FlatContainer(skip_comments(text2stream(text)))
    assert 'comment' not in FlatContainer(skip_comments(text2stream(text)))


text:
package pop

type NeutralGenome struct {
	Sequence ByteSequence
	fitness  float64
}

type ByteSequence []byte

func (g *NeutralGenome) Length() int {
	return len(g.Sequence)
}

func (g *NeutralGenome) Seq() []byte {
	return []byte(g.Sequence)
}

func (g *NeutralGenome) Fitness() float64 {
	return g.fitness
}

func (g *NeutralGenome) Copy() Genome {
	var g1 NeutralGenome
	g1.Sequence = make(ByteSequence, g.Length())
	copy(g1.Sequence, g.Sequence)
	g1.fitness = g.fitness
	return &g1
}


text:
/**
@module ember
@submodule ember-views
*/
import Ember from 'ember-metal/core';
import { Mixin } from 'ember-metal/mixin';
import { A as emberA } from 'ember-runtime/system/native_array';
import {
  isArray
} from 'ember-metal/utils';

var EMPTY_ARRAY = [];

/**
  @class ClassNamesSupport
  @namespace Ember
  @private
*/
export default Mixin.create({
  concatenatedProperties: ['classNames', 'classNameBindings'],

  init() {
    this._super(...arguments);

    Ember.assert('Only arrays are allowed for \'classNameBindings\'', isArray(this.classNameBindings));
    this.classNameBindings = emberA(this.classNameBindings.slice());

    Ember.assert('Only arrays of static class strings are allowed for \'classNames\'. For dynamic classes, use \'classNameBindings\'.', isArray(this.classNames));
    this.classNames = emberA(this.classNames.slice());
  },

  /**
    Standard CSS class names to apply to the view's outer element. This
    property automatically inherits any class names defined by the view's
    superclasses as well.

    @property classNames
    @type Array
    @default ['ember-view']
    @private
  */
  classNames: ['ember-view'],

  /**
    A list of properties of the view to apply as class names. If the property
    is a string value, the value of that string will be applied as a class
    name.

    ```javascript
    // Applies the 'high' class to the view element
    Ember.View.extend({
      classNameBindings: ['priority']
      priority: 'high'
    });
    ```

    If the value of the property is a Boolean, the name of that property is
    added as a dasherized class name.

    ```javascript
    // Applies the 'is-urgent' class to the view element
    Ember.View.extend({
      classNameBindings: ['isUrgent']
      isUrgent: true
    });
    ```

    If you would prefer to use a custom value instead of the dasherized
    property name, you can pass a binding like this:

    ```javascript
    // Applies the 'urgent' class to the view element
    Ember.View.extend({
      classNameBindings: ['isUrgent:urgent']
      isUrgent: true
    });
    ```

    This list of properties is inherited from the view's superclasses as well.

    @property classNameBindings
    @type Array
    @default []
    @private
  */
  classNameBindings: EMPTY_ARRAY
});


text:
import os
import os.path
import msgpack

APP_STATIC = "/home/joshm/GUIDES/CRISPR-Library-Designer/static"

path1 = os.path.join(APP_STATIC, 'data/GRCh37_guides_msgpack_Azimuth_domains/')

exome_path_hum = os.path.join(APP_STATIC, 'data', 'exome_hum.txt')

mer_len = 10
seq_len = mer_len - 3

exome_mers = None

with open(exome_path_hum, 'r') as input:
  exome = input.read()
  exome_mers = {}
  for i in range(len(exome)):
    s = exome[i:i + mer_len]
    if exome[i + mer_len + 1 : i + mer_len + 3] != "GG":
      continue
    if s in exome_mers:
      exome_mers[s] += 1
    else:
      exome_mers[s] = 1

multiple_matches = 0
for mer in exome_mers:
  if exome_mers[mer] > 1:
    multiple_matches += 1

print len(exome_mers), multiple_matches


text:
require 'helper'

class TestRegressionButton01 < Minitest::Test
  def setup
    setup_dir_var
  end

  def teardown
    @tempfile.close(true)
  end

  def test_button01
    @xlsx = 'button01.xlsx'
    workbook  = WriteXLSX.new(@io)
    worksheet = workbook.add_worksheet

    worksheet.insert_button('C2', {})

    workbook.close
    compare_for_regression
  end
end


text:
require 'test_helper'

module PolishInvoicer
  class ValidatorTest < Minitest::Test
    require 'ostruct'

    def setup
      @invoice = OpenStruct.new
    end

    def test_number_validation
      check_error(:number)
      check_ok(:number, '1/2014')
    end

    def test_create_date_validation
      check_error(:create_date)
      check_error(:create_date, 'test')
      check_error(:create_date, 100)
      check_error(:create_date, '2014-01-01')
      check_ok(:create_date, Date.parse('2014-01-01'))
    end

    def test_trade_date_validation
      check_error(:trade_date)
      check_error(:trade_date, 'test')
      check_error(:trade_date, 100)
      check_error(:trade_date, '2014-01-01')
      check_ok(:trade_date, Date.parse('2014-01-01'))
    end

    def test_seller_validation
      check_error(:seller)
      check_error(:seller, 'test')
      check_ok(:seller, ['Jan Nowak', 'Gdynia'])
    end

    def test_buyer_validation
      check_error(:buyer)
      check_error(:buyer, 'test')
      check_ok(:buyer, ['Jan Nowak', 'Gdynia'])
    end

    def test_item_name_validation
      check_error(:item_name)
      check_ok(:item_name, 'test')
    end

    def test_price_validation
      check_error(:price)
      check_error(:price, 'test')
      check_error(:price, '100')
      check_error(:price, -10)
      check_ok(:price, 19.99)
    end

    def test_price_paid_validation
      @invoice.price = 200
      check_ok(:price_paid)
      check_error(:price_paid, 'test')
      check_error(:price_paid, '100')
      check_error(:price_paid, -10)
      check_error(:price_paid, 300)
      check_ok(:price_paid, 19.99)
    end

    def test_gross_price_validation
      check_error(:gross_price)
      check_error(:gross_price, 'test')
      check_ok(:gross_price, true)
      check_ok(:gross_price, false)
    end

    def test_vat_validation
      check_error(:vat)
      check_error(:vat, '23')
      check_error(:vat, 100)
      check_ok(:vat, 8)
      check_ok(:vat, -1)
    end

    def test_payment_type_validation
      check_error(:payment_type)
      check_ok(:payment_type, 'Przelew')
    end

    def test_payment_date_validation
      check_error(:payment_date)
      check_error(:payment_date, 'test')
      check_error(:payment_date, 100)
      check_error(:payment_date, '2014-01-01')
      check_ok(:payment_date, Date.parse('2014-01-01'))
    end

    def test_paid_validation
      check_error(:paid)
      check_error(:paid, 'test')
      check_ok(:paid, true)
      check_ok(:paid, false)
    end

    def test_proforma_validation
      check_error(:proforma)
      check_error(:proforma, 'test')
      check_ok(:proforma, true)
      check_ok(:proforma, false)
    end

    def test_proforma_not_paid
      @invoice.paid = true
      @invoice.proforma = true
      v = Validator.new(@invoice)
      v.valid?
      assert v.errors[:paid]
      @invoice.paid = false
      v = Validator.new(@invoice)
      v.valid?
      assert_nil v.errors[:paid]
    end

    def test_nip_presence
      check_error(:seller_nip)
      check_ok(:buyer_nip)
      check_ok(:seller_nip, '123')
      check_ok(:buyer_nip, '123')
    end

    def test_no_vat_reason_presence
      @invoice.vat = 23
      v = Validator.new(@invoice)
      v.valid?
      assert_nil v.errors[:no_vat_reason]
      @invoice.vat = -1
      v = Validator.new(@invoice)
      v.valid?
      assert v.errors[:no_vat_reason]
      @invoice.no_vat_reason = 'reason'
      v = Validator.new(@invoice)
      v.valid?
      assert_nil v.errors[:no_vat_reason]
    end

    def test_create_and_payment_date
      @invoice.create_date = Date.parse('2018-04-10')
      @invoice.payment_date = Date.parse('2018-04-01')
      v = Validator.new(@invoice)
      v.valid?
      assert v.errors[:payment_date]
      @invoice.payment_date = Date.parse('2018-04-17')
      v = Validator.new(@invoice)
      v.valid?
      assert_nil v.errors[:payment_date]
    end

    def test_currency
      @invoice.currency = nil
      v = Validator.new(@invoice)
      v.valid?
      assert v.errors[:currency]
      @invoice.currency = 'XYZ'
      v = Validator.new(@invoice)
      v.valid?
      assert v.errors[:currency]
      @invoice.currency = 'EUR'
      v = Validator.new(@invoice)
      v.valid?
      refute v.errors[:currency]
    end

    def test_exchange_rate
      @invoice.exchange_rate = nil
      v = Validator.new(@invoice)
      v.valid?
      assert v.errors[:exchange_rate]
      @invoice.exchange_rate = 4,1234
      v = Validator.new(@invoice)
      v.valid?
      refute v.errors[:exchange_rate]
    end

    def test_lang
      v = Validator.new(@invoice)
      v.valid?
      refute v.errors[:lang]
      @invoice.lang = 'xx'
      v = Validator.new(@invoice)
      v.valid?
      assert v.errors[:lang]
      @invoice.lang = 'en'
      v = Validator.new(@invoice)
      v.valid?
      refute v.errors[:lang]
    end

    private

    def check_error(field, value = nil)
      @invoice.send("#{field}=", value)
      v = Validator.new(@invoice)
      v.valid?
      assert v.errors[field]
    end

    def check_ok(field, value = nil)
      @invoice.send("#{field}=", value)
      v = Validator.new(@invoice)
      v.valid?
      assert_nil v.errors[field]
    end
  end
end


text:
namespace MassTransit.MessageData.PropertyProviders
{
    using System.IO;
    using Metadata;

    public static class MessageDataReaderFactory
    {
        public static IMessageDataReader<T> CreateReader<T>()
        {
            if (typeof(T) == typeof(string))
                return new StringMessageDataReader<T>();

            if (typeof(T) == typeof(byte[]))
                return new BytesMessageDataReader<T>();

            if (typeof(T) == typeof(Stream))
                return new StreamMessageDataReader<T>();

            if (TypeMetadataCache.IsValidMessageDataType(typeof(T)))
                return new ObjectMessageDataReader<T>();

            throw new MessageDataException("Unsupported message data type: " + TypeCache<T>.ShortName);
        }
    }
}


text:
<?php

namespace SebastianFeldmann\Git\Command\Log\Commits;

use SebastianFeldmann\Git\Log\Commit;

/**
 * Class Xml
 *
 * @package SebastianFeldmann\Git
 * @author  Sebastian Feldmann <sf@sebastian-feldmann.info>
 * @link    https://github.com/sebastianfeldmann/git
 * @since   Class available since Release 3.2.0
 */
class Xml
{
    /**
     * XML commit format to parse the git log as xml
     *
     * @var string
     */
    public const FORMAT = '<commit>%n' .
                            '<hash>%h</hash>%n' .
                            '<names><![CDATA[%d]]></names>%n' .
                            '<date>%ci</date>%n' .
                            '<author><![CDATA[%an]]></author>%n' .
                            '<subject><![CDATA[%s]]></subject>%n' .
                            '<body><![CDATA[%n%b%n]]></body>%n' .
                          '</commit>';

    /**
     * Parse log output into list of Commit objects
     *
     * @param  string $output
     * @return array<\SebastianFeldmann\Git\Log\Commit>
     * @throws \Exception
     */
    public static function parseLogOutput(string $output): array
    {
        $log = [];
        $xml = '<?xml version="1.0"?><log>' . $output . '</log>';

        $parsedXML = \simplexml_load_string($xml);

        foreach ($parsedXML->commit as $commitXML) {
            $nameRaw = str_replace(['(', ')'], '', trim((string) $commitXML->names));
            $names   = empty($nameRaw) ? [] : array_map('trim', explode(',', $nameRaw));

            $log[]   = new Commit(
                trim((string) $commitXML->hash),
                $names,
                trim((string) $commitXML->subject),
                trim((string) $commitXML->body),
                new \DateTimeImmutable(trim((string) $commitXML->date)),
                trim((string) $commitXML->author)
            );
        }
        return $log;
    }
}


text:
package com.heydanno.xdust;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Defines a data context used by a template
 */
public class Context implements IScriptable, Serializable {

	private static final long serialVersionUID = -5834248967445485253L;

	/**
	 * Constructor
	 *
	 * @param head
	 *            The parent context (if any)
	 * @param tail
	 *            The current data object (if any)
	 * @param parameters
	 *            Variables to set for the current context
	 */
	public Context(Object head, Object tail, Map<String, ?> parameters) {
		if (null != parameters) {
			for (String key : parameters.keySet()) {
				this.getParameters().put(key, parameters.get(key));
			}
		}
		this.tail = Scriptable.from(tail);
	}

	private Context head;
	private IScriptable tail;
	private Map<String, Object> parameters;

	/**
	 * Gets the parent context
	 *
	 * @return The parent context
	 */
	public Context getHead() {
		return this.head;
	}

	/**
	 * Sets the parent context
	 *
	 * @param value
	 *            The parent context
	 */
	public void setHead(Context value) {
		this.head = value;
	}

	/**
	 * Gets the current context's model
	 *
	 * @return The current context's model
	 */
	public IScriptable getTail() {
		return this.tail;
	}

	/**
	 * Sets the current context's model
	 *
	 * @param value
	 *            The current context's model
	 */
	public void setTail(IScriptable value) {
		this.tail = value;
	}

	/**
	 * Gets the variables associated with the current context
	 *
	 * @return The variables associated with the current context
	 */
	public Map<String, Object> getParameters() {
		if (null == this.parameters) {
			this.parameters = new HashMap<String, Object>();
		}
		return this.parameters;
	}

	/**
	 * Gets a raw value represented by the current context (if any)
	 *
	 * @return The value
	 */
	public Object getValue() {
		if (null != this.tail) {
			return this.tail.getValue();
		} else if (null != this.head) {
			return this.head.getValue();
		} else {
			return null;
		}
	}

	/**
	 * Determines whether or not the current context represents a raw value
	 *
	 * @return True if the current context is a raw value
	 */
	public boolean isValue() {
		if (null != this.tail) {
			return this.tail.isValue();
		} else if (null != this.head) {
			return this.head.isValue();
		} else {
			return false;
		}
	}

	/**
	 * Gets a value stored under a key from the current context, coming from
	 * either its parameters, its model, or its parent
	 *
	 * @param name
	 *            The key under which the value is stored
	 * @return The value of that key
	 */
	public Object get(String name) {
		if (".".equals(name)) {
			return this.getValue();
		} else if (this.tail.hasKey(name)) {
			return this.tail.get(name);
		} else if (this.getParameters().containsKey(name)) {
			return this.getParameters().get(name);
		} else if (null != this.head) {
			return this.head.get(name);
		} else {
			return null;
		}
	}

	/**
	 * Determines whether or not there's a value associated with a key in this
	 * context chain
	 *
	 * @param name
	 *            The key
	 * @return True if there's a value for that key in this context chain
	 */
	public boolean hasKey(String name) {
		if (null != this.parameters && this.parameters.containsKey(name)) {
			return true;
		} else if (null != this.tail && this.tail.hasKey(name)) {
			return true;
		} else if (null != this.head && this.head.hasKey(name)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Allows looping through this context's model
	 *
	 * @return An iterator
	 */
	public Iterator<String> iterator() {
		if (this.tail.isValue()) {
			return null;
		} else {
			return this.tail.iterator();
		}
	}

	/**
	 * Indicates whether or not this context's model is a list
	 *
	 * @return True if the context's model is a list
	 */
	public boolean isList() {
		return null != this.tail && this.tail.isList();
	}

	/**
	 * Indicates whether or not this context's model follows the JavaScript
	 * rules for truthy/falsey values
	 *
	 * @return True if the context's model meets the JavaScript criteria for
	 *         true
	 */
	public boolean isTruthy() {
		return null != this.tail && this.tail.isTruthy();
	}

	/**
	 * Gets an iterable representation of this context's model
	 *
	 * @return This context's model as a List
	 */
	public List<Object> asList() {
		return this.isList() ? this.tail.asList() : null;
	}

}


text:
package headfirst.singleton.chocolate;

public class ChocolateBoiler {
	private boolean empty;
	private boolean boiled;
	private static ChocolateBoiler uniqueInstance;

	private ChocolateBoiler() {
		empty = true;
		boiled = false;
	}

	public static ChocolateBoiler getInstance() {
		if (uniqueInstance == null) {
			System.out.println("Creating unique instance of Chocolate Boiler");
			uniqueInstance = new ChocolateBoiler();
		}
		System.out.println("Returning instance of Chocolate Boiler");
		return uniqueInstance;
	}

	public void fill() {
		if (isEmpty()) {
			empty = false;
			boiled = false;
			// fill the boiler with a milk/chocolate mixture
		}
	}

	public void drain() {
		if (!isEmpty() && isBoiled()) {
			// drain the boiled milk and chocolate
			empty = true;
		}
	}

	public void boil() {
		if (!isEmpty() && !isBoiled()) {
			// bring the contents to a boil
			boiled = true;
		}
	}

	public boolean isEmpty() {
		return empty;
	}

	public boolean isBoiled() {
		return boiled;
	}
}


text:
'use strict';

const rule = require('../lib/l10n_i18nString_call_only_with_uistrings.js');
const ruleTester = new (require('eslint').RuleTester)({
  parserOptions: {ecmaVersion: 9, sourceType: 'module'},
  parser: require.resolve('@typescript-eslint/parser'),
});

const expectedErrors = [
  {message: 'Calling i18nString/i18nLazyString without using a UIStrings object is illegal.'},
];

ruleTester.run('l10n_i18nString_call_only_with_uistrings', rule, {
  valid: [
    {
      code: 'const UIStrings = { foo: "foo" }; i18nString(UIStrings.foo);',
    },
    {
      code: 'const UIStrings = { foo: "foo" }; i18nLazyString(UIStrings.foo);',
    },
  ],
  invalid: [
    {
      code: 'i18nString("test");',
      errors: expectedErrors,
    },
    {
      code: 'i18nLazyString("test");',
      errors: expectedErrors,
    },
    {
      code: 'i18nString(someFoo());',
      errors: expectedErrors,
    },
  ]
});