text:
<TITLE>Dali C++ Coding Conventions</TITLE>

General coding conventions

Type casting <input type="button" value="Hide" onclick="toggleVisibility( this, 'ccasts_details' );"/>

        Never use C-Style Casts

        The C-style cast - "(type) expr" used to convert one fundamental type to another is subject to implementation-defined effects.
        For scalar types it can result in silent truncation of the value. For pointers and references, it does not check the
        compatibility of the value with the target type.

        Don't cast away const, use mutable keyword instead

        Don't reinterpret_cast, fix the design instead

        Remember that reference cast will throw an error if cast fails

        Avoid using pointer or reference casts. They have been referred to as the goto of OO programming, fix the design instead

  X* ptr = static_cast<X*>( y_ptr ); // ok, compiler checks whether types are compatible

  (Foo*) ptr; // bad! C-cast is not guaranteed to check and never complains

Classes

    A class interface should be complete and minimal. Class should encapsulate one thing and one thing only.
    A complete interface allows clients to do anything they may reasonably want to do.
    On the other hand, a minimal interface will contain as few functions as possible.
    Class methods must be defined in the same order as they are declared. This helps navigating through code.

Compulsory member functions <input type="button" value="Hide" onclick="toggleVisibility( this, 'implicit_method_details' );"/>

        Every class must define default constructor, copy constructor, assignment operator and destructor.
        If you dont declare them, compiler will and the compiler generated versions are usually not good or safe enough.
        If your class does not support copying, then declare copy constructor and assignment operator as private and don't define them.

        If for example the assignment operator is not needed for a particular class, then it
        must be declared private and not defined. Any attempt to invoke the operator will result
        in a compile-time error. On the contrary, if the assignment operator is not declared, then
        when it is invoked, a compiler-generated form will be created and subsequently executed.
        This could lead to unexpected results. The same goes with default constructor and copy constructor.

  class X
  {
    X();                      // default constructor
    X( const X& );            // copy constructor
    X& operator=( const X& ); // copy assignment operator
    ~X();                     // destructor
  };

  class X
  {
    X();                                // default constructor
    ~X();                               // destructor
    X( const X& ) = delete;             // copy constructor not allowed
    X& operator=( const X& ); = delete; // copy assignment operator not allowed
  };

Class types <input type="button" value="Hide" onclick="toggleVisibility( this, 'class_types_details' );"/>

        Classes can have either Value semantics or Pointer semantics. Not both.
        It must be clearly documented whether a class follows value or pointer semantics and this also
        sets requirements on the class interface.

        Classes with Value semantics are passed as value types. These classes provide a copy constructor,
        a default constructor and assignment operator so that they can be copied and also stored on STL containers.

        Classes with Pointer semantics are always passed through pointers, references or smart pointers.
        These classes are ususally compound types that cannot be easily copied and thus prevent copy constructor,
        and assignment operator. They can be only stored on STL containers through smart pointers.

Access Rights <input type="button" value="Hide" onclick="toggleVisibility( this, 'access_details' );"/>

        Public and protected data should only be used in structs, not classes.
        Roughly two types of classes exist: those that essentially aggregate data and those that provide
        an abstraction while maintaining a well-defined state or invariant.

        A structure should be used to model an entity that does not require an invariant (Plain Old Data)
        A class should be used to model an entity that maintains an invariant.
        Rationale: A class is able to maintain its invariant by controlling access to its data. However,
        a class cannot control access to its members if those members non-private.
        Hence all data in a class should be private.

Constructors <input type="button" value="Hide" onclick="toggleVisibility( this, 'constructor_details' );"/>

        Virtual function calls are not allowed from constructor
        Rationale: Virtual functions are resolved statically (not dynamically) in constructor

        Member initialization order must be the same in which they are declared in the class.
        Note: Since base class members are initialized before derived class members, base class
              initializers should appear at the beginning of the member initialization list.
        Rationale: Members of a class are initialized in the order in which they are declared—not
        the order in which they appear in the initialization list.

        Constructor body should not throw an exception, keep constructor simple and trivial.
        If constructor fails, objects lifecycle never started, destructor will not be called.

        Declare all single argument constructors as explicit thus preventing their use as implicit type convertors.

  class C
  {
  public:
    explicit C( int );         // good, explicit
    C( int, int );             // ok more than one non-default argument
  };

  class C
  {
  public:
    C( double );               // bad, can be used in implicit conversion
    C( float f, int i=0 );     // bad, implicit conversion constructor
    C( int i=0, float f=0.0 ); // bad, default constructor, but also a conversion constructor
  };

Destructor <input type="button" value="Hide" onclick="toggleVisibility( this, 'destructor_details' );"/>

        All classes should define a destructor, either:

public for value types

public and virtual for base classes with virtual methods

protected and virtual for base classes to prevent deletion (and ownership) through base class

        This prevents undefined behavior. If an application attempts to delete a derived class object
        through a base class pointer, the result is undefined if the base class destructor is non-virtual.

        Virtual function calls are not allowed from inside the destructor.
        Rationale: A class's virtual functions are resolved statically (not dynamically) in its destructor

        All resources acquired by a class shall be released by the class's destructor.

        Destructor is not allowed to throw an exception, avoid doing complicated things in destructor.

Methods <input type="button" value="Hide" onclick="toggleVisibility( this, 'method_details' );"/>

        Don't shortcut, like use the returned reference of getter to assign a new value. If a Setter is missing, add it!

  initial.GetPosition() = Position(10, 10); // bad!, If GetPosition is one day changed to return copy
                                            // of Position this code silently changes to a no-op.

  initial.SetPosition( Position( 10, 10 ) );

        Code that is not used (commented out) should be deleted.
        Rationale: No dead code should be left to confuse other people.
        Exception: Code that is simply part of an explanation may appear in comments.

Inline member functions <input type="button" value="Hide" onclick="toggleVisibility( this, 'inline_details' );"/>

        GCC automatically inlines member functions defined within the class body of C++ programs even if they are not explicitly declared inline.

  class Color
  {
    inline float& GetRed()  { return mRed;   } // inline keyword not needed
    inline float& GetGreen(){ return mGreen; }
  };

  class Color
  {
    float& GetRed()   { return mRed;   }
    float& GetGreen(){ return mGreen; }
  };

        If there are a lot of inlines, they should be in a .inl file.
        Remember the inline keyword is just a hint to the compiler. Whether
        a function will be inlined or not is down to the compiler and its flags.

Conversion operators <input type="button" value="Hide" onclick="toggleVisibility( this, 'conversion_details' );"/>

        Don't declare implicit conversion operators in classes. They allow the compiler to trip you up and go from one type to another via the conversion operator unintentionally.
        Conversion operators are particularly dangerous in conjunction with auto keyword. If conversion is required, make it explicit or better yet, add a getter with a more meaningfull name.

  // Bad:
  class SmallInt
  {
  public:
    // implicit conversion to float
    operator float() const { return float( val ); }
  private:
    int val;
  };
  //... and in the program:

  int main( void )
  {
    int value;
    SmallValue foo;
    value = foo; // oops, didn't really want to allow conversion to int but the compiler can do that as float can be assigned to int.

    return 0;
  }

  // Good:
  class SmallInt
  {
  public:
    // explicit getter for float
    float AsFloat const { return static_cast<float>( val ); }
  private:
    int val;
  };
  //... and in the program:

  int main( void )
  {
    int value;
    SmallValue foo;
    si.AsFloat() + 3; // ok: explicitly request the conversion

    return 0;
  }

  // Good:
  class SmallInt
  {
  public:
    // explicit conversion to int
    explicit operator int() const { return val; }
  private:
    int val;
  };
  //... and in the program:

  int main()
  {
    SmallInt si = 3; // ok: the SmallInt constructor is not explicit
    si + 3; // error: implicit is conversion required, but operator int is explicit
    static_cast<int>(si) + 3; // ok: explicitly request the conversion

    return 0;
  }

Auto keyword <input type="button" value="Hide" onclick="toggleVisibility( this, 'auto_details' );"/>

        auto keyword should only be used where it improves the readability of the code and does not lead to ambiguities.
        never use auto in a line where multiple different types occur as part of expressions like additions, subtracts, multiplies as the conversion ordering rules are not always obvious.

  // Good:
  auto actor = Actor::DownCast(GetOwner()); // it is obvious that actor is of type Actor so no need to retype the type
  auto widthMode = widthMeasureSpec.GetMode(); // it is relatively obvious that Mode is an enumeration with potentially long name so no need to repeat the type, no ambiguity
  auto childLayout = GetChildAt( i ); // name of the variable is clear enough indication of the type, no ambiguity
  auto childPosition = childOwner.GetProperty< Dali::Vector3 >( Actor::Property::POSITION ); // getter already contains the type, no need to repeat it

  for ( auto&& renderTask : mImpl->taskList.GetTasks() ) // iterator type not relevant for the algorithm, code much cleaner with auto
  {
    renderTask->UpdateState();
  }

  // Bad:
  auto width = layout->GetWidth() - padding.end - padding.start; // not obvious what the final type ends up as multiple type conversions may occur

  auto size = std::max( LayoutLength(0), specSize - padding ); // not obvious which of the types is preferred by compiler; or what the type of specSize - padding actually is

  auto minPosition = Vector3( Vector3::ZERO ); // auto does not add any value here

  // Good:
  Vector3 minPosition; // vector initializes to 0,0,0

  // Bad:
  auto specification = MeasureSpec( GetMeasuredHeight(), MeasureSpec::Mode::EXACTLY ); // no value in typing auto in assignment, much cleaner and less ambiguous to write:

  // Good:
  MeasureSpec specification( GetMeasuredHeight(), MeasureSpec::Mode::EXACTLY ); // obvious construction of a type with parameters

Class Inheritance <input type="button" value="Hide" onclick="toggleVisibility( this, 'class_inheritance' );"/>

Overriding

        When using inheritance, any methods in the base class that can be overridden MUST be marked as virtual.
        In deriving classes, when a virtual method is overridden, then only use the override keyword.
        If a method should not be overridden further, then use the final keyword alone.

  // Good:
  class Base
  {
  public:
    virtual void Print() const;
    virtual void SetPrintSpeed( float speed );
  };

  class Derived : public Base
  {
  public:
    void Print() const override;
    void SetPrintSpeed( float speed ) final;
  };

        If a class should not be overridden then use the final keyword on the class itself.
        This should also be done for a derived class that should not to be overridden further as well.
        Overridden methods within that class can be marked as final or override.

  class Derived final : public Base
  {
  public:
    void Print() const override;
    void SetPrintSpeed( float speed ) final;
  };

Overloading

        Overloading of Base class methods SHOULD be avoided but if it's required, then use the using keyword.

  class Derived : public Base
  {
  public:
    void Print( float number ) const; // overloaded member
    using Base::Print; // Make the Base class' Print method visible here as well.
  };

        If we do not add the using line, then we can only use the overloaded Print method for a Derived object (unless we cast to the Base class).
        Attempting to use the base class' Print() method on a Derived object would result in a compilation error.

General design priciples

    Here's a few pragmatic programmer guidelines to follow (Web version)

Details <input type="button" value="Hide" onclick="toggleVisibility( this, 'general_details' );"/>

Care About the Software, Care about your API users and end users

            Why spend your life developing software unless you care about doing it well?
            Turn off the autopilot and take control. Constantly critique and appraise your work.

Don't Live with Broken Windows

            Fix bad designs, wrong decisions, and poor code when you see them.
            You can't force change on people. Instead, show them how the future might be and help them participate in creating it.

Remember the Big Picture

            Don't get so engrossed in the details that you forget to check what's happening around you.

DRY - Don't Repeat Yourself

            Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

Eliminate Effects Between Unrelated Things

            Design components that are self-contained. independent, and have a single, well-defined purpose.

There Are No Final Decisions

            No decision is cast in stone. Instead, consider each as being written in the sand at the beach, and plan for change.

Fix the Problem, Not the Blame

            It doesn't really matter whether the bug is your fault or someone else's—it is still your problem, and it still needs to be fixed.

You Can't Write Perfect Software

            Software can't be perfect. Protect your code and users from the inevitable errors.

Design with Contracts

            Use contracts to document and verify that code does no more and no less than it claims to do.

Crash Early

            A dead program normally does a lot less damage than a crippled one.

Use Assertions to Prevent the Impossible

            Assertions validate your assumptions. Use them to protect your code from an uncertain world.

Use Exceptions for Exceptional Problems

            Exceptions can suffer from all the readability and maintainability problems of classic spaghetti code. Reserve exceptions for exceptional things.

Minimize Coupling Between Modules

            Avoid coupling by writing "shy" code and applying the Law of Demeter.

Put Abstractions in Code, Details in Metadata

            Program for the general case, and put the specifics outside the compiled code base.

Always Design for Concurrency

            Allow for concurrency, and you'll design cleaner interfaces with fewer assumptions.

Don't Program by Coincidence

            Rely only on reliable things. Beware of accidental complexity, and don't confuse a happy coincidence with a purposeful plan.

Test Your Estimates

            Mathematical analysis of algorithms doesn't tell you everything. Try timing your code in its target environment.

Refactor Early, Refactor Often

            Just as you might weed and rearrange a garden, rewrite, rework, and re-architect code when it needs it. Fix the root of the problem.

Design to Test

            Start thinking about testing before you write a line of code.

Abstractions Live Longer than Details

            Invest in the abstraction, not the implementation. Abstractions can survive the barrage of changes from different implementations and new technologies.

Coding Ain't Done 'Til All the Tests Run

            'Nuff said.

Use Saboteurs to Test Your Testing

            Introduce bugs on purpose in a separate copy of the source to verify that testing will catch them.

Find Bugs Once

            Once a human tester finds a bug, it should be the last time a human tester finds that bug. Automatic tests should check for it from then on.

Sign Your Work

            Craftsmen of an earlier age were proud to sign their work. You should be, too.

Avoid Tight Coupling

      Always choose the loosest possible coupling between entities. In C++ the tightest coupling is Friend, second is Inheritance,
      then Containment and last is Usage through reference, pointer or handle.

Details <input type="button" value="Hide" onclick="toggleVisibility( this, 'coupling_details' );"/>

Friend defines a "must-know" about details of implementation, don't use it unless your happy stating that Xxx really must know about Yyy implementation. and Yyy can never change without informing Xxx.

Inheritance defines a "is-a" relationship, don't use it unless you really can naturally say Xxx is-a Yyy. Most of the cases containment through interface is what you

Containment defines a "owns-a" relationship, use it when you have a natural Xxx owns-a Yyy relationship.

      Most of the time containment through interface and normal usage is what you should go for.
      Strong ownership always beats sharing through reference counting. Reference counting means "part owns".
      You would not want to part own anything in real life, so why do that in software? sooner or later it will leak,

  Two key principles to follow:

Open Closed Principle

      Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
      That is, such an entity can allow its behaviour to be modified without altering its source code. Techniqu

Dependency Inversion Principle

      High-level modules should not depend on low-level modules. Both should depend on abstractions.
      Abstractions should not depend upon details. Details should depend upon abstractions.

Thats all folks, if you read this far you are now all equipped to write good code :) !!


text:
#include <iostream>
#include <stddef.h>
#include <new>
#include <string.h>
#include "ehm.h"

using namespace std;

namespace PeFlow {

	class CommandLineParser
	{

	public:

		static bool CreateParser(int argc, char** argv, CommandLineParser** parser);

		string GetPeDataFile();

		virtual ~CommandLineParser();

	private:

		void PrintUsage();

		CommandLineParser(void);

		bool ParseData(int argc, char** argv);

		string m_PeDataFile;

	};

}

#endif

redpajama_set_name: RedPajamaGithub


text:
var cp = Promise.promisifyAll(require('child_process'), {
	multiArgs: true
});
var fs = Promise.promisifyAll(require('fs-extra'));
var temp = Promise.promisifyAll(require('temp')).track();
var path = require('path');

var languages = {
	'.cpp': 'g++ -O2 -static -s -lm -o code [file]',
	'.pas': 'fpc -O2 -ocode [file]'
};

var verdicts = {
	'RE': 'Runtime Error',
	'SG': 'Code killed with Fatal Signal 11',
	'AC': 'Accepted',
	'WA': 'Wrong Answer'
};

/**
 * execAsync with stderr on Error
 */
function executeAsync(cmd, options) {
	options = options || {};
	return new Promise(function(resolve, reject) {
		cp.exec(cmd, options, function(err, stdout, stderr) {
			if (err && !options.ignoreExitcode) reject(new Error(stderr));
			else resolve([stdout, stderr]);
		});
	});
}

/**
 * Compiles the given code
 * @param {String} file The file to be compiled
 * @return {Promise<Buffer / Error>} The buffer of the compiled file, or an error
 *                           		 if compilation fails
 */
function Compile(file) {
	return temp.mkdirAsync('')
		.then(function(dir) {
			return executeAsync(languages[path.extname(file)].replace('[file]', file), {
				cwd: dir
			})
			.then(function() {
				return fs.readFileAsync(path.join(dir, 'code'));
			});
		});
}

/**
 * Evaluates the code on the given testcase
 * @param {Object} options The obtions Object
 *  @param {Buffer} file   The binary code file to execute
 *  @param {String} input  The input file to act as stdin
 *  @param {String} output The output file to compare with
 *  @param [String] checker The checker file to run, or `false` for diff
 *  @param {Number} timeLimit The time limit, in miliseconds
 *  @param {Number} memoryLimit The memory limit, in kilobytes
 * @return {Promise<Object>} The result object
 */
function Evaluate(options) {
	var boxdir;
	var ret = executeAsync('isolate --init --cg')
			.then(function(std) {
				// Get working folder from isolate
				var [stdout, stderr] = std;
				boxdir = path.join(stdout.replace('\n', ''), 'box');
			})
			.then(function() {
				// Copy evaluation files into isolate's folder
				return Promise.all([
					fs.writeFileAsync(path.join(boxdir, 'code'), options.code),
					fs.copyAsync(options.input, path.join(boxdir, 'input.txt'))
				]);
			})
			.then(function() {
				return Promise.all([
					fs.chmodAsync(path.join(boxdir, 'code'), '755')
				]);
			})
			.then(function() {
				// Runs the code in isolate
				return executeAsync('isolate --run --cg' +
									' -M ' + path.join(boxdir, '__meta.txt') +
									' -t ' + (options.timeLimit / 1000) +
									' -w ' + (2 * options.timeLimit / 1000) +
									' -x 1 ' +
									' -k 262144' +
									' -m ' + options.memoryLimit +
									' -i input.txt' +
									' -o output.txt' + ' code', {
										ignoreExitcode: true
									});
			})
			.then(function() {
				// Reads the meta file and get information
				return fs.readFileAsync(path.join(boxdir, '__meta.txt'), 'utf8')
					.then(function(content) {
						var opt = {};
						content.split('\n').forEach(function(line) {
							var [name, val] = line.split(':');
							opt[name] = val;
						});
						return opt;
					});
			}).then(function(opt) {
				// If the file runs ok, pass it to diff
				// Else just return information
				var ret = {
					runningTime: Number(opt.time) * 1000,
					memoryUsed: Number(opt['cg-mem'])
				};
				if (opt.status) {
					ret.signal = opt.status;
					ret.verdict = verdicts[opt.status] || opt.message;
					return ret;
				}
				// Use diff
				if (options.checker === false)
					return executeAsync('diff -wi ' + options.output + ' ' + path.join(boxdir, 'output.txt'))
						.then(function() {
							ret.signal = 'AC';
							ret.verdict = verdicts.AC;
						})
						.catch(function() {
							ret.signal = 'WA';
							ret.verdict = verdicts.WA;
						})
						.then(function() {
							return ret;
						});
				// Use checker
				else
					return executeAsync(options.checker +
										' ' + options.input +
										' ' + path.join(boxdir, 'output.txt') +
										' ' + options.output)
						.then(function(streams) {
							var [stdout, stderr] = streams;
							ret.signal = 'AC';
							ret.verdict = (stderr ? stderr.replace('\n', '') : verdicts.AC);
						}).catch(function(stderr) {
							ret.signal = 'WA';
							ret.verdict = (stderr ? stderr.replace('\n', '') : verdicts.WA);
						})
						.then(function() {
							return ret;
						});
			})
	.then(function(data) {
		return executeAsync('isolate --cleanup', { ignoreExitcode: true }).then(function() {
			return data;
		});
	});
	return ret;
}

try {
	if (!cp.execSync('isolate --init').error) {
		console.log('isolate sandbox loaded');
	}
} catch (e) {
	throw new Error('isolate not installed / configured!');
}

module.exports = {
	Compile: Compile,
	Evaluate: Evaluate
};


text:
"""
distribution.py
Author: Glen
Credit: Adam, Stack overflow

Assignment:

Write and submit a Python program (distribution.py) that computes and displays
the distribution of characters in a given sample of text.

Output of your program should look like this:

Please enter a string of text (the bigger the better): The rain in Spain stays mainly in the plain.
The distribution of characters in "The rain in Spain stays mainly in the plain." is:
iiiiii
nnnnnn
aaaaa
sss
ttt
ee
hh
ll
pp
yy
m
r

Notice about this example:

* The text: 'The rain ... plain' is provided by the user as input to your program.
* Uppercase characters are converted to lowercase
* Spaces and punctuation marks are ignored completely.
* Characters that are more common appear first in the list.
* Where the same number of characters occur, the lines are ordered alphabetically.
  For example, in the printout above, the letters e, h, l, p and y both occur twice
  in the text and they are listed in the output in alphabetical order.
* Letters that do not occur in the text are not listed in the output at all.
"""
x = 0
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

#put quotes in around words
words = str(input("Please enter a string of text (the bigger the better): "))
print('The distribution of characters in "{0}" is:'.format(words))
words = words.lower()

letters = list(words)
bears = []

for i in range (0, 26):
    bears.append(letters.count(alphabet[i]))
bears2 = list(zip(bears, alphabet))

final = sorted(bears2, key=lambda bears2: (-bears2[0], bears2[1]))

for z in range (0,26):
    print(final[z][0]*final[z][1])


text:
package fr.inra.maiage.bibliome.util.filters;

public class OrFilter<T> implements Filter<T> {
	private final Filter<T> left;
	private final Filter<T> right;

	public OrFilter(Filter<T> left, Filter<T> right) {
		super();
		this.left = left;
		this.right = right;
	}

	@Override
	public boolean accept(T x) {
		return left.accept(x) || right.accept(x);
	}
}


text:
export { TagInputDropdown } from './dropdown/index';
export { DeleteIconComponent } from './icon/index';
export { TagInputForm } from './tag-input-form/index';
export { TagRipple, TagComponent } from './tag/index';
export { TagInputComponent } from './tag-input/index';


text:
<?php
namespace Neos\Flow\Property\TypeConverter;

use Neos\Flow\Annotations as Flow;
use Neos\Error\Messages\Error;
use Neos\Flow\Http\Uri;
use Neos\Flow\Property\PropertyMappingConfigurationInterface;

/**
 * A type converter for converting URI strings to Http Uri objects.
 *
 * This converter simply creates a Neos\Flow\Http\Uri instance from the source string.
 *
 * @Flow\Scope("singleton")
 */
class UriTypeConverter extends AbstractTypeConverter
{
    /**
     * @var array<string>
     */
    protected $sourceTypes = ['string'];

    /**
     * @var string
     */
    protected $targetType = Uri::class;

    /**
     * @var integer
     */
    protected $priority = 1;

    /**
     * Converts the given string to a Uri object.
     *
     * @param string $source The URI to be converted
     * @param string $targetType
     * @param array $convertedChildProperties
     * @param PropertyMappingConfigurationInterface $configuration
     * @return Uri|Error if the input format is not supported or could not be converted for other reasons
     */
    public function convertFrom($source, $targetType, array $convertedChildProperties = [], PropertyMappingConfigurationInterface $configuration = null)
    {
        try {
            return new Uri($source);
        } catch (\InvalidArgumentException $exception) {
            return new Error('The given URI "%s" could not be converted', 1351594881, [$source]);
        }
    }
}


text:
/*!
 * Copyright (c) 2019 by Contributors
 * \file quantized_elemwise_add.cc
 * \brief
*/
#include "../tensor/elemwise_unary_op.h"
#include "./quantized_elemwise_add-inl.h"

namespace mxnet {
namespace op {

static bool ElemwiseAddShape(const nnvm::NodeAttrs& attrs,
                             mxnet::ShapeVector* in_shape,
                             mxnet::ShapeVector* out_shape) {
  // A, B, A_min, A_max, B_min, B_max
  CHECK_EQ(in_shape->size(), 6U);
  // C, C_min, C_max
  CHECK_EQ(out_shape->size(), 3U);
  CHECK_EQ((*in_shape)[0], (*in_shape)[1]);

  SHAPE_ASSIGN_CHECK(*in_shape, 2, TShape{1});
  SHAPE_ASSIGN_CHECK(*in_shape, 3, TShape{1});
  SHAPE_ASSIGN_CHECK(*in_shape, 4, TShape{1});
  SHAPE_ASSIGN_CHECK(*in_shape, 5, TShape{1});

  SHAPE_ASSIGN_CHECK(*out_shape, 0, (*in_shape)[0]);
  SHAPE_ASSIGN_CHECK(*out_shape, 1, TShape{1});
  SHAPE_ASSIGN_CHECK(*out_shape, 2, TShape{1});
  return true;
}

static bool ElemwiseAddType(const nnvm::NodeAttrs& attrs,
                            std::vector<int>* in_type,
                            std::vector<int>* out_type) {
  // A, B, A_min, A_max, B_min, B_max
  CHECK_EQ(in_type->size(), 6U);
  // C, C_min, C_max
  CHECK_EQ(out_type->size(), 3U);

  // A, B
  const int elem_add_num = 2;
  for (int i = 0; i < elem_add_num; ++i) {
    if (in_type->at(i) == mshadow::kInt8) {
      TYPE_ASSIGN_CHECK(*in_type, i, mshadow::kInt8);
    } else {
      TYPE_ASSIGN_CHECK(*in_type, i, mshadow::kUint8);
    }
  }
  // C
  int dtype = mshadow::kInt32;
  const QuantizeElemwiseAddParam& params = nnvm::get<QuantizeElemwiseAddParam>(attrs.parsed);
  if (params.max_calib_range.has_value() && params.min_calib_range.has_value()) {
    dtype = (in_type->at(0) == in_type->at(1)) ? in_type->at(0) : mshadow::kInt8;
  }
  TYPE_ASSIGN_CHECK(*out_type, 0, dtype);
  // C_min
  TYPE_ASSIGN_CHECK(*out_type, 1, mshadow::kFloat32);
  // C_max
  TYPE_ASSIGN_CHECK(*out_type, 2, mshadow::kFloat32);

  return true;
}

void QuantizedElemwiseAddForward(const nnvm::NodeAttrs& attrs,
                                 const OpContext &ctx,
                                 const std::vector<TBlob> &in_data,
                                 const std::vector<OpReqType> &req,
                                 const std::vector<TBlob> &out_data) {
  LOG(FATAL) << "Not supported for MXNet built without MKLDNN. "
                "Please install MKLDNN enabled MXNet.";
}

NNVM_REGISTER_OP(_contrib_quantized_elemwise_add)
.describe(R"code(elemwise_add operator for input dataA and input dataB data type of int8,
and accumulates in type int32 for the output. For each argument, two more arguments of type
float32 must be provided representing the thresholds of quantizing argument from data
type float32 to int8. The final outputs contain result in int32, and min
and max thresholds representing the threholds for quantizing the float32 output into int32.

.. Note::
    This operator only supports forward propogation. DO NOT use it in training.

)code")
.set_num_inputs([](const NodeAttrs& attrs) {
// A, B, A_min, A_max, B_min, B_max
  return 6;
})
// C, C_min, C_max
.set_num_outputs(3)
.set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) {
  return std::vector<std::string>{"lhs", "rhs", "lhs_min", "lhs_max", "rhs_min", "rhs_max"}; \
})
.set_attr<nnvm::FListOutputNames>("FListOutputNames", [](const NodeAttrs& attrs) {
  return std::vector<std::string>{"output", "min_output", "max_output"};
})
.set_attr<nnvm::FInferType>("FInferType", ElemwiseAddType)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseAddShape)
.set_attr<FCompute>("FCompute<cpu>", QuantizedElemwiseAddForward)
.set_attr<FNeedRequantize>("FNeedRequantize", [](const NodeAttrs& attrs) { return true; })
.add_argument("lhs", "NDArray-or-Symbol", "first input")
.add_argument("rhs", "NDArray-or-Symbol", "second input")
.add_argument("lhs_min", "NDArray-or-Symbol", "3rd input")
.add_argument("lhs_max", "NDArray-or-Symbol", "4th input")
.add_argument("rhs_min", "NDArray-or-Symbol", "5th input")
.add_argument("rhs_max", "NDArray-or-Symbol", "6th input");

// TODO(zhangrong): need extra condition check if there's benefited if it's switched on
// Since it's not compute-intensive.
#if 0
NNVM_REGISTER_OP(elemwise_add)
.set_attr<FQuantizedOp>("FQuantizedOp", [](const NodeAttrs& attrs) {
  nnvm::NodePtr node = nnvm::Node::Create();
  node->attrs.op = Op::Get("_contrib_quantized_elemwise_add");
  node->attrs.name = "quantized_" + attrs.name;
  node->attrs.dict = attrs.dict;
  if (node->op()->attr_parser != nullptr) {
    node->op()->attr_parser(&(node->attrs));
  }
  return node;
});
#endif

}  // namespace op
}  // namespace mxnet


text:
$(document).ready(function () {
  R("ready", ["app"], function (app) {
    //
    //TODO: integrate your localization logic; i.e. how the server is returning the page language?
    //
    I.setLocale("en");
    var el = document.getElementById("content");
    el.setAttribute("data-bind", "template: 'view'");
    ko.bind(app, el);
  });
});


text:
title: "Four States of Being"
author: "Alexander Wong"
cover: "/img/avatar.png"
tags: ["UDIA", "Personal"]
date: 2017-10-05T21:12:55-06:00
draft: false
---

There are only four states of being, or identity. Awareness, I (self), Dream (other), Universe (all).

## Awareness

This is the state you are born into, the state of being when you are first conscious of external stimuli. As an entity with awareness, the only requirement is one can acknowledge receiving some form of flow, or energy.

Examples: A baby crying. An insect navigating around.

## I (Self-Awareness)

This is the state in which you begin to recognize one self. Where one can look in a mirror and see one's own reflection and attribute it to their own being. Self-awareness is molded as an individual grows. In normal humans, toddlers begin development of self awareness around 1-3 years where they begin to know their own name and refer to themselves by their name. They will make clearer their own preferences, likes and dislikes, needs and wishes.

## Dream (Other)

This is the state in which you associate yourself as part of a larger whole of others. An individual who associates his or her identity with his or her peers. This is sometimes refered to as 'tribalism'. A few examples of this include citizenship (eg. "I am Canadian"), education (eg. "I am a University of Alberta alumni"), species ("I am human").

In addition, this state can take on other, more abstract forms. You identify yourself with current states of being, like "I am hot/cold". or "I am angry/sad". You can identify yourself with age, "I am old/young/444 months alive".

An entity identifies with a group, but still uses that identification as a method to separate one from another. In the trivial example, excluding cases of dual (or more) citizenship, one cannot be both Korean and Russian. One cannot be both 37 years old and 2 months old.

## Universe

This is the state in which you are at one with your environment and all of your sensory inputs. The concept of "I am (value)" no longer applies as one identifies simultaneously with all values. One is simultaneously hot and cold, angry and sad. The perception of one self is intertwined with infinite. This is commonly described as "ego death". One is merged with space, or other objects, or the universe. Loss of reality becomes so severe that it defies explanation.

The universe in which things are normally perceived ceases to exist. Satorienlightenment, or other equivalent labels.


text:
package br.gov.sintegra.ie.estados;

import br.gov.sintegra.ie.InscricaoEstadualBase;

/**
 *
 * @author kaoe
 */
public class InscricaoEstadualRR extends InscricaoEstadualBase {

    private static final Integer[] MULTIPLICADOR = {1,2,3,4,5,6,7,8};

    @Override
    public boolean validar(String numero) {
        boolean valido = false;

        if(numero.equals("isento"))
        	return true;

        String ie = limpar(numero, "[^0-9]");

        if (ie.length()==9) {
            Integer[] numeros = split(ie);
            Integer[] calculo = multiplicar(numeros, MULTIPLICADOR);
            int soma = somar(calculo);
            int digito = modulo9(soma);
            valido = numeros[8]==digito;
        }

        return valido;
    }

}


text:
<?php

namespace Oro\Bundle\CalendarBundle\Form\Type;

use Oro\Bundle\CalendarBundle\Model\Recurrence;
use Oro\Bundle\FormBundle\Form\Type\OroDateTimeType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TimezoneType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Calendar Recurrence form type
 * Used in CalendarEventApiType and CalendarEventType for adding appropriate recurrence for events
 */
class RecurrenceFormType extends AbstractType
{
    /** @var Recurrence  */
    protected $recurrenceModel;

    /**
     * RecurrenceFormType constructor.
     */
    public function __construct(Recurrence $recurrenceModel)
    {
        $this->recurrenceModel = $recurrenceModel;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'recurrenceType',
                ChoiceType::class,
                [
                    'required' => true,
                    'label' => 'oro.calendar.recurrence.entity_label',
                    'placeholder' => false,
                    'choices' => $this->recurrenceModel->getRecurrenceTypes(),
                ]
            )
            ->add(
                'interval',
                IntegerType::class,
                [
                    'required' => true,
                    'label' => 'oro.calendar.recurrence.interval.label',
                ]
            )
            ->add(
                'instance',
                ChoiceType::class,
                [
                    'required' => false,
                    'label' => 'oro.calendar.recurrence.instance.label',
                    'placeholder' => false,
                    'choices' => $this->recurrenceModel->getInstances(),
                ]
            )
            ->add(
                'dayOfWeek',
                ChoiceType::class,
                [
                    'required' => false,
                    'label' => 'oro.calendar.recurrence.day_of_week.label',
                    'multiple' => true,
                    'choices' => $this->recurrenceModel->getDaysOfWeek(),
                ]
            )
            ->add(
                'dayOfMonth',
                IntegerType::class,
                [
                    'required' => false,
                    'label' => 'oro.calendar.recurrence.day_of_month.label',
                ]
            )
            ->add(
                'monthOfYear',
                IntegerType::class,
                [
                    'required' => false,
                    'label' => 'oro.calendar.recurrence.month_of_year.label',
                ]
            )
            ->add(
                'startTime',
                OroDateTimeType::class,
                [
                    'required' => true,
                    'label' => 'oro.calendar.recurrence.start_time.label',
                    'with_seconds' => true,
                    'model_timezone' => 'UTC',
                    'widget' => 'single_text'
                ]
            )
            ->add(
                'endTime',
                OroDateTimeType::class,
                [
                    'required' => false,
                    'label' => 'oro.calendar.recurrence.end_time.label',
                    'with_seconds' => true,
                    'model_timezone' => 'UTC',
                    'widget' => 'single_text'
                ]
            )
            ->add(
                'occurrences',
                IntegerType::class,
                [
                    'required' => false,
                    'label' => 'oro.calendar.recurrence.occurrences.label',
                    'property_path' => 'occurrences',
                ]
            )
            ->add(
                'timeZone',
                TimezoneType::class,
                [
                    'required' => true,
                    'label' => 'oro.calendar.recurrence.timezone.label',
                ]
            );
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'csrf_token_id' => 'oro_calendar_event_recurrence',
                'data_class' => 'Oro\Bundle\CalendarBundle\Entity\Recurrence',
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->getBlockPrefix();
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'oro_calendar_event_recurrence';
    }
}


text:
@interface DownloadCell : UITableViewCell
@property (nonatomic, strong) IBOutlet UIImageView
*downloadImageView;

@end


text:
layout: post
status: publish
published: true
title: !binary |-
  U3VtbWlmeSByYWNoZXTDqSBwYXIgVHdlZXRlcg==
author: mick
author_login: mick
author_email: mickael@flochlay.com
wordpress_id: 1244
wordpress_url: http://morningcoffee.mickaelflochlay.com/?p=1244
date: 2012-01-20 10:44:30.000000000 +01:00
categories:
- Geek
tags:
- Summify
- Twitter
comments: []
---
Le concept est intéressant, reste à savoir si ça marche bien en pratique. Il faudra attendre un petit peu pour cela car les nouvelles inscriptions sont fermées pour le moment.

via Summary of Your Social News Feeds - Summify.


text:
"use strict";

angular
	.module( "csus" )
	.config( ["$stateProvider", function( $stateProvider ) {
		$stateProvider
			.state( 'contact', {
				url: "/contact",
				templateUrl: "js/components/contact/contact.html",
				controller: "ContactController",
				controllerAs: "vm"
			} );
	}] );


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

#include "chrome/browser/media_transfer_protocol/media_transfer_protocol_manager.h"

#include <map>
#include <queue>
#include <set>
#include <utility>

#include "base/bind.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/stl_util.h"
#include "chrome/browser/media_transfer_protocol/media_transfer_protocol_daemon_client.h"
#include "chrome/browser/media_transfer_protocol/mtp_file_entry.pb.h"
#include "chrome/browser/media_transfer_protocol/mtp_storage_info.pb.h"
#include "content/public/browser/browser_thread.h"

#if defined(OS_CHROMEOS)
#include "chromeos/dbus/dbus_thread_manager.h"
#else
#include "dbus/bus.h"
#endif

using content::BrowserThread;

namespace chrome {

namespace {

MediaTransferProtocolManager* g_media_transfer_protocol_manager = NULL;

// The MediaTransferProtocolManager implementation.
class MediaTransferProtocolManagerImpl : public MediaTransferProtocolManager {
 public:
  MediaTransferProtocolManagerImpl() : weak_ptr_factory_(this) {
    dbus::Bus* bus = NULL;
#if defined(OS_CHROMEOS)
    chromeos::DBusThreadManager* dbus_thread_manager =
        chromeos::DBusThreadManager::Get();
    bus = dbus_thread_manager->GetSystemBus();
    if (!bus)
      return;
#else
    dbus::Bus::Options options;
    options.bus_type = dbus::Bus::SYSTEM;
    options.connection_type = dbus::Bus::PRIVATE;
    options.dbus_thread_message_loop_proxy =
        BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE);
    session_bus_ = new dbus::Bus(options);
    bus = session_bus_.get();
#endif

    DCHECK(bus);
    mtp_client_.reset(
        MediaTransferProtocolDaemonClient::Create(bus, false /* not stub */));

    // Set up signals and start initializing |storage_info_map_|.
    mtp_client_->SetUpConnections(
        base::Bind(&MediaTransferProtocolManagerImpl::OnStorageChanged,
                   weak_ptr_factory_.GetWeakPtr()));
    mtp_client_->EnumerateStorage(
        base::Bind(&MediaTransferProtocolManagerImpl::OnEnumerateStorage,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&base::DoNothing));
  }

  virtual ~MediaTransferProtocolManagerImpl() {
  }

  // MediaTransferProtocolManager override.
  virtual void AddObserver(Observer* observer) OVERRIDE {
    observers_.AddObserver(observer);
  }

  // MediaTransferProtocolManager override.
  virtual void RemoveObserver(Observer* observer) OVERRIDE {
    observers_.RemoveObserver(observer);
  }

  // MediaTransferProtocolManager override.
  const std::vector<std::string> GetStorages() const OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    std::vector<std::string> storages;
    for (StorageInfoMap::const_iterator it = storage_info_map_.begin();
         it != storage_info_map_.end();
         ++it) {
      storages.push_back(it->first);
    }
    return storages;
  }

  // MediaTransferProtocolManager override.
  virtual const MtpStorageInfo* GetStorageInfo(
      const std::string& storage_name) const OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    StorageInfoMap::const_iterator it = storage_info_map_.find(storage_name);
    if (it == storage_info_map_.end())
      return NULL;
    return &it->second;
  }

  // MediaTransferProtocolManager override.
  virtual void OpenStorage(const std::string& storage_name,
                           const std::string& mode,
                           const OpenStorageCallback& callback) OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!ContainsKey(storage_info_map_, storage_name)) {
      callback.Run("", true);
      return;
    }
    open_storage_callbacks_.push(callback);
    mtp_client_->OpenStorage(
        storage_name,
        mode,
        base::Bind(&MediaTransferProtocolManagerImpl::OnOpenStorage,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&MediaTransferProtocolManagerImpl::OnOpenStorageError,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  // MediaTransferProtocolManager override.
  virtual void CloseStorage(const std::string& storage_handle,
                            const CloseStorageCallback& callback) OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!ContainsKey(handles_, storage_handle)) {
      callback.Run(true);
      return;
    }
    close_storage_callbacks_.push(std::make_pair(callback, storage_handle));
    mtp_client_->CloseStorage(
        storage_handle,
        base::Bind(&MediaTransferProtocolManagerImpl::OnCloseStorage,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&MediaTransferProtocolManagerImpl::OnCloseStorageError,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  // MediaTransferProtocolManager override.
  virtual void ReadDirectoryByPath(
      const std::string& storage_handle,
      const std::string& path,
      const ReadDirectoryCallback& callback) OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!ContainsKey(handles_, storage_handle)) {
      callback.Run(std::vector<MtpFileEntry>(), true);
      return;
    }
    read_directory_callbacks_.push(callback);
    mtp_client_->ReadDirectoryByPath(
        storage_handle,
        path,
        base::Bind(&MediaTransferProtocolManagerImpl::OnReadDirectory,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&MediaTransferProtocolManagerImpl::OnReadDirectoryError,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  // MediaTransferProtocolManager override.
  virtual void ReadDirectoryById(
      const std::string& storage_handle,
      uint32 file_id,
      const ReadDirectoryCallback& callback) OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!ContainsKey(handles_, storage_handle)) {
      callback.Run(std::vector<MtpFileEntry>(), true);
      return;
    }
    read_directory_callbacks_.push(callback);
    mtp_client_->ReadDirectoryById(
        storage_handle,
        file_id,
        base::Bind(&MediaTransferProtocolManagerImpl::OnReadDirectory,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&MediaTransferProtocolManagerImpl::OnReadDirectoryError,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  // MediaTransferProtocolManager override.
  virtual void ReadFileByPath(const std::string& storage_handle,
                              const std::string& path,
                              const ReadFileCallback& callback) OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!ContainsKey(handles_, storage_handle)) {
      callback.Run(std::string(), true);
      return;
    }
    read_file_callbacks_.push(callback);
    mtp_client_->ReadFileByPath(
        storage_handle,
        path,
        base::Bind(&MediaTransferProtocolManagerImpl::OnReadFile,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&MediaTransferProtocolManagerImpl::OnReadFileError,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  // MediaTransferProtocolManager override.
  virtual void ReadFileById(const std::string& storage_handle,
                            uint32 file_id,
                            const ReadFileCallback& callback) OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!ContainsKey(handles_, storage_handle)) {
      callback.Run(std::string(), true);
      return;
    }
    read_file_callbacks_.push(callback);
    mtp_client_->ReadFileById(
        storage_handle,
        file_id,
        base::Bind(&MediaTransferProtocolManagerImpl::OnReadFile,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&MediaTransferProtocolManagerImpl::OnReadFileError,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  virtual void GetFileInfoByPath(const std::string& storage_handle,
                                 const std::string& path,
                                 const GetFileInfoCallback& callback) OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!ContainsKey(handles_, storage_handle)) {
      callback.Run(MtpFileEntry(), true);
      return;
    }
    get_file_info_callbacks_.push(callback);
    mtp_client_->GetFileInfoByPath(
        storage_handle,
        path,
        base::Bind(&MediaTransferProtocolManagerImpl::OnGetFileInfo,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&MediaTransferProtocolManagerImpl::OnGetFileInfoError,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  virtual void GetFileInfoById(const std::string& storage_handle,
                               uint32 file_id,
                               const GetFileInfoCallback& callback) OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!ContainsKey(handles_, storage_handle)) {
      callback.Run(MtpFileEntry(), true);
      return;
    }
    get_file_info_callbacks_.push(callback);
    mtp_client_->GetFileInfoById(
        storage_handle,
        file_id,
        base::Bind(&MediaTransferProtocolManagerImpl::OnGetFileInfo,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&MediaTransferProtocolManagerImpl::OnGetFileInfoError,
                   weak_ptr_factory_.GetWeakPtr()));
  }

 private:
  // Map of storage names to storage info.
  typedef std::map<std::string, MtpStorageInfo> StorageInfoMap;
  // Callback queues - DBus communication is in-order, thus callbacks are
  // received in the same order as the requests.
  typedef std::queue<OpenStorageCallback> OpenStorageCallbackQueue;
  // (callback, handle)
  typedef std::queue<std::pair<CloseStorageCallback, std::string>
                    > CloseStorageCallbackQueue;
  typedef std::queue<ReadDirectoryCallback> ReadDirectoryCallbackQueue;
  typedef std::queue<ReadFileCallback> ReadFileCallbackQueue;
  typedef std::queue<GetFileInfoCallback> GetFileInfoCallbackQueue;

  void OnStorageChanged(bool is_attach, const std::string& storage_name) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (is_attach) {
      mtp_client_->GetStorageInfo(
          storage_name,
          base::Bind(&MediaTransferProtocolManagerImpl::OnGetStorageInfo,
                     weak_ptr_factory_.GetWeakPtr()),
          base::Bind(&base::DoNothing));
      return;
    }

    // Detach case.
    StorageInfoMap::iterator it = storage_info_map_.find(storage_name);
    if (it == storage_info_map_.end()) {
      // This might happen during initialization when |storage_info_map_| has
      // not been fully populated yet?
      return;
    }
    storage_info_map_.erase(it);
    FOR_EACH_OBSERVER(Observer,
                      observers_,
                      StorageChanged(false /* detach */, storage_name));
  }

  void OnEnumerateStorage(const std::vector<std::string>& storage_names) {
    for (size_t i = 0; i < storage_names.size(); ++i) {
      mtp_client_->GetStorageInfo(
          storage_names[i],
          base::Bind(&MediaTransferProtocolManagerImpl::OnGetStorageInfo,
                     weak_ptr_factory_.GetWeakPtr()),
          base::Bind(&base::DoNothing));
    }
  }

  void OnGetStorageInfo(const MtpStorageInfo& storage_info) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    const std::string& storage_name = storage_info.storage_name();
    if (ContainsKey(storage_info_map_, storage_name)) {
      // This should not happen, since MediaTransferProtocolManagerImpl should
      // only call EnumerateStorage() once, which populates |storage_info_map_|
      // with the already-attached devices.
      // After that, all incoming signals are either for new storage
      // attachments, which should not be in |storage_info_map_|, or for
      // storage detachements, which do not add to |storage_info_map_|.
      NOTREACHED();
      return;
    }

    // New storage. Add it and let the observers know.
    storage_info_map_.insert(std::make_pair(storage_name, storage_info));
    FOR_EACH_OBSERVER(Observer,
                      observers_,
                      StorageChanged(true /* is attach */, storage_name));
  }

  void OnOpenStorage(const std::string& handle) {
    if (!ContainsKey(handles_, handle)) {
      handles_.insert(handle);
      open_storage_callbacks_.front().Run(handle, false);
    } else {
      NOTREACHED();
      open_storage_callbacks_.front().Run("", true);
    }
    open_storage_callbacks_.pop();
  }

  void OnOpenStorageError() {
    open_storage_callbacks_.front().Run("", true);
    open_storage_callbacks_.pop();
  }

  void OnCloseStorage() {
    const std::string& handle = close_storage_callbacks_.front().second;
    if (ContainsKey(handles_, handle)) {
      handles_.erase(handle);
      close_storage_callbacks_.front().first.Run(false);
    } else {
      NOTREACHED();
      close_storage_callbacks_.front().first.Run(true);
    }
    close_storage_callbacks_.pop();
  }

  void OnCloseStorageError() {
    close_storage_callbacks_.front().first.Run(true);
    close_storage_callbacks_.pop();
  }

  void OnReadDirectory(const std::vector<MtpFileEntry>& file_entries) {
    read_directory_callbacks_.front().Run(file_entries, false);
    read_directory_callbacks_.pop();
  }

  void OnReadDirectoryError() {
    read_directory_callbacks_.front().Run(std::vector<MtpFileEntry>(), true);
    read_directory_callbacks_.pop();
  }

  void OnReadFile(const std::string& data) {
    read_file_callbacks_.front().Run(data, false);
    read_file_callbacks_.pop();
  }

  void OnReadFileError() {
    read_file_callbacks_.front().Run(std::string(), true);
    read_file_callbacks_.pop();
  }

  void OnGetFileInfo(const MtpFileEntry& entry) {
    get_file_info_callbacks_.front().Run(entry, false);
    get_file_info_callbacks_.pop();
  }

  void OnGetFileInfoError() {
    get_file_info_callbacks_.front().Run(MtpFileEntry(), true);
    get_file_info_callbacks_.pop();
  }

  // Mtpd DBus client.
  scoped_ptr<chrome::MediaTransferProtocolDaemonClient> mtp_client_;

#if !defined(OS_CHROMEOS)
  // And a D-Bus session for talking to mtpd.
  scoped_refptr<dbus::Bus> session_bus_;
#endif

  // Device attachment / detachment observers.
  ObserverList<Observer> observers_;

  base::WeakPtrFactory<MediaTransferProtocolManagerImpl> weak_ptr_factory_;

  // Everything below is only accessed on the UI thread.

  // Map to keep track of attached storages by name.
  StorageInfoMap storage_info_map_;

  // Set of open storage handles.
  std::set<std::string> handles_;

  // Queued callbacks.
  OpenStorageCallbackQueue open_storage_callbacks_;
  CloseStorageCallbackQueue close_storage_callbacks_;
  ReadDirectoryCallbackQueue read_directory_callbacks_;
  ReadFileCallbackQueue read_file_callbacks_;
  GetFileInfoCallbackQueue get_file_info_callbacks_;

  DISALLOW_COPY_AND_ASSIGN(MediaTransferProtocolManagerImpl);
};

}  // namespace

// static
void MediaTransferProtocolManager::Initialize() {
  if (g_media_transfer_protocol_manager) {
    LOG(WARNING) << "MediaTransferProtocolManager was already initialized";
    return;
  }
  g_media_transfer_protocol_manager = new MediaTransferProtocolManagerImpl();
  VLOG(1) << "MediaTransferProtocolManager initialized";
}

// static
void MediaTransferProtocolManager::Shutdown() {
  if (!g_media_transfer_protocol_manager) {
    LOG(WARNING) << "MediaTransferProtocolManager::Shutdown() called with "
                 << "NULL manager";
    return;
  }
  delete g_media_transfer_protocol_manager;
  g_media_transfer_protocol_manager = NULL;
  VLOG(1) << "MediaTransferProtocolManager Shutdown completed";
}

// static
MediaTransferProtocolManager* MediaTransferProtocolManager::GetInstance() {
  return g_media_transfer_protocol_manager;
}

}  // namespace chrome


text:
package org.apereo.portal.rest.layout;

import org.apereo.portal.portlet.marketplace.MarketplacePortletDefinition;
import org.apereo.portal.security.IPerson;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

import static org.junit.Assert.*;
import static org.mockito.MockitoAnnotations.initMocks;

/**
 * Unit tests for MarketplaceEntry.
 *
 * @since uPortal 4.2
 */
public class MarketplaceEntryTest {

    @Mock MarketplacePortletDefinition marketplacePortletDefinition;
    @Mock MarketplacePortletDefinition anotherMarketplacePortletDefinition;

    @Mock IPerson user;
    @Mock IPerson anotherUser;

    /**
     * Set up the test case.
     */
    @Before
    public void setUp() {
        initMocks(this);
    }

    /**
     * A MarketplaceEntry does not equals(null), of course.
     */
    @Test
    public void testDoesNotEqualNull() {

        final MarketplaceEntry anEntry = new MarketplaceEntry(marketplacePortletDefinition, user);

        assertFalse(anEntry.equals(null));
    }

    /**
     * MarketplaceEntries do not equal one another when their users differ.
     */
    @Test
    public void testDoesNotEqualWhenUsersDiffer() {

        final MarketplaceEntry anEntry = new MarketplaceEntry(marketplacePortletDefinition, user);

        final MarketplaceEntry sameDefinitionDifferentUser =
            new MarketplaceEntry(marketplacePortletDefinition, anotherUser);

        assertFalse(anEntry.equals(sameDefinitionDifferentUser));
    }

    /**
     * Marketplace entries do not equal one another when their backing portlet definitions differ.
     */
    @Test
    public void testDoesNotEqualWhenDefinitionsDiffer() {

        final MarketplaceEntry anEntry = new MarketplaceEntry(marketplacePortletDefinition, user);

        final MarketplaceEntry differentDefinitionSameUser =
            new MarketplaceEntry(anotherMarketplacePortletDefinition, user);

        assertFalse(anEntry.equals(differentDefinitionSameUser));

    }

    /**
     * Marketplace entries do not equal one another when their canAdd differs.
     */
    @Test
    public void testDoesNotEqualWhenCanAddDiffers() {

        final MarketplaceEntry anEntry = new MarketplaceEntry(marketplacePortletDefinition, user);

        final MarketplaceEntry sameDefinitionSameUser =
            new MarketplaceEntry(marketplacePortletDefinition, user);

        anEntry.setCanAdd(false);
        sameDefinitionSameUser.setCanAdd(true);

        assertFalse(anEntry.equals(sameDefinitionSameUser));

        anEntry.setCanAdd(true);
        sameDefinitionSameUser.setCanAdd(false);

        assertFalse(anEntry.equals(sameDefinitionSameUser));

        sameDefinitionSameUser.setCanAdd(true);
    }

    /**
     * Marketplace entries differ when their configuration as to whether to have related portlets
     * differs.
     */
    @Test
    public void testDoesNotEqualWhenHavingnessOfRelatedPortletsDiffers() {

        final MarketplaceEntry noRelatedPortlets =
            new MarketplaceEntry(marketplacePortletDefinition, false, user);
        noRelatedPortlets.setCanAdd(false);

        final MarketplaceEntry yesRelatedPortlets =
            new MarketplaceEntry(marketplacePortletDefinition, true, user);
        yesRelatedPortlets.setCanAdd(false);

        assertFalse(noRelatedPortlets.equals(yesRelatedPortlets));
    }

    /**
     * Test that Marketplace entries that have the same backing definition, the same backing user,
     * convey the same user permission to add, and have the same configuration as to whether to have
     * related portlets, are equal.
     */
    @Test
    public void testEquals() {

        final MarketplaceEntry anEntry =
            new MarketplaceEntry(marketplacePortletDefinition, true, user);

        final MarketplaceEntry equalEntry =
            new MarketplaceEntry(marketplacePortletDefinition, true, user);

        anEntry.setCanAdd(true);
        equalEntry.setCanAdd(true);

        assertEquals(anEntry, equalEntry);
        assertEquals(anEntry.hashCode(), equalEntry.hashCode());

        anEntry.setCanAdd(false);
        equalEntry.setCanAdd(false);

        assertEquals(anEntry, equalEntry);
        assertEquals(anEntry.hashCode(), equalEntry.hashCode());
    }

}


text:
// Copyright 2007-2011 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Topshelf.RecoveryConfigurators
{
	public class RestartServiceConfiguratorImpl :
		RestartServiceConfigurator
	{
		readonly RecoveryHostConfigurator _configurator;

		public RestartServiceConfiguratorImpl(RecoveryHostConfigurator configurator)
		{
			_configurator = configurator;
		}

		public FailureConfigurator OnFirstFailure()
		{
			return _configurator.OnFirstFailure();
		}

		public FailureConfigurator OnSecondFailure()
		{
			return _configurator.OnSecondFailure();
		}

		public FailureConfigurator OnSubsequentFailures()
		{
			return _configurator.OnSubsequentFailures();
		}

		public void ResetFailureCountAfter(int days)
		{
			_configurator.ResetFailureCountAfter(days);
		}

		public RestartServiceConfigurator Wait(int minutes)
		{
			_configurator.SetComputerRestartDelay(minutes);

			return this;
		}
	}
}


text:
namespace media {

class AudioBlockFifoTest : public testing::Test {
 public:
  AudioBlockFifoTest() {}
  virtual ~AudioBlockFifoTest() {}

  void PushAndVerify(AudioBlockFifo* fifo, int frames_to_push,
                     int channels, int block_frames, int max_frames) {
    const int bytes_per_sample = 2;
    const int data_byte_size = bytes_per_sample * channels * frames_to_push;
    scoped_ptr<uint8[]> data(new uint8[data_byte_size]);
    memset(data.get(), 0, data_byte_size);

    for (int filled_frames = max_frames - fifo->GetUnfilledFrames();
         filled_frames + frames_to_push <= max_frames;) {
      fifo->Push(data.get(), frames_to_push, bytes_per_sample);
      filled_frames += frames_to_push;
      EXPECT_EQ(max_frames - filled_frames, fifo->GetUnfilledFrames());
      EXPECT_EQ(static_cast<int>(filled_frames / block_frames),
                fifo->available_blocks());
    }
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(AudioBlockFifoTest);
};

// Verify that construction works as intended.
TEST_F(AudioBlockFifoTest, Construct) {
  const int channels = 6;
  const int frames = 128;
  const int blocks = 4;
  AudioBlockFifo fifo(channels, frames, blocks);
  EXPECT_EQ(0, fifo.available_blocks());
  EXPECT_EQ(frames * blocks, fifo.GetUnfilledFrames());
}

// Pushes audio bus objects to/from a FIFO up to different degrees.
TEST_F(AudioBlockFifoTest, Push) {
  const int channels = 2;
  const int frames = 128;
  const int blocks = 2;
  AudioBlockFifo fifo(channels, frames, blocks);

  // Push frames / 2 of data until FIFO is full.
  PushAndVerify(&fifo, frames / 2, channels, frames, frames * blocks);
  fifo.Clear();

  // Push frames of data until FIFO is full.
  PushAndVerify(&fifo, frames, channels, frames, frames * blocks);
  fifo.Clear();

  // Push 1.5 * frames of data.
  PushAndVerify(&fifo, frames * 1.5, channels, frames, frames * blocks);
  fifo.Clear();
}

// Perform a sequence of Push/Consume calls to different degrees, and verify
// things are correct.
TEST_F(AudioBlockFifoTest, PushAndConsume) {
  const int channels = 2;
  const int frames = 441;
  const int blocks = 4;
  AudioBlockFifo fifo(channels, frames, blocks);
  PushAndVerify(&fifo, frames, channels, frames, frames * blocks);
  EXPECT_TRUE(fifo.GetUnfilledFrames() == 0);
  EXPECT_TRUE(fifo.available_blocks() == blocks);

  // Consume 1 block of data.
  const AudioBus* bus = fifo.Consume();
  EXPECT_TRUE(channels == bus->channels());
  EXPECT_TRUE(frames == bus->frames());
  EXPECT_TRUE(fifo.available_blocks() == (blocks - 1));
  EXPECT_TRUE(fifo.GetUnfilledFrames() == frames);

  // Fill it up again.
  PushAndVerify(&fifo, frames, channels, frames, frames * blocks);
  EXPECT_TRUE(fifo.GetUnfilledFrames() == 0);
  EXPECT_TRUE(fifo.available_blocks() == blocks);

  // Consume all blocks of data.
  for (int i = 1; i <= blocks; ++i) {
    const AudioBus* bus = fifo.Consume();
    EXPECT_TRUE(channels == bus->channels());
    EXPECT_TRUE(frames == bus->frames());
    EXPECT_TRUE(fifo.GetUnfilledFrames() == frames * i);
    EXPECT_TRUE(fifo.available_blocks() == (blocks - i));
  }
  EXPECT_TRUE(fifo.GetUnfilledFrames() == frames * blocks);
  EXPECT_TRUE(fifo.available_blocks() == 0);

  fifo.Clear();
  int new_push_frames = 128;
  // Change the input frame and try to fill up the FIFO.
  PushAndVerify(&fifo, new_push_frames, channels, frames,
                frames * blocks);
  EXPECT_TRUE(fifo.GetUnfilledFrames() != 0);
  EXPECT_TRUE(fifo.available_blocks() == blocks -1);

  // Consume all the existing filled blocks of data.
  while (fifo.available_blocks()) {
    const AudioBus* bus = fifo.Consume();
    EXPECT_TRUE(channels == bus->channels());
    EXPECT_TRUE(frames == bus->frames());
  }

  // Since one block of FIFO has not been completely filled up, there should
  // be remaining frames.
  const int number_of_push =
      static_cast<int>(frames * blocks / new_push_frames);
  const int remain_frames = frames * blocks - fifo.GetUnfilledFrames();
  EXPECT_EQ(number_of_push * new_push_frames - frames * (blocks - 1),
            remain_frames);

  // Completely fill up the buffer again.
  new_push_frames = frames * blocks - remain_frames;
  PushAndVerify(&fifo, new_push_frames, channels, frames,
                frames * blocks);
  EXPECT_TRUE(fifo.GetUnfilledFrames() == 0);
  EXPECT_TRUE(fifo.available_blocks() == blocks);
}

// Perform a sequence of Push/Consume calls to a 1 block FIFO.
TEST_F(AudioBlockFifoTest, PushAndConsumeOneBlockFifo) {
  static const int channels = 2;
  static const int frames = 441;
  static const int blocks = 1;
  AudioBlockFifo fifo(channels, frames, blocks);
  PushAndVerify(&fifo, frames, channels, frames, frames * blocks);
  EXPECT_TRUE(fifo.GetUnfilledFrames() == 0);
  EXPECT_TRUE(fifo.available_blocks() == blocks);

  // Consume 1 block of data.
  const AudioBus* bus = fifo.Consume();
  EXPECT_TRUE(channels == bus->channels());
  EXPECT_TRUE(frames == bus->frames());
  EXPECT_TRUE(fifo.available_blocks() == 0);
  EXPECT_TRUE(fifo.GetUnfilledFrames() == frames);
}

}  // namespace media


text:
cd /vagrant

/usr/local/bin/composer update --prefer-source

app/console --env=test doctrine:database:drop --force -n
app/console --env=test doctrine:database:create -n
app/console --env=test doctrine:schema:create -n
app/console --env=test doctrine:fixtures:load -n

app/console doctrine:database:drop --force -n
app/console doctrine:database:create -n
app/console doctrine:schema:create -n
app/console doctrine:fixtures:load -n


text:
namespace WUManager
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using WUManager.Tools;

    public partial class FormAddHosts : Form
    {
        FormMain formMain;

        public FormAddHosts()
        {
            InitializeComponent();

            throw new Exception("Use constructor with parameter 'FormMain'");
        }

        public FormAddHosts(FormMain formMain)
        {
            InitializeComponent();
            this.formMain = formMain;
        }

        private void CmdAdd_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textHosts.Text))
            {
                DataGridViewAddRowsDelegate delegateAddRows =
                    new DataGridViewAddRowsDelegate(this.formMain.DataGridViewAddRow);

                delegateAddRows.BeginInvoke(textHosts.Lines, null, null);

                this.Close();
            }
        }

        private void TextHosts_TextChanged(object sender, EventArgs e)
        {
            lblLines.Text = string.Format("Lines: {0}", textHosts.Lines.Length);
        }

        private void BtnSearchAD_Click(object sender, EventArgs e)
        {
            string ldapADPath = txtBoxCustomLdapPath.Text;
            ADManager adMgr;

            if (DefaultLdapPatchChBox.Checked)
            {
                adMgr = new ADManager();
            }
            else
            {
                adMgr = new ADManager($"LDAP://{ldapADPath}");
            }

            try
            {
                textHosts.Text = adMgr.GetADHosts().ToString();
            }
            catch (Exception err)
            {
                lblLines.Text = err.Message;
            }
            finally
            {
                adMgr.Dispose();
            }
        }

        private void DefaultLdapPatchChBox_CheckedChanged(object sender, EventArgs e)
        {
            ADManager adMgr;
            if (DefaultLdapPatchChBox.Checked)
            {
                txtBoxCustomLdapPath.Visible = false;
            }
            else
            {
                try
                {
                    adMgr = new ADManager();

                    string ldapDefaultPath = adMgr.GetDefaultLdapPath();
                    txtBoxCustomLdapPath.Text = ldapDefaultPath;
                }
                catch { }

                txtBoxCustomLdapPath.Visible = true;
            }
        }
    }
}


text:
package ru.stqa.pft.addressbook.tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import ru.stqa.pft.addressbook.model.GroupData;
import ru.stqa.pft.addressbook.model.Groups;

import java.io.File;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Created by Admin on 7/11/2016.
 */
public class ContactDeleteFromGroupTests extends TestBase {

  private GroupData selectedGroup = null;
  private ContactData selectedContact = null;

  @BeforeMethod
  public void ensurePreconditions() {
    Contacts contacts = app.db().contacts();
    Groups groups = app.db().groups();
    if (contacts.size() == 0) {
      if (groups.size() == 0) {
        app.goTo().groupPage();
        app.group().create(new GroupData().withName("test 1"));
        groups = app.db().groups();
      }
      app.contact().create(new ContactData()
              .setFirstname("Anna").setLastname("Test").setHomePhone("111").setMobilePhone("222").setWorkPhone("333")
              .setEmail("inga.test@mail.ru").setPhoto(new File("src/test/resources/smil1.png")).inGroup(groups.iterator().next()));
      contacts = app.db().contacts();
    }

    selectedGroup = groups.iterator().next();
    System.out.println("selectedGroup: " + selectedGroup.getId() + " " + selectedGroup.getName());
    Contacts groupContacts = selectedGroup.getContacts();
    System.out.println("GroupContacts: " + groupContacts);

    for(ContactData contact : contacts){
      while (groupContacts.contains(contact)){
        selectedContact = contact;
        System.out.println("selectedContact1: " + selectedContact.getId());
        break;
      }
    }

    if (selectedContact == null) {
      selectedContact = contacts.iterator().next();
      System.out.println("selectedContact2: " + selectedContact.getId());
      app.goTo().homePage();
      app.contact().addContactToGroup(selectedContact, selectedGroup);
    }

  }

  @Test
  public void testContactDeleteFromGroup() {
    Contacts beforeGroupContacts = selectedGroup.getContacts();

    app.goTo().homePage();
    app.contact().deleteContactFromGroup(selectedContact, selectedGroup);

    Groups groups = app.db().groups();
    selectedGroup = groups.iterator().next();
    Contacts afterGroupContacts = selectedGroup.getContacts();
    System.out.println("afterGroupContacts: " + afterGroupContacts);

    assertThat(afterGroupContacts, equalTo(beforeGroupContacts.without(selectedContact)));
  }
}


text:
using System;

namespace System
{
	public static class DateTimeExtension
	{
		public static DateTime StartOfDay(this DateTime date)
		{
			return new DateTime(date.Year, date.Month, date.Day);
		}
		public static DateTime StartOfWeek(this DateTime date)
		{
			return date.AddDays((int)date.DayOfWeek);
		}
		public static DateTime StartOfMonth(this DateTime date)
		{
			return new DateTime(date.Year, date.Month, 1);
		}
		public static DateTime StartOfQuarter(this DateTime date)
		{
			return new DateTime(date.Year, ((date.Month - 1) / 3) * 3 + 1, 1);
		}
		public static DateTime StartOfYear(this DateTime date)
		{
			return new DateTime(date.Year, 1, 1);
		}
		public static DateTime AddWeeks(this DateTime date, int weeks)
		{
			return date.AddDays(weeks * 7);
		}
		public static DateTime AddQuarters(this DateTime date, int quarters)
		{
			return date.AddMonths(quarters * 3);
		}
	}
}


text:
import { TagContract } from '../Contracts'

export const elseTag: TagContract = {
  block: false,
  seekable: false,
  tagName: 'else',

  /**
   * Compiles else block node to Javascript else statement
   */
  compile(_, buffer, token) {
    buffer.writeStatement('} else {', token.filename, -1)
  },
}


text:
Datum vec_to_min_transfn(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(vec_to_min_transfn);

/**
 * Returns an of n elements,
 * which each element is the min value found in that position
 * from all input arrays.
 *
 * by Paul A. Jungwirth
 */
Datum
vec_to_min_transfn(PG_FUNCTION_ARGS)
{
  Oid elemTypeId;
  int16 elemTypeWidth;
  bool elemTypeByValue;
  char elemTypeAlignmentCode;
  int currentLength;
  MemoryContext aggContext;
  ArrayBuildState *state = NULL;
  ArrayType *currentArray;
  int arrayLength;
  Datum *currentVals;
  bool *currentNulls;
  int i;
  MemoryContext old = NULL;

  if (!AggCheckCallContext(fcinfo, &aggContext)) {
    elog(ERROR, "vec_to_min_transfn called in non-aggregate context");
  }

  // PG_ARGISNULL tests for SQL NULL,
  // but after the first pass we can have a
  // value that is non-SQL-NULL but still is C NULL.
  if (!PG_ARGISNULL(0)) {
    state = (ArrayBuildState *)PG_GETARG_POINTER(0);
  }

  if (PG_ARGISNULL(1)) {
    // just return the current state unchanged (possibly still NULL)
    PG_RETURN_POINTER(state);
  }
  currentArray = PG_GETARG_ARRAYTYPE_P(1);
  if (ARR_NDIM(currentArray) == 0) {
    PG_RETURN_POINTER(state);
  }

  if (state == NULL) {
    // Since we have our first not-null argument
    // we can initialize the state to match its type & length.
    elemTypeId = ARR_ELEMTYPE(currentArray);
    if (elemTypeId != INT2OID &&
        elemTypeId != INT4OID &&
        elemTypeId != INT8OID &&
        elemTypeId != FLOAT4OID &&
        elemTypeId != FLOAT8OID &&
        elemTypeId != NUMERICOID) {
      ereport(ERROR, (errmsg("vec_to_min input must be array of SMALLINT, INTEGER, BIGINT, REAL, DOUBLE PRECISION, or NUMERIC")));
    }
    if (ARR_NDIM(currentArray) != 1) {
      ereport(ERROR, (errmsg("One-dimensional arrays are required")));
    }
    arrayLength = (ARR_DIMS(currentArray))[0];
    // Just start with all NULLs and let the comparisons below replace them:
    state = initArrayResultWithNulls(elemTypeId, aggContext, arrayLength);
  } else {
    elemTypeId = state->element_type;
    arrayLength = state->nelems;
  }

  get_typlenbyvalalign(elemTypeId, &elemTypeWidth, &elemTypeByValue, &elemTypeAlignmentCode);
  deconstruct_array(currentArray, elemTypeId, elemTypeWidth, elemTypeByValue, elemTypeAlignmentCode,
      &currentVals, &currentNulls, &currentLength);
  if (currentLength != arrayLength) {
    ereport(ERROR, (errmsg("All arrays must be the same length, but we got %d vs %d", currentLength, arrayLength)));
  }

  if (elemTypeId == NUMERICOID) old = MemoryContextSwitchTo(aggContext);
  for (i = 0; i < arrayLength; i++) {
    if (currentNulls[i]) {
      // do nothing: nulls can't change the result.
    } else if (state->dnulls[i]) {
      state->dnulls[i] = false;
      state->dvalues[i] = datumCopy(currentVals[i], elemTypeByValue, elemTypeWidth);
    } else {
      // Moving this switch outside the for loop makes sense
      // but doesn't seem to change performance at all,
      // and it's more DRY leaving it here.
      switch (elemTypeId) {
        case INT2OID:
          if (DatumGetInt16(currentVals[i]) < DatumGetInt16(state->dvalues[i])) state->dvalues[i] = currentVals[i];
          break;
        case INT4OID:
          if (DatumGetInt32(currentVals[i]) < DatumGetInt32(state->dvalues[i])) state->dvalues[i] = currentVals[i];
          break;
        case INT8OID:
          if (DatumGetInt64(currentVals[i]) < DatumGetInt64(state->dvalues[i])) state->dvalues[i] = currentVals[i];
          break;
        case FLOAT4OID:
          if (DatumGetFloat4(currentVals[i]) < DatumGetFloat4(state->dvalues[i])) state->dvalues[i] = currentVals[i];
          break;
        case FLOAT8OID:
          if (DatumGetFloat8(currentVals[i]) < DatumGetFloat8(state->dvalues[i])) state->dvalues[i] = currentVals[i];
          break;
        case NUMERICOID:
          if (DatumGetBool(DirectFunctionCall2(numeric_lt, currentVals[i], state->dvalues[i]))) state->dvalues[i] = datumCopy(currentVals[i], elemTypeByValue, elemTypeWidth);
          break;
        default:
          elog(ERROR, "Unknown elemTypeId!");
      }
    }
  }
  if (elemTypeId == NUMERICOID) MemoryContextSwitchTo(old);
  PG_RETURN_POINTER(state);
}

Datum vec_to_min_finalfn(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(vec_to_min_finalfn);

Datum
vec_to_min_finalfn(PG_FUNCTION_ARGS)
{
  Datum result;
  ArrayBuildState *state;
  int dims[1];
  int lbs[1];

  Assert(AggCheckCallContext(fcinfo, NULL));

  state = PG_ARGISNULL(0) ? NULL : (ArrayBuildState *)PG_GETARG_POINTER(0);

  if (state == NULL)
    PG_RETURN_NULL();

  dims[0] = state->nelems;
  lbs[0] = 1;

  result = makeMdArrayResult(state, 1, dims, lbs, CurrentMemoryContext, false);
  PG_RETURN_DATUM(result);
}


text:
// Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.

package jodd.madvoc;

import jodd.madvoc.filter.BaseActionFilter;
import jodd.servlet.wrapper.BufferResponseWrapper;

import javax.servlet.http.HttpServletResponse;

public class AppendingFilter extends BaseActionFilter {

	/*
	@Override
	public Object intercept(ActionRequest actionRequest) throws Exception {
		HttpServletResponse httpResponse = actionRequest.getHttpServletResponse();

		BufferResponseWrapper wrapper = new BufferResponseWrapper(httpResponse);
		actionRequest.setHttpServletResponse(wrapper);

		Object result = actionRequest.invoke();

		char[] chars = wrapper.getBufferContentAsChars();
		chars = ArraysUtil.join(chars, "peep!".toCharArray());
		wrapper.writeContentToResponse(chars);

		actionRequest.setHttpServletResponse(httpResponse);

		return result;
	}*/

	public Object filter(ActionRequest actionRequest) throws Exception {
		HttpServletResponse httpResponse = actionRequest.getHttpServletResponse();

		BufferResponseWrapper wrapper = new BufferResponseWrapper(httpResponse);
		actionRequest.setHttpServletResponse(wrapper);

		Object result = actionRequest.invoke();

		wrapper.print("peep!");
		wrapper.writeContentToResponse();

		actionRequest.setHttpServletResponse(httpResponse);

		return result;
	}

}


text:
<?php

namespace Application\Helper;

use Zend\View\Helper\AbstractHelper;

class LeftLinks extends AbstractHelper {

    public function __invoke(array $values, $urlPrefix)
    {
        $html = '
'.PHP_EOL;
        foreach ($values as $item){
            $html .= sprintf("
%s
\n", $urlPrefix, $item, $item);
        }
        $html .= "
" . PHP_EOL;
        return $html;
    }
}


text:
const path = require('path');

process.env.CHROME_BIN = require('puppeteer').executablePath();

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: path.join(__dirname, 'coverage/app'),
      reports: ['html'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['ChromeHeadless'],
    singleRun: false,
    restartOnFileChange: true
  });
};