text:
#include "packer.h"
#include "cr_opcodes.h"

static GLboolean __handleFogData( GLenum pname, const GLfloat *params )
{
	GET_PACKER_CONTEXT(pc);
	int params_length = 0;
	int packet_length = sizeof( int ) + sizeof( pname );
	unsigned char *data_ptr;
	switch( pname )
	{
		case GL_FOG_MODE:
		case GL_FOG_DENSITY:
		case GL_FOG_START:
		case GL_FOG_END:
		case GL_FOG_INDEX:
			params_length = sizeof( *params );
			break;
		case GL_FOG_COLOR:
			params_length = 4*sizeof( *params );
			break;
		default:
			params_length = __packFogParamsLength( pname );
			if (!params_length)
			{
				char msg[100];
				sprintf(msg, "Invalid pname in Fog: %d", (int) pname );
				__PackError( __LINE__, __FILE__, GL_INVALID_ENUM, msg);
				return GL_FALSE;
			}
			break;
	}
	packet_length += params_length;

	GET_BUFFERED_POINTER(pc, packet_length );
	WRITE_DATA( 0, int, packet_length );
	WRITE_DATA( 4, GLenum, pname );
	WRITE_DATA( 8, GLfloat, params[0] );
	if (packet_length > 12)
	{
		WRITE_DATA( 12, GLfloat, params[1] );
		WRITE_DATA( 16, GLfloat, params[2] );
		WRITE_DATA( 20, GLfloat, params[3] );
	}
	return GL_TRUE;
}

void PACK_APIENTRY crPackFogfv(GLenum pname, const GLfloat *params)
{
	GET_PACKER_CONTEXT(pc);
	if (__handleFogData( pname, params ))
		WRITE_OPCODE( pc, CR_FOGFV_OPCODE );
}

void PACK_APIENTRY crPackFogiv(GLenum pname, const GLint *params)
{
	GET_PACKER_CONTEXT(pc);
	/* floats and ints are the same size, so the packing should be the same */
	if (__handleFogData( pname, (const GLfloat *) params ))
		WRITE_OPCODE( pc, CR_FOGIV_OPCODE );
}

redpajama_set_name: RedPajamaGithub


text:
@interface FileUtils : NSObject

+(BOOL)fileIsAtPath:(NSString*)path;

+(BOOL)deletefileAtPath:(NSString*)path;

+(BOOL)makeDirectory:(NSString*)path;

+(BOOL)copyItemAtPath:(NSString *)scrPath toPath:(NSString *)toPath;

+(BOOL)writDataToPath:(NSString*)path data:(NSData*)data;
@end


text:
<?php

namespace Parsec;

/**
 * A context that will catch all uncatch tokens and appends them to $_value
 */
abstract class CatchAllContext extends Context
{
    /** @var string */
    protected $value = '';

    public function __call($method, $args)
    {
        $this->value .= $args[0];
    }
}


text:
#pragma once
#include <aws/cloudsearchdomain/CloudSearchDomain_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace CloudSearchDomain
{
namespace Model
{

  /**
   *
The statistics for a field calculated in the request.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_CLOUDSEARCHDOMAIN_API FieldStats
  {
  public:
    FieldStats();
    FieldStats(Aws::Utils::Json::JsonView jsonValue);
    FieldStats& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The minimum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), min is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, min is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline const Aws::String& GetMin() const{ return m_min; }

    /**
     *
The minimum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), min is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, min is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline bool MinHasBeenSet() const { return m_minHasBeenSet; }

    /**
     *
The minimum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), min is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, min is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline void SetMin(const Aws::String& value) { m_minHasBeenSet = true; m_min = value; }

    /**
     *
The minimum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), min is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, min is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline void SetMin(Aws::String&& value) { m_minHasBeenSet = true; m_min = std::move(value); }

    /**
     *
The minimum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), min is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, min is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline void SetMin(const char* value) { m_minHasBeenSet = true; m_min.assign(value); }

    /**
     *
The minimum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), min is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, min is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline FieldStats& WithMin(const Aws::String& value) { SetMin(value); return *this;}

    /**
     *
The minimum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), min is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, min is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline FieldStats& WithMin(Aws::String&& value) { SetMin(std::move(value)); return *this;}

    /**
     *
The minimum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), min is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, min is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline FieldStats& WithMin(const char* value) { SetMin(value); return *this;}

    /**
     *
The maximum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), max is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, max is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline const Aws::String& GetMax() const{ return m_max; }

    /**
     *
The maximum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), max is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, max is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline bool MaxHasBeenSet() const { return m_maxHasBeenSet; }

    /**
     *
The maximum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), max is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, max is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline void SetMax(const Aws::String& value) { m_maxHasBeenSet = true; m_max = value; }

    /**
     *
The maximum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), max is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, max is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline void SetMax(Aws::String&& value) { m_maxHasBeenSet = true; m_max = std::move(value); }

    /**
     *
The maximum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), max is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, max is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline void SetMax(const char* value) { m_maxHasBeenSet = true; m_max.assign(value); }

    /**
     *
The maximum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), max is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, max is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline FieldStats& WithMax(const Aws::String& value) { SetMax(value); return *this;}

    /**
     *
The maximum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), max is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, max is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline FieldStats& WithMax(Aws::String&& value) { SetMax(std::move(value)); return *this;}

    /**
     *
The maximum value found in the specified field in the result set.

If
     * the field is numeric (int, int-array,
     * double, or double-array), max is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, max is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline FieldStats& WithMax(const char* value) { SetMax(value); return *this;}

    /**
     *
The number of documents that contain a value in the specified field in the
     * result set.

     */
    inline long long GetCount() const{ return m_count; }

    /**
     *
The number of documents that contain a value in the specified field in the
     * result set.

     */
    inline bool CountHasBeenSet() const { return m_countHasBeenSet; }

    /**
     *
The number of documents that contain a value in the specified field in the
     * result set.

     */
    inline void SetCount(long long value) { m_countHasBeenSet = true; m_count = value; }

    /**
     *
The number of documents that contain a value in the specified field in the
     * result set.

     */
    inline FieldStats& WithCount(long long value) { SetCount(value); return *this;}

    /**
     *
The number of documents that do not contain a value in the specified field in
     * the result set.

     */
    inline long long GetMissing() const{ return m_missing; }

    /**
     *
The number of documents that do not contain a value in the specified field in
     * the result set.

     */
    inline bool MissingHasBeenSet() const { return m_missingHasBeenSet; }

    /**
     *
The number of documents that do not contain a value in the specified field in
     * the result set.

     */
    inline void SetMissing(long long value) { m_missingHasBeenSet = true; m_missing = value; }

    /**
     *
The number of documents that do not contain a value in the specified field in
     * the result set.

     */
    inline FieldStats& WithMissing(long long value) { SetMissing(value); return *this;}

    /**
     *
The sum of the field values across the documents in the result set.
     * null for date fields.

     */
    inline double GetSum() const{ return m_sum; }

    /**
     *
The sum of the field values across the documents in the result set.
     * null for date fields.

     */
    inline bool SumHasBeenSet() const { return m_sumHasBeenSet; }

    /**
     *
The sum of the field values across the documents in the result set.
     * null for date fields.

     */
    inline void SetSum(double value) { m_sumHasBeenSet = true; m_sum = value; }

    /**
     *
The sum of the field values across the documents in the result set.
     * null for date fields.

     */
    inline FieldStats& WithSum(double value) { SetSum(value); return *this;}

    /**
     *
The sum of all field values in the result set squared.

     */
    inline double GetSumOfSquares() const{ return m_sumOfSquares; }

    /**
     *
The sum of all field values in the result set squared.

     */
    inline bool SumOfSquaresHasBeenSet() const { return m_sumOfSquaresHasBeenSet; }

    /**
     *
The sum of all field values in the result set squared.

     */
    inline void SetSumOfSquares(double value) { m_sumOfSquaresHasBeenSet = true; m_sumOfSquares = value; }

    /**
     *
The sum of all field values in the result set squared.

     */
    inline FieldStats& WithSumOfSquares(double value) { SetSumOfSquares(value); return *this;}

    /**
     *
The average of the values found in the specified field in the result set.

     *
If the field is numeric (int, int-array,
     * double, or double-array), mean is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, mean is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline const Aws::String& GetMean() const{ return m_mean; }

    /**
     *
The average of the values found in the specified field in the result set.

     *
If the field is numeric (int, int-array,
     * double, or double-array), mean is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, mean is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline bool MeanHasBeenSet() const { return m_meanHasBeenSet; }

    /**
     *
The average of the values found in the specified field in the result set.

     *
If the field is numeric (int, int-array,
     * double, or double-array), mean is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, mean is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline void SetMean(const Aws::String& value) { m_meanHasBeenSet = true; m_mean = value; }

    /**
     *
The average of the values found in the specified field in the result set.

     *
If the field is numeric (int, int-array,
     * double, or double-array), mean is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, mean is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline void SetMean(Aws::String&& value) { m_meanHasBeenSet = true; m_mean = std::move(value); }

    /**
     *
The average of the values found in the specified field in the result set.

     *
If the field is numeric (int, int-array,
     * double, or double-array), mean is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, mean is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline void SetMean(const char* value) { m_meanHasBeenSet = true; m_mean.assign(value); }

    /**
     *
The average of the values found in the specified field in the result set.

     *
If the field is numeric (int, int-array,
     * double, or double-array), mean is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, mean is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline FieldStats& WithMean(const Aws::String& value) { SetMean(value); return *this;}

    /**
     *
The average of the values found in the specified field in the result set.

     *
If the field is numeric (int, int-array,
     * double, or double-array), mean is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, mean is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline FieldStats& WithMean(Aws::String&& value) { SetMean(std::move(value)); return *this;}

    /**
     *
The average of the values found in the specified field in the result set.

     *
If the field is numeric (int, int-array,
     * double, or double-array), mean is the
     * string representation of a double-precision 64-bit floating point value. If the
     * field is date or date-array, mean is the
     * string representation of a date with the format specified in IETF RFC3339:
     * yyyy-mm-ddTHH:mm:ss.SSSZ.

     */
    inline FieldStats& WithMean(const char* value) { SetMean(value); return *this;}

    /**
     *
The standard deviation of the values in the specified field in the result
     * set.

     */
    inline double GetStddev() const{ return m_stddev; }

    /**
     *
The standard deviation of the values in the specified field in the result
     * set.

     */
    inline bool StddevHasBeenSet() const { return m_stddevHasBeenSet; }

    /**
     *
The standard deviation of the values in the specified field in the result
     * set.

     */
    inline void SetStddev(double value) { m_stddevHasBeenSet = true; m_stddev = value; }

    /**
     *
The standard deviation of the values in the specified field in the result
     * set.

     */
    inline FieldStats& WithStddev(double value) { SetStddev(value); return *this;}

  private:

    Aws::String m_min;
    bool m_minHasBeenSet = false;

    Aws::String m_max;
    bool m_maxHasBeenSet = false;

    long long m_count;
    bool m_countHasBeenSet = false;

    long long m_missing;
    bool m_missingHasBeenSet = false;

    double m_sum;
    bool m_sumHasBeenSet = false;

    double m_sumOfSquares;
    bool m_sumOfSquaresHasBeenSet = false;

    Aws::String m_mean;
    bool m_meanHasBeenSet = false;

    double m_stddev;
    bool m_stddevHasBeenSet = false;
  };

} // namespace Model
} // namespace CloudSearchDomain
} // namespace Aws


text:
namespace planet {
namespace net {

    namespace path_reg {
        extern xpv::sregex dir_num;
    }   // namespace path_reg

    namespace detail {
        // Session socket descriptor set
        class fd_table {
        public:
            typedef string_type key_type;
            typedef int mapped_type;
            typedef std::map<key_type, mapped_type> map_type;
            typedef map_type::iterator iterator;
            typedef map_type::const_iterator const_iterator;
            template<typename T1, typename T2>
            using pair = std::pair<T1, T2>;
            typedef pair<iterator, bool> return_type;

            fd_table() = default;
            optional<mapped_type> find(const key_type& k) const;
            optional<mapped_type> find_from_path(const key_type& path) const;
            void clear() noexcept;
            bool erase(key_type const& k);
            bool erase_from_path(key_type const& path);
            return_type insert(key_type const& k, mapped_type fd);
            return_type insert_from_path(key_type const& path, mapped_type fd);
        private:
            static key_type dir_number(key_type const& path);
            map_type table_;
        };
        extern fd_table fdtable;
    }   // namespace detail

    extern void get_name_info(sockaddr const *peer, int addrlen, string_type& node, string_type& serv, int flags = 0);

}   // namespace net
}   // namespace planet

#endif  // PLANET_NET_COMMON_HPP


text:
package com.facebook.buck.jvm.java;

import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeThat;

import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TemporaryPaths;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.testutil.integration.ZipInspector;
import com.facebook.buck.util.ProcessExecutor;
import com.facebook.buck.util.environment.Platform;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Path;

public class JavaBinaryIntegrationTest {

  @Rule
  public TemporaryPaths tmp = new TemporaryPaths();

  @Before
  public void checkPlatform() {
    assumeThat(Platform.detect(), not(Platform.WINDOWS));
  }

  @Test
  public void fatJarLoadingNativeLibraries() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "fat_jar", tmp);
    workspace.setUp();
    workspace.runBuckCommand("run", "//:bin-fat").assertSuccess();
  }

  @Test
  public void fatJarWithOutput() throws IOException, InterruptedException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "fat_jar", tmp);
    workspace.setUp();
    Path jar = workspace.buildAndReturnOutput("//:bin-output");
    ProcessExecutor.Result result = workspace.runJar(jar);
    assertEquals("output", result.getStdout().get().trim());
    assertEquals("error", result.getStderr().get().trim());
  }

  @Test
  public void fatJarWithExitCode() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "fat_jar", tmp);
    workspace.setUp();
    workspace.runBuckCommand("run", "//:bin-exit-code").assertSpecialExitCode("error", 5);
  }

  @Test
  public void fatJarWithVmArguments() throws IOException, InterruptedException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "fat_jar", tmp);
    workspace.setUp();
    ImmutableList<String> args = ImmutableList.of(
        "-ea",
        "-Dfoo.bar.baz=1234",
        "-Xms64m");
    String expected = Joiner.on("\n").join(args);
    Path jar = workspace.buildAndReturnOutput("//:bin-jvm-args");
    ProcessExecutor.Result result = workspace.runJar(jar, args);
    assertEquals(expected, result.getStdout().get().trim());
  }

  @Test
  public void fatJarWithAlternateJavaBin() throws IOException, InterruptedException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "fat_jar", tmp);
    workspace.setUp();
    Path jar = workspace.buildAndReturnOutput("//:bin-alternate-java");
    String javaHomeArg = "-Dbuck.fatjar.java.home=" + tmp.getRoot().toString();
    ProcessExecutor.Result result = workspace.runJar(jar, ImmutableList.of(javaHomeArg));
    assertEquals("Running java wrapper\nRunning inner jar", result.getStdout().get().trim());
  }

  @Test
  public void fatJarWithBlacklist() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "java_binary_with_blacklist", tmp);
    workspace.setUp();
    Path binaryJarWithBlacklist = workspace.buildAndReturnOutput("//:bin-blacklist");
    Path binaryJarWithoutBlacklist = workspace.buildAndReturnOutput("//:bin-no-blacklist");

    ImmutableSet<String> commonEntries = ImmutableSet.of(
        "META-INF/",
        "META-INF/MANIFEST.MF",
        "com/",
        "com/example/",
        "com/example/B.class"
    );
    ImmutableSet<String> blacklistedEntries = ImmutableSet.of(
        "com/example/A.class",
        "com/example/A$C.class",
        "com/example/Alligator.class"
    );
    assertEquals(
        "com.example.Alligator, com.example.A and any inner classes should be removed.",
        commonEntries,
        new ZipInspector(binaryJarWithBlacklist).getZipFileEntries());
    assertEquals(
        ImmutableSet.builder().addAll(commonEntries).addAll(blacklistedEntries).build(),
        new ZipInspector(binaryJarWithoutBlacklist).getZipFileEntries());
  }
}


text:
package in.zapr.druid.druidry.postAggregator;

import com.fasterxml.jackson.annotation.JsonInclude;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;

@Getter
@JsonInclude(JsonInclude.Include.NON_NULL)
@EqualsAndHashCode(callSuper = true)
public class FieldAccessPostAggregator extends DruidPostAggregator {

    private final static String FIELD_ACCESS_POST_AGGREGATOR_TYPE = "fieldAccess";

    private String fieldName;

    public FieldAccessPostAggregator(@NonNull String name, @NonNull String fieldName) {
        this.type = FIELD_ACCESS_POST_AGGREGATOR_TYPE;
        this.name = name;
        this.fieldName = fieldName;
    }

    public FieldAccessPostAggregator(@NonNull String fieldName) {
        this.type = FIELD_ACCESS_POST_AGGREGATOR_TYPE;
        this.fieldName = fieldName;
    }
}


text:
/*
 * PopupViewDelegate.h
 *
 * Created by Sajid Anwar.
 *
 * Subject to terms and conditions in LICENSE.md.
 *
 */

#import <Foundation/Foundation.h>

#import "AppDelegate.h"
#import "Utilities.h"
#import "PlaybackConstants.h"

@class AppDelegate;

@interface PopupViewDelegate : NSObject

@property (assign) IBOutlet AppDelegate *appDelegate;

@property (assign) IBOutlet NSTextField *noSongLabel;

@property (assign) IBOutlet NSImageView *artView;
@property (assign) IBOutlet NSProgressIndicator *artProgress;
@property (assign) IBOutlet NSTextField *titleLabel;
@property (assign) IBOutlet NSTextField *artistLabel;
@property (assign) IBOutlet NSTextField *albumLabel;

@property (assign) IBOutlet NSButton *repeatButton;
@property (assign) IBOutlet NSButton *backButton;
@property (assign) IBOutlet NSButton *playPauseButton;
@property (assign) IBOutlet NSButton *forwardButton;
@property (assign) IBOutlet NSButton *shuffleButton;

@property (assign) IBOutlet NSButton *thumbsupButton;
@property (assign) IBOutlet NSButton *thumbsdownButton;

@property (assign) IBOutlet NSSlider *playbackSlider;

- (void) updateSong:(NSString *)title artist:(NSString *)artist album:(NSString *)album art:(NSString *)art;
- (void) downloadAlbumArt:(NSString *)art;

- (void) shuffleChanged:(NSString *)mode;
- (void) repeatChanged:(NSString *)mode;
- (void) playbackChanged:(NSInteger)mode;
- (void) playbackTimeChanged:(NSInteger)currentTime totalTime:(NSInteger)totalTime;
- (void) ratingChanged:(NSInteger)rating;

- (IBAction) setPlaybackTime:(id)sender;

@end


text:
/* global $, pushStateTree, demoPath, navbarAdd, basePath */
(function($, pushStateTree){
  'use strict';

  var rule = pushStateTree.createRule({
    id: 'faq',
    rule: /^faq($|\/(.*))/
  });

  // Add menu option in the first load
  navbarAdd('FAQ', '/faq', 1);

  // Handler for the content of API page
  var $app;

  $(rule).on('enter', function(){
    // Lazy execute when template is ready
    // if it already have been cached, will execute at same instant
    $('#content').append($app);
  });

  $(rule).on('leave', function(){
    // if can remove, remove it when leaving
    $app.remove();
  });

  // Load template, storing the promise from jquery
  $.ajax(demoPath + 'faq.html').done(function (template){
    $app = $(template);
    if (basePath) {
      $app.find('[src]').each(function(i, element){
        var oldSrc = $(element).attr('src');
        $(element).attr('src', basePath + oldSrc);
      });
    }

    $(pushStateTree)
      .append(rule)
      .get(0).dispatch();
  });

})($, pushStateTree);


text:
package com.rockhoppertech.music.chord;

import java.util.Scanner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rockhoppertech.music.Pitch;
import com.rockhoppertech.music.midi.js.MIDINote;
import com.rockhoppertech.music.midi.js.MIDITrack;

/**
 *
 * @author Gene De Lisa
 *
 */
public class ChordVoicing {
    private static final Logger logger = LoggerFactory
            .getLogger(ChordVoicing.class);
    private int octave = 0;
    private String voicing;

    public ChordVoicing() {
        this.voicing = "1 3 5";
    }

    public ChordVoicing(int octave, String s) {
        this.octave = octave;
        this.voicing = s;
    }

    public ChordVoicing(String s) {
        this.voicing = s;
    }

    public MIDITrack getNoteList(int octave, Chord c) {
        Chord cl = (Chord) c.clone();
        int root = c.getRoot();
        int pc = root % 12;
        int n = octave * 12 + pc;
        cl.setRoot(n);
        return parse(this.voicing, cl);
    }

    public MIDITrack getTrack(Chord c) {
        Chord cl = (Chord) c.clone();
        int root = c.getRoot();
        int pc = root % 12;
        int n = this.octave * 12 + pc;
        cl.setRoot(n);
        logger.debug("new root for chord is {} ", n);
        MIDITrack nl = ChordVoicing.parse(this.voicing, cl);
        logger.debug("track chord is {}", nl);
        return nl;
    }

    public int getOctave() {
        return octave;
    }

    public void setOctave(int octave) {
        this.octave = octave;
    }

    public String getVoicing() {
        return voicing;
    }

    public void setVoicing(String voicing) {
        this.voicing = voicing;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("octave =").append(this.octave);
        sb.append(" voicing =").append(this.voicing);
        return sb.toString();
    }

    /**
     * The input voicing is something like 1 3 5 7 9 11 13. You can add a series
     * of + or - characters to jump octaves.
     *
     * <pre>
     * MIDITrack nl = ChordVoicing.parse("1 5 ++3", c);
     * </pre>
     *
     * If you give an invalid voicing it just complains. e.g. "1 3 5 7" for a
     * triad. The seventh will be ignored.
     *
     *
     * @param s
     *            a Voicing String
     * @param c
     *            a Chord instance
     * @return a MIDITrack
     * @see MIDITrack
     */
    private static MIDITrack parse(String s, Chord c) {
        int octaveOffset = 0;
        boolean repeatedRoot = false;
        boolean repeatedThird = false;
        boolean repeatedFifth = false;
        boolean repeatedSeventh = false;
        boolean repeatedNinth = false;
        boolean repeatedEleventh = false;
        boolean repeatedThirteenth = false;

        MIDITrack track = new MIDITrack();
        Scanner scanner = new Scanner(s.trim());
        while (scanner.hasNext()) {
            octaveOffset = 0;
            String d = scanner.next().trim();
            while (d.indexOf('+') != -1) {
                octaveOffset++;
                d = d.substring(1);
            }
            while (d.indexOf('-') != -1) {
                octaveOffset--;
                d = d.substring(1);
            }

            int i = Integer.parseInt(d);
            int n = 0;
            switch (i) {
            case 1:
                n = c.getRoot();
                // if the voicing is something like: 1 3 5 1 3 5 the root is
                // repeated and the oct
                // needs to be bumped up.
                if (repeatedRoot) {
                    octaveOffset++;
                    repeatedRoot = false;
                }
                addMIDINote(octaveOffset, track, n, c);
                repeatedRoot = true;
                break;
            case 3:
                n = c.getThird();
                // what about 1 3 3 5?
                // nah, would be best to make the exception for 1
                // and make the others specify the jump.
                // so, 1 3 + 3 5

                // if (repeatedThird) {
                // octaveOffset++;
                // }
                addMIDINote(octaveOffset, track, n, c);
                repeatedThird = true;
                break;
            case 5:
                n = c.getFifth();
                addMIDINote(octaveOffset, track, n, c);
                repeatedFifth = true;
                break;
            case 7:
                if (c.hasSeventh()) {
                    n = c.getSeventh();
                    addMIDINote(octaveOffset, track, n, c);
                    repeatedSeventh = true;
                } else {
                    System.err.printf("%s does not have a %d%n", c
                            .getDisplayName(), i);
                    logger.error(String.format("%s does not have a %d%n", c
                            .getDisplayName(), i));
                }
                break;
            case 9:
                if (c.hasNinth()) {
                    n = c.getNinth();
                    addMIDINote(octaveOffset, track, n, c);
                    repeatedNinth = true;
                } else {
                    System.err.printf("%s does not have a %d%n", c
                            .getDisplayName(), i);
                    logger.error(String.format("%s does not have a %d%n", c
                            .getDisplayName(), i));
                }
                break;
            case 11:
                if (c.hasEleventh()) {
                    n = c.getEleventh();
                    addMIDINote(octaveOffset, track, n, c);
                    repeatedEleventh = true;
                } else {
                    System.err.printf("%s does not have a %d%n", c
                            .getDisplayName(), i);
                    logger.error(String.format("%s does not have a %d%n", c
                            .getDisplayName(), i));
                }
                break;
            case 13:
                if (c.hasThirteenth()) {
                    n = c.getThirteenth();
                    addMIDINote(octaveOffset, track, n, c);
                    repeatedThirteenth = true;
                } else {
                    System.err.printf("%s does not have a %d%n", c
                            .getDisplayName(), i);
                    logger.error(String.format("%s does not have a %d%n", c
                            .getDisplayName(), i));
                }
                break;
                default :
                    logger.debug("Don't know {}", i);
                    break;
            }
        }
        scanner.close();

        return track;
    }

    private static void addMIDINote(int octaveOffset, MIDITrack notelist,
            int n, Chord chord) {
        logger.debug(String.format("adding note %d with offset %d%n", n,
                octaveOffset));
        if (octaveOffset > 0) {
            while (octaveOffset-- > 0) {
                n += 12;
            }
        } else if (octaveOffset < 0) {
            while (octaveOffset++ < 0) {
                n -= 12;
            }
        }
        MIDINote mn = new MIDINote(n, chord.getStartBeat(), chord.getDuration());
        if (logger.isDebugEnabled()) {
            logger.debug(String.format(
                    "pitch %d created and added midi note %s", n, mn));
        }
        notelist.add(mn);
    }

    public int getNumberOfInversions(Chord chord) {
        String[] sa = chord.getDefaultVoicingString().split("\\s");
        return sa.length;
    }

    // drop 2 is drop the second highest pitch an octave
    public static String getDropString(Chord chord, int drop) {
        StringBuilder sb = new StringBuilder();
        MIDITrack notelist = chord.createMIDITrack();
        notelist.sortByAscendingPitches();
        int size = notelist.size();
        int index = 0;
        if (drop > 0)
            index = size - drop;
        else
            index = 0;
        MIDINote n = notelist.get(index);
        logger.debug("Dropping " + n);
        if (n.getMidiNumber() >= 12) {
            n.setPitch(n.getPitch().transpose(-12));
        } else {
            logger.error("Too low to drop " + n);
        }

        for (MIDINote note : notelist) {
            if (note == n && index != 0) {
                sb.append("-");
            }
            int mn = note.getMidiNumber();
            int degree = chord.pitchToChordDegree(mn);
            logger.debug(String.format("chord %s mn %d degree %d", chord,
                    mn, degree));
            sb.append(degree).append(' ');
        }

        return sb.toString().trim();
    }

    /**
     * pretty much closed position.
     *
     * @param chord the chord
     * @param inversion the inversion
     * @return a String with the inversion
     */
    public String getInversion(Chord chord, int inversion) {
        StringBuilder sb = new StringBuilder();
        String[] sa = chord.getDefaultVoicingString().split("\\s");
        // String[] sa = this.voicing.split("\\s");
        String[] dest = new String[sa.length];

       // int croot = chord.getRoot();
        // int coct = croot / 12;
        // logger.debug(String.format("croot %d coct is %d", croot, coct));

        // rotate
        System.arraycopy(sa, inversion, dest, 0, sa.length - inversion);
        System.arraycopy(sa, 0, dest, sa.length - inversion, inversion);

        String firstPitchString = dest[0];
        if (firstPitchString.indexOf('+') != -1) {
            firstPitchString = firstPitchString.substring(firstPitchString
                    .lastIndexOf('+') + 1);
        }
        if (firstPitchString.indexOf('-') != -1) {
            firstPitchString = firstPitchString.substring(firstPitchString
                    .lastIndexOf('-') + 1);
        }
        int firstPitch = chord.getChordDegree(Integer
                .parseInt(firstPitchString));
        logger.debug(String.format("first pitch is %d", firstPitch));
        // firstPitch = croot;
        logger.debug(String.format("first pitch is %d", firstPitch));
        // int firstPitchOct = firstPitch / 12;
        logger.debug(String.format("%d is the first pitch", firstPitch));
        for (String s : dest) {
            if (s.indexOf('+') != -1) {
                s = s.substring(s.lastIndexOf('+') + 1);
            }
            if (s.indexOf('-') != -1) {
                s = s.substring(s.lastIndexOf('-') + 1);
            }
            int i = Integer.parseInt(s);
            int p = chord.getChordDegree(i);
            while (p < firstPitch && p < Pitch.MAX) {
                logger.debug(String.format("%d bumped up an octave to %d, %d",
                        p, p + 12, firstPitch));
                p += 12;
                sb.append('+');

            }
            logger.debug(String.format("%d is the pitch degree for %s", p, s));
            //
            // int nPlus = (p /12) - coct;
            // logger.debug(String.format("root oct %d nplus is %d", (p /12),
            // nPlus));

            sb.append(s).append(' ');
        }

        if (logger.isDebugEnabled()) {
            String s = String.format("inversion %d is this voicing %s",
                    inversion, sb.toString());
            logger.debug(s);
        }
        return sb.toString();
    }

    public void setInversion(Chord chord, int inversion) {
        String inv = this.getInversion(chord, inversion);
        this.octave = chord.getRoot() / 12;
        this.voicing = inv;
    }

    public static void main(String[] args) {
        Chord c = null;
        try {
            c = ChordFactory.getChordByFullSymbol("Cmaj9");
        } catch (UnknownChordException e) {
            e.printStackTrace();
            return;
        }
        c.setRoot(Pitch.C3);
        String cv = c.getChordVoicing();
        System.out.println(c);
        System.out.println(cv);
    }

    static void foo() {
        Chord c = null;
        try {
            c = ChordFactory.getChordByFullSymbol("Dm9");
        } catch (UnknownChordException e) {
            e.printStackTrace();
            return;
        }
        System.out.println(c.getIntervalstoString());
        // so you get 3 7. relative to the root.
        MIDITrack notelist = null;
        int octave = 3;
        ChordVoicing cv = null;

        cv = new ChordVoicing(octave, "1 +3 5 7 9");
        notelist = cv.getNoteList(octave, c);
        System.out.println(notelist);
        try {
            c = ChordFactory.getChordByFullSymbol("Cmaj9");
        } catch (UnknownChordException e) {
            e.printStackTrace();
        }
        cv = new ChordVoicing(octave, "1 +3 5 7 9");
        notelist = cv.getNoteList(octave, c);
        System.out.println(notelist);

        try {
            c = ChordFactory.getChordByFullSymbol("C");
        } catch (UnknownChordException e) {
            e.printStackTrace();
        }
        c.setChordVoicing("1 +3 5");
        notelist = c.createMIDITrack();
        System.out.println(notelist);
        /*
         * or this turnaround C4 Bb4 E5 G5 A5 C6 A3 G4 Cs5 F5 Bb5 D4 A4 C5 E5 A5
         * G3 F4 B4 Eb5 Af5 C4 B4 D5 E5 G5
         */

        MIDITrack prog = new MIDITrack();
        try {
            c = ChordFactory.getChordByFullSymbol("C13");
        } catch (UnknownChordException e) {
            e.printStackTrace();
        }
        c.setDuration(2);
        c.setChordVoicing("1 7 +3 5 1");
        prog.append(c.createMIDITrack());
        System.out.println(c.createMIDITrack());
        try {
            c = ChordFactory.getChordByFullSymbol("A7-9+5");
        } catch (UnknownChordException e) {
            e.printStackTrace();
        }
        c.setDuration(2);
        c.setChordVoicing("1 7 +3 5 9");
        System.out.println(c.createMIDITrack());
        prog.append(c.createMIDITrack());
        try {
            c = ChordFactory.getChordByFullSymbol("D9");
        } catch (UnknownChordException e) {
            e.printStackTrace();
        }
        c.setDuration(2);
        c.setChordVoicing("1 5 7 9 +5"); // the + 5 since
        // the 5 and the
        // 9 are in same
        // oct
        System.out.println(c.createMIDITrack());
        prog.append(c.createMIDITrack());
        try {
            c = ChordFactory.getChordByFullSymbol("g7-9+5");
        } catch (UnknownChordException e) {
            e.printStackTrace();
        }
        c.setDuration(2);
        c.setChordVoicing("1 +7 3 5 9");
        System.out.println(c.createMIDITrack());
        prog.append(c.createMIDITrack());
        try {
            c = ChordFactory.getChordByFullSymbol("Cmaj9");
        } catch (UnknownChordException e) {
            e.printStackTrace();
        }
        c.setDuration(4);
        c.setChordVoicing("1 7 9 3 5");
        System.out.println(c.createMIDITrack());
        prog.append(c.createMIDITrack());

        prog.play();

        // c.setRoot(Pitch.D3);
        // notelist = parse("1 +3 5 7 9", c);
        //
        // c.setRoot(Pitch.D3);
        // notelist = parse("1 3 5 7 9", c);
        //
        // c.setRoot(Pitch.D3);
        // notelist = parse("1 3 ++5 +7 9", c);

        // ChordVoicing cv = new ChordVoicing(Pitch.C3, new int[] { 1 });

        /*
         * capture these: D3 F4 A4 C5 E5 G3 F4 A4 B4 E5 C3 E4 G4 B4 E5
         *
         * so that's root, 3 5 7 9 root, 3 up an octave, 5 7 9 "R +3 5 7 9"
         * where + means skip an octave then the rest in order
         *
         *
         *
         *
         * for cmaj9 C3 B4 D5 E5 G5 dm9 D3 C5 E5 F5 A5 g13 G5 B4 E5 F5 A5
         *
         *
         * Key ii (tritone) V (tritone) I VI (tritone) C Dm7 (Abm7) G7 (Db7) C
         * A7alt (Eb7alt )
         */
    }

    public String getDisplayName() {
        return this.voicing.trim();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + octave;
        result = prime * result + ((voicing == null) ? 0 : voicing.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ChordVoicing other = (ChordVoicing) obj;
        if (octave != other.octave) {
            return false;
        }
        if (voicing == null) {
            if (other.voicing != null)
                return false;
        } else if (!voicing.equals(other.voicing)) {
            return false;
        }
        return true;
    }

}


text:
"""
Test for color sensor.
"""

from minibot.peripherals.colorsensor import ColorSensor

# TODO(scott): Write color sensor tests.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <TITLE>Generic Image Library: pixel_reference_is_proxy Struct Template Reference</TITLE>
    <META HTTP-EQUIV="content-type" CONTENT="text/html;charset=ISO-8859-1"/>
    <LINK TYPE="text/css" REL="stylesheet" HREF="adobe_source.css"/>

Modules
                  | Alphabetical List
                  | Class List
                  | Directories
                  | File List
                  | GIL Home Page

boost::gil::pixel_reference_is_proxy

pixel_reference_is_proxy Struct Template Reference

[Type Analysis Metafunctions]

#include <metafunctions.hpp>

Detailed Description

template<typename PixelReference>

 struct boost::gil::pixel_reference_is_proxy< PixelReference >

Determines whether the given pixel reference is a proxy class or a native C++ reference.

The documentation for this struct was generated from the following file:

metafunctions.hpp

<address style="text-align: right;">Generated on Sat May 2 13:50:18 2009 for Generic Image Library by

 1.5.6 </address>


text:
<?php

namespace Knp\Component\Pager\Event\Subscriber\Filtration;

use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface;
use Knp\Component\Pager\Event\ItemsEvent;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class PropelQuerySubscriber implements EventSubscriberInterface
{
    private ArgumentAccessInterface $argumentAccess;

    public function __construct(ArgumentAccessInterface $argumentAccess)
    {
        $this->argumentAccess = $argumentAccess;
    }

    public function items(ItemsEvent $event): void
    {
        $query = $event->target;
        if ($query instanceof \ModelCriteria) {
            if (!$this->argumentAccess->has($event->options[PaginatorInterface::FILTER_VALUE_PARAMETER_NAME])) {
                return;
            }
            if ($this->argumentAccess->has($event->options[PaginatorInterface::FILTER_FIELD_PARAMETER_NAME])) {
                $columns = $this->argumentAccess->get($event->options[PaginatorInterface::FILTER_FIELD_PARAMETER_NAME]);
            } elseif (!empty($event->options[PaginatorInterface::DEFAULT_FILTER_FIELDS])) {
                $columns = $event->options[PaginatorInterface::DEFAULT_FILTER_FIELDS];
            } else {
                return;
            }
            if (is_string($columns) && false !== strpos($columns, ',')) {
                $columns = explode(',', $columns);
            }
            $columns = (array) $columns;
            if (isset($event->options[PaginatorInterface::FILTER_FIELD_ALLOW_LIST])) {
                foreach ($columns as $column) {
                    if (!in_array($column, $event->options[PaginatorInterface::FILTER_FIELD_ALLOW_LIST])) {
                        throw new \UnexpectedValueException("Cannot filter by: [{$column}] this field is not in allow list");
                    }
                }
            }
            $value = $this->argumentAccess->get($event->options[PaginatorInterface::FILTER_VALUE_PARAMETER_NAME]);
            $criteria = \Criteria::EQUAL;
            if (false !== strpos($value, '*')) {
                $value = str_replace('*', '%', $value);
                $criteria = \Criteria::LIKE;
            }
            foreach ($columns as $column) {
                if (false !== strpos($column, '.')) {
                    $query->where($column.$criteria.'?', $value);
                } else {
                    $query->{'filterBy'.$column}($value, $criteria);
                }
            }
        }
    }

    public static function getSubscribedEvents(): array
    {
        return [
            'knp_pager.items' => ['items', 0],
        ];
    }
}


text:
{% extends "account/base.html" %}

{% load url from future %}
{% load i18n %}
{% load bootstrap_tags %}

{% block head_title %}{% trans "Change password" %}{% endblock %}

{% block body %}
    <form method="POST" action="">
        <legend>{% trans "Change password" %}</legend>
        <fieldset>
            {% csrf_token %}
            {{ form|as_bootstrap }}
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">{% trans "Save" %}</button>
            </div>
        </fieldset>
    </form>
{% endblock %}


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

<title>ControlScope (HappyBrackets API)</title>
<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 |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

net.happybrackets.core.control

Enum ControlScope

java.lang.Object

java.lang.Enum<ControlScope>

net.happybrackets.core.control.ControlScope

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<ControlScope>

public enum ControlScope
extends java.lang.Enum<ControlScope>

Define the different types of scope we want for our controls
 Although similar to the send and receive objects in Max in that the name and type
 parameter of the DynamicControl determines message interconnection,
 the ControlScope dictates how far (in
 a topological sense) the object can reach in order to communicate with other
 DynamicControl objects.  The different scopes available are:

UNIQUE - a new independent control is created and only sends messages to registered listeners

SKETCH - messages are also sent to other controls with the same name and scope belonging to other instances in the same sketch.

CLASS - messages are also sent to other controls with the same name and scope belonging to other instances of the same class.

DEVICE - messages are also sent to other controls with the same name and scope on the same device

GLOBAL - messages are also sent to other controls with the same name and scope on the entire network.

TARGET - messages are also sent to other controls with the same name and scope on specific or targeted devices on the network.

 The Default ControlScope is SKETCH, so if DynamicControlParent.setControlScope(ControlScope) or DynamicControl.setControlScope(ControlScope) is not called, controls have SKETCH
 For two Controls to match, they must have the same ControlScope, ControlType, and Name. For example:

    IntegerControl control1 = new IntegerControlSender(this, "ControlName", 0);
    control1.setControlScope(ControlScope.CLASS);

    IntegerTextControl control2 = new IntegerTextControl(this, "ControlName", 0) {
         @Override
        public void valueChanged(int control_val) {// Write your DynamicControl code below this line
            System.out.println("Read " + control_val);
            // Write your DynamicControl code above this line
        }
    };// End DynamicControl control2 code
    control2.setControlScope(ControlScope.CLASS);

    control1.setValue(2);

 The control1 and control2 will match because they both have a matching CLASS condition, the same name ("ControlName")
 and are of type ControlType.INT. The result will be that control2 will receive the value from
 control1, which will result in Read 2 being printed to standard output.

Enum Constant Summary

Enum Constants

Enum Constant and Description

CLASS

Messages are sent to all devices of the same ControlType, ControlScope and name to all instances of the same Class as the first parameter of the control constructor.

DEVICE

Messages are sent to all devices of the same ControlType, ControlScope and name on the same device.

GLOBAL

Messages are sent to all devices of the same ControlType, ControlScope and name on the entire network.

SKETCH

Messages are sent to all devices of the same ControlType, ControlScope and name to all instances of the same  Object as the first parameter of the control constructor.

TARGET

Messages are sent to registered listeners with the same scope and specific or targeted devices on the network.

UNIQUE

An independent control that only sends messages to the GUI and not to other Controls.

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static ControlScope
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static ControlScope[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

UNIQUE

public static final ControlScope UNIQUE

An independent control that only sends messages to the GUI and not to other Controls.

SKETCH

public static final ControlScope SKETCH

Messages are sent to all devices of the same ControlType, ControlScope and name to all instances of the same  Object as the first parameter of the control constructor.

     IntegerControl control1 = new IntegerControlSender(this, "ControlName", 0);
     control1.setControlScope(ControlScope.SKETCH);

     IntegerTextControl control2 = new IntegerTextControl(this, "ControlName", 0) {
         @Override
        public void valueChanged(int control_val) {// Write your DynamicControl code below this line
        System.out.println("Read " + control_val);
        // Write your DynamicControl code above this line
        }
     };// End DynamicControl control2 code
     control2.setControlScope(ControlScope.SKETCH);

     control1.setValue(2);

 The control1 and control2 will match because they both have a matching CLASS condition and have the same Object as the first parameter of the control constructor , the same name ("ControlName")
 and are of type ControlType.INT. The result will be that control2 will receive the value from
 control1, which will result in Read 2 being printed to standard output.

SKETCH is different to CLASS in that if this code was sent multiple times on identical sketches,
 control1 and control2 would only match on the same sketch.

The Object used to match SKETCH  controls can be defined as another object. For example:

     Object controlObject = hb.get("ControlObject");

     IntegerControl control1 = new IntegerControlSender(controlObject, "ControlName", 0);

     IntegerTextControl control2 = new IntegerTextControl(controlObject, "ControlName", 0) {

     control1 and control2 match because they are both using controlObject as the control reference.

CLASS

public static final ControlScope CLASS

Messages are sent to all devices of the same ControlType, ControlScope and name to all instances of the same Class as the first parameter of the control constructor.
 This is the default scope and if DynamicControlParent.setControlScope(ControlScope) or DynamicControl.setControlScope(ControlScope) is not called, controls have SKETCH

     IntegerControl control1 = new IntegerControlSender(this, "ControlName", 0);
     control1.setControlScope(ControlScope.CLASS);

     IntegerTextControl control2 = new IntegerTextControl(this, "ControlName", 0) {
         @Override
        public void valueChanged(int control_val) {// Write your DynamicControl code below this line
            System.out.println("Read " + control_val);
        // Write your DynamicControl code above this line
        }
     };// End DynamicControl control2 code
     control2.setControlScope(ControlScope.CLASS);

     control1.setValue(2);

 The control1 and control2 will match because they both have a matching CLASS condition and have the same Class as the first parameter of the control constructor , the same name ("ControlName")
 and are of type ControlType.INT. The result will be that control2 will receive the value from
 control1, which will result in Read 2 being printed to standard output.

CLASS is different to SKETCH in that if this code was sent multiple times on identical sketches,
 control1 and control2 on all the sketches would match on all sketches.

DEVICE

public static final ControlScope DEVICE

Messages are sent to all devices of the same ControlType, ControlScope and name on the same device. For example:

     IntegerControl control1 = new IntegerControlSender(this, "ControlName", 0);
     control1.setControlScope(ControlScope.DEVICE);

     IntegerTextControl control2 = new IntegerTextControl(this, "ControlName", 0) {
          @Override
        public void valueChanged(int control_val) {// Write your DynamicControl code below this line
        System.out.println("Read " + control_val);
        // Write your DynamicControl code above this line
        }
     };// End DynamicControl control2 code
     control2.setControlScope(ControlScope.DEVICE);

     control1.setValue(2);

     The value 2 will be sent to every IntegerControl or DynamicControl of ControlType.INT on this device that has the
     name "ControlName" and has DEVICE.

GLOBAL

public static final ControlScope GLOBAL

Messages are sent to all devices of the same ControlType, ControlScope and name on the entire network.

     // this is on device 1
     IntegerControl control1 = new IntegerControlSender(this, "ControlName", 0);
     control1.setControlScope(ControlScope.GLOBAL);

     control1.setValue(2);

     // this is on device 2
     IntegerTextControl control2 = new IntegerTextControl(this, "ControlName", 0) {
         @Override
        public void valueChanged(int control_val) {// Write your DynamicControl code below this line
            System.out.println("Read " + control_val);
            // Write your DynamicControl code above this line
        }
     };// End DynamicControl control2 code
     control2.setControlScope(ControlScope.GLOBAL);

     The value 2 will be sent to every IntegerControl or DynamicControl of ControlType.INT on the entire network that has the
     name "ControlName" and has GLOBAL.

TARGET

public static final ControlScope TARGET

Messages are sent to registered listeners with the same scope and specific or targeted devices on the network.
 See DynamicControlParent.setControlTarget(String...) and DynamicControlParent.setControlTarget(InetAddress...) for specific details on
 sending messages to a specific target address. Consider the following

    IntegerControl control1 = new IntegerControlSender(this, "ControlName", 0);
    control1.setControlScope(ControlScope.TARGET);
    control1.addControlTarget("HB-123456", "HB-654321");
    control1.addControlTarget( "192.168.0.2");

    IntegerTextControl control2 = new IntegerTextControl(this, "ControlName", 0) {
         @Override
        public void valueChanged(int control_val) {// Write your DynamicControl code below this line
            System.out.println("Read " + control_val);
            // Write your DynamicControl code above this line
        }
    };// End DynamicControl control2 code
    control2.setControlScope(ControlScope.TARGET);

    control1.setValue(2); // This will not be seen by control2 unless control1 has this device as one of it's targets

    // This is on device "HB-654321"
    IntegerTextControl control3 = new IntegerTextControl(this, "ControlName", 0) {
         @Override
        public void valueChanged(int control_val) {// Write your DynamicControl code below this line
            System.out.println("Read " + control_val);
            // Write your DynamicControl code above this line
        }
    };// End DynamicControl receiver code
    control3.setControlScope(ControlScope.TARGET);

 In this example, control1 will send the value of 2 to devices whose names are HB-123456 or HB-654321, or at
 address "192.168.0.2". Controls on those devices of ControlType.INT, name "ControlName"
 with TARGET will accept the message. In this case, we see that control3
 matches this (as it is on device "HB-654321") so it will print "Read 2" to the standard output;
 however, control2 will not receive the message even though it is on the same device as control1 because
 control1 did not have it's own device as a target through @link DynamicControlParent#setControlTarget(String...)}

Method Detail

values

public static ControlScope[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (ControlScope c : ControlScope.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static ControlScope valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method


text:
'use strict';

// Module to require whole directories
import requireDir from 'require-dir';

// Pulling in all tasks from the tasks folder
requireDir('./gulp/tasks', { recurse: true });


text:
@class VDLoadingAngularVariationView;

@interface VDLoadingAngularVariationView : VDLoadingView

#pragma mark Public Method

#pragma mark Properties
@property (nonatomic, assign) NSInteger minAngular;
@property (nonatomic, assign) NSInteger maxAngular;
@property (nonatomic, assign) NSInteger leapAngular;
@property (nonatomic, assign) CGFloat radius;
@property (nonatomic, assign) CGFloat torusWidth;
@property (nonatomic, strong) UIColor *angularColor;

#pragma mark Private Method
- (void)internalInitVDLoadingAngularVariationView;

@end


text:
package org.usfirst.frc3680.RecycleRush.commands;

import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc3680.RecycleRush.Robot;
import org.usfirst.frc3680.RecycleRush.RobotMap;
import org.usfirst.frc3680.RecycleRush.subsystems.ArmUpDown;
import edu.wpi.first.wpilibj.*;

public class  ArmDown extends Command {

    public ArmDown() {
        requires(Robot.armUpDown);
    }

    protected void initialize() {

    	// Checks to see if the arm is already down too far. If is, do not run.
    	if(Robot.armUpDown.downTooFar() == true){
        	// Runs when the lower limit switch is held.
    		System.out.println("ArmDown Cannot Run - Lower Limit Switch Pressed | Resetting Encoder");
            ArmUpDown.encoder1.reset();
    	}
    	else{
    		// Moves arm down.
    		System.out.println("Arm is Moving Down");
        	Robot.armUpDown.armDown();
        }
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	// Continually outputs to Riolog when ArmDown is running.
    	System.out.println("ArmDown is Running");

    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
    	// Does not allow command to run if it would break anything.
    	return Robot.armUpDown.downTooFar();
    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.armUpDown.armStop();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    	end();
    }
}


text:
// This file is derived from cache.cc in the LevelDB project:
//
//   Some portions copyright (c) 2011 The LevelDB Authors. All rights reserved.
//   Use of this source code is governed by a BSD-style license that can be
//   found in the LICENSE file.
//
// ------------------------------------------------------------
// This file implements a cache based on the MEMKIND library (http://memkind.github.io/memkind/)
// This library makes it easy to program against persistent memory hardware by exposing an API
// which parallels malloc/free, but allocates from persistent memory instead of DRAM.
//
// We use this API to implement a cache which treats persistent memory or
// non-volatile memory as if it were a larger cheaper bank of volatile memory. We
// currently make no use of its persistence properties.
//
// Currently, we only store key/value in NVM. All other data structures such as the
// ShardedLRUCache instances, hash table, etc are in DRAM. The assumption is that
// the ratio of data stored vs overhead is quite high.

#include "kudu/util/nvm_cache.h"

#include <dlfcn.h>

#include <cstdint>
#include <cstring>
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <vector>

#include <gflags/gflags.h>
#include <glog/logging.h>

#include "kudu/gutil/atomic_refcount.h"
#include "kudu/gutil/atomicops.h"
#include "kudu/gutil/bits.h"
#include "kudu/gutil/dynamic_annotations.h"
#include "kudu/gutil/hash/city.h"
#include "kudu/gutil/macros.h"
#include "kudu/gutil/port.h"
#include "kudu/gutil/ref_counted.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/gutil/sysinfo.h"
#include "kudu/util/cache.h"
#include "kudu/util/cache_metrics.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/locks.h"
#include "kudu/util/metrics.h"
#include "kudu/util/scoped_cleanup.h"
#include "kudu/util/slice.h"
#include "kudu/util/status.h"

#ifndef MEMKIND_PMEM_MIN_SIZE
#define MEMKIND_PMEM_MIN_SIZE (1024 * 1024 * 16) // Taken from memkind 1.9.0.
#endif

struct memkind;

// Useful in tests that require accurate cache capacity accounting.
DECLARE_bool(cache_force_single_shard);

DEFINE_string(nvm_cache_path, "/pmem",
              "The path at which the NVM cache will try to allocate its memory. "
              "This can be a tmpfs or ramfs for testing purposes.");

DEFINE_bool(nvm_cache_simulate_allocation_failure, false,
            "If true, the NVM cache will inject failures in calls to memkind_malloc "
            "for testing.");
TAG_FLAG(nvm_cache_simulate_allocation_failure, unsafe);

DEFINE_double(nvm_cache_usage_ratio, 1.25,
             "A ratio to set the usage of nvm cache. The charge of an item in the nvm "
             "cache is equal to the results of memkind_malloc_usable_size multiplied by "
             "the ratio.");
TAG_FLAG(nvm_cache_usage_ratio, advanced);

using std::string;
using std::unique_ptr;
using std::vector;
using strings::Substitute;

static bool ValidateNVMCacheUsageRatio(const char* flagname, double value) {
  if (value < 1.0) {
    LOG(ERROR) << Substitute("$0 must be greater than or equal to 1.0, value $1 is invalid.",
                             flagname, value);
    return false;
  }
  if (value < 1.25) {
    LOG(WARNING) << Substitute("The value of $0 is $1, it is less than recommended "
                               "value (1.25). Due to memkind fragmentation, an improper "
                               "ratio will cause allocation failures while capacity-based "
                               "evictions are not triggered. Raise --nvm_cache_usage_ratio.",
                               flagname, value);
  }
  return true;
}
DEFINE_validator(nvm_cache_usage_ratio, &ValidateNVMCacheUsageRatio);

namespace kudu {

namespace {

// Taken together, these typedefs and this macro make it easy to call a
// memkind function:
//
//  CALL_MEMKIND(memkind_malloc, vmp_, size);
typedef int (*memkind_create_pmem)(const char*, size_t, memkind**);
typedef int (*memkind_destroy_kind)(memkind*);
typedef void* (*memkind_malloc)(memkind*, size_t);
typedef size_t (*memkind_malloc_usable_size)(memkind*, void*);
typedef void (*memkind_free)(memkind*, void*);
#define CALL_MEMKIND(func_name, ...) ((func_name)g_##func_name)(__VA_ARGS__)

// Function pointers into memkind; set by InitMemkindOps().
void* g_memkind_create_pmem;
void* g_memkind_destroy_kind;
void* g_memkind_malloc;
void* g_memkind_malloc_usable_size;
void* g_memkind_free;

// After InitMemkindOps() is called, true if memkind is available and safe
// to use, false otherwise.
bool g_memkind_available;

std::once_flag g_memkind_ops_flag;

// Try to dlsym() a particular symbol from 'handle', storing the result in 'ptr'
// if successful.
Status TryDlsym(void* handle, const char* sym, void** ptr) {
  dlerror(); // Need to clear any existing error first.
  void* ret = dlsym(handle, sym);
  char* error = dlerror();
  if (error) {
    return Status::NotSupported(Substitute("could not dlsym $0", sym), error);
  }
  *ptr = ret;
  return Status::OK();
}

// Try to dlopen() memkind and set up all the function pointers we need from it.
//
// Note: in terms of protecting ourselves against changes in memkind, we'll
// notice (and fail) if a symbol is missing, but not if it's signature has
// changed or if there's some subtle behavioral change. A scan of the memkind
// repo suggests that backwards compatibility is enforced: symbols are only
// added and behavioral changes are effected via the introduction of new symbols.
void InitMemkindOps() {
  g_memkind_available = false;

  // Use RTLD_NOW so that if any of memkind's dependencies aren't satisfied
  // (e.g. libnuma is too old and is missing symbols), we'll know up front
  // instead of during cache operations.
  void* memkind_lib = dlopen("libmemkind.so.0", RTLD_NOW);
  if (!memkind_lib) {
    LOG(WARNING) << "could not dlopen: " << dlerror();
    return;
  }
  auto cleanup = MakeScopedCleanup([&]() {
    dlclose(memkind_lib);
  });

#define DLSYM_OR_RETURN(func_name, handle) do { \
    const Status _s = TryDlsym(memkind_lib, func_name, handle); \
    if (!_s.ok()) { \
      LOG(WARNING) << _s.ToString(); \
      return; \
    } \
  } while (0)

  DLSYM_OR_RETURN("memkind_create_pmem", &g_memkind_create_pmem);
  DLSYM_OR_RETURN("memkind_destroy_kind", &g_memkind_destroy_kind);
  DLSYM_OR_RETURN("memkind_malloc", &g_memkind_malloc);
  DLSYM_OR_RETURN("memkind_malloc_usable_size", &g_memkind_malloc_usable_size);
  DLSYM_OR_RETURN("memkind_free", &g_memkind_free);
#undef DLSYM_OR_RETURN

  g_memkind_available = true;

  // Need to keep the memkind library handle open so our function pointers
  // remain loaded in memory.
  cleanup.cancel();
}

typedef simple_spinlock MutexType;

// LRU cache implementation

// An entry is a variable length heap-allocated structure.  Entries
// are kept in a circular doubly linked list ordered by access time.
struct LRUHandle {
  Cache::EvictionCallback* eviction_callback;
  LRUHandle* next_hash;
  LRUHandle* next;
  LRUHandle* prev;
  size_t charge;      // TODO(opt): Only allow uint32_t?
  uint32_t key_length;
  uint32_t val_length;
  Atomic32 refs;
  uint32_t hash;      // Hash of key(); used for fast sharding and comparisons
  uint8_t* kv_data;

  Slice key() const {
    return Slice(kv_data, key_length);
  }

  Slice value() const {
    return Slice(&kv_data[key_length], val_length);
  }

  uint8_t* val_ptr() {
    return &kv_data[key_length];
  }
};

// We provide our own simple hash table since it removes a whole bunch
// of porting hacks and is also faster than some of the built-in hash
// table implementations in some of the compiler/runtime combinations
// we have tested.  E.g., readrandom speeds up by ~5% over the g++
// 4.4.3's builtin hashtable.
class HandleTable {
 public:
  HandleTable() : length_(0), elems_(0), list_(nullptr) { Resize(); }
  ~HandleTable() { delete[] list_; }

  LRUHandle* Lookup(const Slice& key, uint32_t hash) {
    return *FindPointer(key, hash);
  }

  LRUHandle* Insert(LRUHandle* h) {
    LRUHandle** ptr = FindPointer(h->key(), h->hash);
    LRUHandle* old = *ptr;
    h->next_hash = (old == nullptr ? nullptr : old->next_hash);
    *ptr = h;
    if (old == nullptr) {
      ++elems_;
      if (elems_ > length_) {
        // Since each cache entry is fairly large, we aim for a small
        // average linked list length (<= 1).
        Resize();
      }
    }
    return old;
  }

  LRUHandle* Remove(const Slice& key, uint32_t hash) {
    LRUHandle** ptr = FindPointer(key, hash);
    LRUHandle* result = *ptr;
    if (result != nullptr) {
      *ptr = result->next_hash;
      --elems_;
    }
    return result;
  }

 private:
  // The table consists of an array of buckets where each bucket is
  // a linked list of cache entries that hash into the bucket.
  uint32_t length_;
  uint32_t elems_;
  LRUHandle** list_;

  // Return a pointer to slot that points to a cache entry that
  // matches key/hash.  If there is no such cache entry, return a
  // pointer to the trailing slot in the corresponding linked list.
  LRUHandle** FindPointer(const Slice& key, uint32_t hash) {
    LRUHandle** ptr = &list_[hash & (length_ - 1)];
    while (*ptr != nullptr &&
           ((*ptr)->hash != hash || key != (*ptr)->key())) {
      ptr = &(*ptr)->next_hash;
    }
    return ptr;
  }

  void Resize() {
    uint32_t new_length = 16;
    while (new_length < elems_ * 1.5) {
      new_length *= 2;
    }
    LRUHandle** new_list = new LRUHandle*[new_length];
    memset(new_list, 0, sizeof(new_list[0]) * new_length);
    uint32_t count = 0;
    for (uint32_t i = 0; i < length_; i++) {
      LRUHandle* h = list_[i];
      while (h != nullptr) {
        LRUHandle* next = h->next_hash;
        uint32_t hash = h->hash;
        LRUHandle** ptr = &new_list[hash & (new_length - 1)];
        h->next_hash = *ptr;
        *ptr = h;
        h = next;
        count++;
      }
    }
    DCHECK_EQ(elems_, count);
    delete[] list_;
    list_ = new_list;
    length_ = new_length;
  }
};

// A single shard of sharded cache.
class NvmLRUCache {
 public:
  explicit NvmLRUCache(memkind *vmp);
  ~NvmLRUCache();

  // Separate from constructor so caller can easily make an array of LRUCache
  void SetCapacity(size_t capacity) { capacity_ = capacity; }

  void SetMetrics(CacheMetrics* metrics) { metrics_ = metrics; }

  Cache::Handle* Insert(LRUHandle* e, Cache::EvictionCallback* eviction_callback);

  // Like Cache::Lookup, but with an extra "hash" parameter.
  Cache::Handle* Lookup(const Slice& key, uint32_t hash, bool caching);
  void Release(Cache::Handle* handle);
  void Erase(const Slice& key, uint32_t hash);
  size_t Invalidate(const Cache::InvalidationControl& ctl);
  void* Allocate(size_t size);

 private:
  void NvmLRU_Remove(LRUHandle* e);
  void NvmLRU_Append(LRUHandle* e);
  // Just reduce the reference count by 1.
  // Return true if last reference
  bool Unref(LRUHandle* e);
  void FreeEntry(LRUHandle* e);

  // Evict the LRU item in the cache, adding it to the linked list
  // pointed to by 'to_remove_head'.
  void EvictOldestUnlocked(LRUHandle** to_remove_head);

  // Free all of the entries in the linked list that has to_free_head
  // as its head.
  void FreeLRUEntries(LRUHandle* to_free_head);

  // Wrapper around memkind_malloc which injects failures based on a flag.
  void* MemkindMalloc(size_t size);

  // Initialized before use.
  size_t capacity_;

  // mutex_ protects the following state.
  MutexType mutex_;
  size_t usage_;

  // Dummy head of LRU list.
  // lru.prev is newest entry, lru.next is oldest entry.
  LRUHandle lru_;

  HandleTable table_;

  memkind* vmp_;

  CacheMetrics* metrics_;
};

NvmLRUCache::NvmLRUCache(memkind* vmp)
  : usage_(0),
  vmp_(vmp),
  metrics_(nullptr) {
  // Make empty circular linked list
  lru_.next = &lru_;
  lru_.prev = &lru_;
}

NvmLRUCache::~NvmLRUCache() {
  for (LRUHandle* e = lru_.next; e != &lru_; ) {
    LRUHandle* next = e->next;
    DCHECK_EQ(e->refs, 1);  // Error if caller has an unreleased handle
    if (Unref(e)) {
      FreeEntry(e);
    }
    e = next;
  }
}

void* NvmLRUCache::MemkindMalloc(size_t size) {
  if (PREDICT_FALSE(FLAGS_nvm_cache_simulate_allocation_failure)) {
    return nullptr;
  }
  return CALL_MEMKIND(memkind_malloc, vmp_, size);
}

bool NvmLRUCache::Unref(LRUHandle* e) {
  DCHECK_GT(ANNOTATE_UNPROTECTED_READ(e->refs), 0);
  return !base::RefCountDec(&e->refs);
}

void NvmLRUCache::FreeEntry(LRUHandle* e) {
  DCHECK_EQ(ANNOTATE_UNPROTECTED_READ(e->refs), 0);
  if (e->eviction_callback) {
    e->eviction_callback->EvictedEntry(e->key(), e->value());
  }
  if (PREDICT_TRUE(metrics_)) {
    metrics_->cache_usage->DecrementBy(e->charge);
    metrics_->evictions->Increment();
  }
  CALL_MEMKIND(memkind_free, vmp_, e);
}

// Allocate NVM memory.
void* NvmLRUCache::Allocate(size_t size) {
  return MemkindMalloc(size);
}

void NvmLRUCache::NvmLRU_Remove(LRUHandle* e) {
  e->next->prev = e->prev;
  e->prev->next = e->next;
  usage_ -= e->charge;
}

void NvmLRUCache::NvmLRU_Append(LRUHandle* e) {
  // Make "e" newest entry by inserting just before lru_
  e->next = &lru_;
  e->prev = lru_.prev;
  e->prev->next = e;
  e->next->prev = e;
  usage_ += e->charge;
}

Cache::Handle* NvmLRUCache::Lookup(const Slice& key, uint32_t hash, bool caching) {
 LRUHandle* e;
  {
    std::lock_guard<MutexType> l(mutex_);
    e = table_.Lookup(key, hash);
    if (e != nullptr) {
      // If an entry exists, remove the old entry from the cache
      // and re-add to the end of the linked list.
      base::RefCountInc(&e->refs);
      NvmLRU_Remove(e);
      NvmLRU_Append(e);
    }
  }

  // Do the metrics outside of the lock.
  if (metrics_) {
    metrics_->lookups->Increment();
    bool was_hit = (e != nullptr);
    if (was_hit) {
      if (caching) {
        metrics_->cache_hits_caching->Increment();
      } else {
        metrics_->cache_hits->Increment();
      }
    } else {
      if (caching) {
        metrics_->cache_misses_caching->Increment();
      } else {
        metrics_->cache_misses->Increment();
      }
    }
  }

  return reinterpret_cast<Cache::Handle*>(e);
}

void NvmLRUCache::Release(Cache::Handle* handle) {
  LRUHandle* e = reinterpret_cast<LRUHandle*>(handle);
  bool last_reference = Unref(e);
  if (last_reference) {
    FreeEntry(e);
  }
}

void NvmLRUCache::EvictOldestUnlocked(LRUHandle** to_remove_head) {
  LRUHandle* old = lru_.next;
  NvmLRU_Remove(old);
  table_.Remove(old->key(), old->hash);
  if (Unref(old)) {
    old->next = *to_remove_head;
    *to_remove_head = old;
  }
}

void NvmLRUCache::FreeLRUEntries(LRUHandle* to_free_head) {
  while (to_free_head != nullptr) {
    LRUHandle* next = to_free_head->next;
    FreeEntry(to_free_head);
    to_free_head = next;
  }
}

Cache::Handle* NvmLRUCache::Insert(LRUHandle* e,
                                   Cache::EvictionCallback* eviction_callback) {
  DCHECK(e);
  LRUHandle* to_remove_head = nullptr;

  e->refs = 2;  // One from LRUCache, one for the returned handle
  e->eviction_callback = eviction_callback;
  if (PREDICT_TRUE(metrics_)) {
    metrics_->cache_usage->IncrementBy(e->charge);
    metrics_->inserts->Increment();
  }

  {
    std::lock_guard<MutexType> l(mutex_);

    NvmLRU_Append(e);

    LRUHandle* old = table_.Insert(e);
    if (old != nullptr) {
      NvmLRU_Remove(old);
      if (Unref(old)) {
        old->next = to_remove_head;
        to_remove_head = old;
      }
    }

    while (usage_ > capacity_ && lru_.next != &lru_) {
      EvictOldestUnlocked(&to_remove_head);
    }
  }

  // we free the entries here outside of mutex for
  // performance reasons
  FreeLRUEntries(to_remove_head);

  return reinterpret_cast<Cache::Handle*>(e);
}

void NvmLRUCache::Erase(const Slice& key, uint32_t hash) {
  LRUHandle* e;
  bool last_reference = false;
  {
    std::lock_guard<MutexType> l(mutex_);
    e = table_.Remove(key, hash);
    if (e != nullptr) {
      NvmLRU_Remove(e);
      last_reference = Unref(e);
    }
  }
  // mutex not held here
  // last_reference will only be true if e != nullptr
  if (last_reference) {
    FreeEntry(e);
  }
}

size_t NvmLRUCache::Invalidate(const Cache::InvalidationControl& ctl) {
  size_t invalid_entry_count = 0;
  size_t valid_entry_count = 0;
  LRUHandle* to_remove_head = nullptr;

  {
    std::lock_guard<MutexType> l(mutex_);

    // rl_.next is the oldest entry in the recency list.
    LRUHandle* h = lru_.next;
    while (h != nullptr && h != &lru_ &&
           ctl.iteration_func(valid_entry_count, invalid_entry_count)) {
      if (ctl.validity_func(h->key(), h->value())) {
        // Continue iterating over the list.
        h = h->next;
        ++valid_entry_count;
        continue;
      }
      // Copy the handle slated for removal.
      LRUHandle* h_to_remove = h;
      // Prepare for next iteration of the cycle.
      h = h->next;

      NvmLRU_Remove(h_to_remove);
      table_.Remove(h_to_remove->key(), h_to_remove->hash);
      if (Unref(h_to_remove)) {
        h_to_remove->next = to_remove_head;
        to_remove_head = h_to_remove;
      }
      ++invalid_entry_count;
    }
  }

  FreeLRUEntries(to_remove_head);

  return invalid_entry_count;
}

// Determine the number of bits of the hash that should be used to determine
// the cache shard. This, in turn, determines the number of shards.
int DetermineShardBits() {
  int bits = PREDICT_FALSE(FLAGS_cache_force_single_shard) ?
      0 : Bits::Log2Ceiling(base::NumCPUs());
  VLOG(1) << "Will use " << (1 << bits) << " shards for LRU cache.";
  return bits;
}

class ShardedLRUCache : public Cache {
 private:
  unique_ptr<CacheMetrics> metrics_;
  vector<unique_ptr<NvmLRUCache>> shards_;

  // Number of bits of hash used to determine the shard.
  const int shard_bits_;

  memkind* vmp_;

  static inline uint32_t HashSlice(const Slice& s) {
    return util_hash::CityHash64(
      reinterpret_cast<const char *>(s.data()), s.size());
  }

  uint32_t Shard(uint32_t hash) {
    // Widen to uint64 before shifting, or else on a single CPU,
    // we would try to shift a uint32_t by 32 bits, which is undefined.
    return static_cast<uint64_t>(hash) >> (32 - shard_bits_);
  }

 public:
  explicit ShardedLRUCache(size_t capacity, const string& /*id*/, memkind* vmp)
      : shard_bits_(DetermineShardBits()),
        vmp_(vmp) {
    int num_shards = 1 << shard_bits_;
    const size_t per_shard = (capacity + (num_shards - 1)) / num_shards;
    for (int s = 0; s < num_shards; s++) {
      unique_ptr<NvmLRUCache> shard(new NvmLRUCache(vmp_));
      shard->SetCapacity(per_shard);
      shards_.emplace_back(std::move(shard));
    }
  }

  virtual ~ShardedLRUCache() {
    shards_.clear();
    // Per the note at the top of this file, our cache is entirely volatile.
    // Hence, when the cache is destructed, we delete the underlying
    // memkind pool.
    CALL_MEMKIND(memkind_destroy_kind, vmp_);
  }

  virtual UniqueHandle Insert(UniquePendingHandle handle,
                              Cache::EvictionCallback* eviction_callback) OVERRIDE {
    LRUHandle* h = reinterpret_cast<LRUHandle*>(DCHECK_NOTNULL(handle.release()));
    return UniqueHandle(
        shards_[Shard(h->hash)]->Insert(h, eviction_callback),
        Cache::HandleDeleter(this));
  }
  virtual UniqueHandle Lookup(const Slice& key, CacheBehavior caching) OVERRIDE {
    const uint32_t hash = HashSlice(key);
    return UniqueHandle(
        shards_[Shard(hash)]->Lookup(key, hash, caching == EXPECT_IN_CACHE),
        Cache::HandleDeleter(this));
  }
  virtual void Release(Handle* handle) OVERRIDE {
    LRUHandle* h = reinterpret_cast<LRUHandle*>(handle);
    shards_[Shard(h->hash)]->Release(handle);
  }
  virtual void Erase(const Slice& key) OVERRIDE {
    const uint32_t hash = HashSlice(key);
    shards_[Shard(hash)]->Erase(key, hash);
  }
  virtual Slice Value(const UniqueHandle& handle) const OVERRIDE {
    return reinterpret_cast<const LRUHandle*>(handle.get())->value();
  }
  virtual uint8_t* MutableValue(UniquePendingHandle* handle) OVERRIDE {
    return reinterpret_cast<LRUHandle*>(handle->get())->val_ptr();
  }

  virtual void SetMetrics(unique_ptr<CacheMetrics> metrics) OVERRIDE {
    metrics_ = std::move(metrics);
    for (const auto& shard : shards_) {
      shard->SetMetrics(metrics_.get());
    }
  }
  virtual UniquePendingHandle Allocate(Slice key, int val_len, int charge) OVERRIDE {
    int key_len = key.size();
    DCHECK_GE(key_len, 0);
    DCHECK_GE(val_len, 0);

    // Try allocating from each of the shards -- if memkind is tight,
    // this can cause eviction, so we might have better luck in different
    // shards.
    for (const auto& shard : shards_) {
      UniquePendingHandle ph(static_cast<PendingHandle*>(
          shard->Allocate(sizeof(LRUHandle) + key_len + val_len)),
          Cache::PendingHandleDeleter(this));
      if (ph) {
        LRUHandle* handle = reinterpret_cast<LRUHandle*>(ph.get());
        uint8_t* buf = reinterpret_cast<uint8_t*>(ph.get());
        handle->kv_data = &buf[sizeof(LRUHandle)];
        handle->val_length = val_len;
        handle->key_length = key_len;
        // Multiply the results of memkind_malloc_usable_size by a ratio
        // due to the fragmentation is not counted in.
        handle->charge = (charge == kAutomaticCharge) ?
            CALL_MEMKIND(memkind_malloc_usable_size, vmp_, buf) * FLAGS_nvm_cache_usage_ratio :
            charge;
        handle->hash = HashSlice(key);
        memcpy(handle->kv_data, key.data(), key.size());
        return ph;
      }
    }
    // TODO(unknown): increment a metric here on allocation failure.
    return UniquePendingHandle(nullptr, Cache::PendingHandleDeleter(this));
  }

  virtual void Free(PendingHandle* ph) OVERRIDE {
    CALL_MEMKIND(memkind_free, vmp_, ph);
  }

  size_t Invalidate(const InvalidationControl& ctl) override {
    size_t invalidated_count = 0;
    for (const auto& shard: shards_) {
      invalidated_count += shard->Invalidate(ctl);
    }
    return invalidated_count;
  }
};

} // end anonymous namespace

template<>
Cache* NewCache<Cache::EvictionPolicy::LRU,
                Cache::MemoryType::NVM>(size_t capacity, const std::string& id) {
  std::call_once(g_memkind_ops_flag, InitMemkindOps);

  // TODO(adar): we should plumb the failure up the call stack, but at the time
  // of writing the NVM cache is only usable by the block cache, and its use of
  // the singleton pattern prevents the surfacing of errors.
  CHECK(g_memkind_available) << "Memkind not available!";

  // memkind_create_pmem() will fail if the capacity is too small, but with
  // an inscrutable error. So, we'll check ourselves.
  CHECK_GE(capacity, MEMKIND_PMEM_MIN_SIZE)
    << "configured capacity " << capacity << " bytes is less than "
    << "the minimum capacity for an NVM cache: " << MEMKIND_PMEM_MIN_SIZE;

  LOG(INFO) << 1 / FLAGS_nvm_cache_usage_ratio * 100 << "% capacity "
            << "from nvm block cache is available due to memkind fragmentation.";

  memkind* vmp;
  int err = CALL_MEMKIND(memkind_create_pmem, FLAGS_nvm_cache_path.c_str(), capacity, &vmp);
  // If we cannot create the cache pool we should not retry.
  PLOG_IF(FATAL, err) << "Could not initialize NVM cache library in path "
                           << FLAGS_nvm_cache_path.c_str();

  return new ShardedLRUCache(capacity, id, vmp);
}

bool CanUseNVMCacheForTests() {
  std::call_once(g_memkind_ops_flag, InitMemkindOps);
  return g_memkind_available;
}

} // namespace kudu


text:
//
//  BaseModel.m
//  YHDBExample
//
//  Created by 一鸿温 on 15/12/18.
//  Copyright © 2015年 wyh. All rights reserved.
//

#import "BaseModel.h"
#import <objc/runtime.h>

@implementation BaseModel

/** a database
 *
 */
//- (NSString *)dbName {
//    return @"MyDB";
//}

- (NSString *)description {
    NSMutableString *mString = [NSMutableString stringWithString:@"{"];
    [[self _propertyNames] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([[self valueForKey:obj] isKindOfClass:[NSString class]]) {
            [mString appendFormat:@"\n %@ = @\"%@\"", obj, [self valueForKey:obj]];
        }
        else {
            [mString appendFormat:@"\n %@ = %@", obj, [self valueForKey:obj]];
        }
    }];
    [mString appendString:@"\n}"];
    return mString;
}

- (NSArray *)_propertyNames {
        unsigned int outCount, i;
        NSMutableArray *propertyName = [NSMutableArray array];
        objc_property_t *properties = class_copyPropertyList([self class], &outCount);

        for (i=0; i<outCount; i++) {
            objc_property_t property = properties[i];
            const char *propName = property_getName(property);
            if(propName) {
                NSString *name = [NSString stringWithCString:propName
                                                    encoding:[NSString defaultCStringEncoding]];
                [propertyName addObject:name];
            }
        }
        free(properties);
        return propertyName;
}

@end


text:
.class public abstract Lgenerics/TestClassSignature;
.super Ljava/lang/Object;
.source "SourceFile"

# interfaces
.implements Ljava/util/Iterator;

# annotations
.annotation system Ldalvik/annotation/Signature;
    value = {
        "<T:",
        "Ljava/lang/Object;",
        ">",
        "Lgenerics/TestClassSignature<",
        "TT;>;"
    }
.end annotation

# instance fields
.field public f:Ljava/lang/Object;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "TT;"
        }
    .end annotation
.end field

# direct methods
.method public constructor <init>(Ljava/lang/Object;)V
    .registers 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TT;)V"
        }
    .end annotation

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V
    iput-object p1, p0, Lgenerics/TestClassSignature;->f:Ljava/lang/Object;
    return-void
.end method

# virtual methods
.method public abstract a(Ljava/lang/Object;)Ljava/lang/Object;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TT;)TT;"
        }
    .end annotation
.end method

.method public final hasNext()Z
    .registers 2

    .line 1
    iget-object v0, p0, Lgenerics/TestClassSignature;->f:Ljava/lang/Object;
    if-eqz v0, :cond_6
    const/4 v0, 0x1
    goto :goto_7

    :cond_6
    const/4 v0, 0x0

    :goto_7
    return v0
.end method

.method public final next()Ljava/lang/Object;
    .registers 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TT;"
        }
    .end annotation

    invoke-virtual {p0}, Lgenerics/TestClassSignature;->hasNext()Z
    move-result v0
    if-eqz v0, :cond_1b

    :try_start_6
    iget-object v0, p0, Lgenerics/TestClassSignature;->f:Ljava/lang/Object;
    :try_end_8
    .catchall {:try_start_6 .. :try_end_8} :catchall_11

    iget-object v1, p0, Lgenerics/TestClassSignature;->f:Ljava/lang/Object;
    invoke-virtual {p0, v1}, Lgenerics/TestClassSignature;->a(Ljava/lang/Object;)Ljava/lang/Object;
    move-result-object v1
    iput-object v1, p0, Lgenerics/TestClassSignature;->f:Ljava/lang/Object;
    return-object v0

    :catchall_11
    move-exception v0

    iget-object v1, p0, Lgenerics/TestClassSignature;->f:Ljava/lang/Object;
    invoke-virtual {p0, v1}, Lgenerics/TestClassSignature;->a(Ljava/lang/Object;)Ljava/lang/Object;
    move-result-object v1
    iput-object v1, p0, Lgenerics/TestClassSignature;->f:Ljava/lang/Object;
    throw v0

    :cond_1b
    new-instance v0, Ljava/util/NoSuchElementException;
    invoke-direct {v0}, Ljava/util/NoSuchElementException;-><init>()V
    throw v0
.end method

.method public final remove()V
    .registers 2

    new-instance v0, Ljava/lang/UnsupportedOperationException;
    invoke-direct {v0}, Ljava/lang/UnsupportedOperationException;-><init>()V
    throw v0
.end method


text:
from kombu.mixins import ConsumerMixin
from kombu.log import get_logger
from kombu import Exchange, Queue, Connection
import uuid

conn = Connection('amqp://guest:guest@localhost:5672//', heartbeat=4)

exchange = Exchange('fanout-test', type='fanout')

# Create a queue for this consumer and give it a uuid for the name
queue = Queue(name=str(uuid.uuid4()), exchange=exchange, routing_key='doesnt matter what this is')
queue.maybe_bind(conn)
queue.declare()

logger = get_logger(__name__)

class Worker(ConsumerMixin):

    def __init__(self, connection):
        self.connection = connection
        self.id = uuid.uuid4()
        logger.info(self.id)

    def get_consumers(self, Consumer, channel):
        return [Consumer(queues=[queue],
                         accept=['pickle', 'json'],
                         callbacks=[self.process_message])]

    def process_message(self, body, message):
        logger.info(self.id)
        logger.info("The body is {}".format(body))
        message.ack()

if __name__ == '__main__':
    from kombu.utils.debug import setup_logging
    # setup root logger
    setup_logging(loglevel='INFO', loggers=[''])

    try:
        worker = Worker(conn)
        worker.run()
    except KeyboardInterrupt:
        print('bye bye')


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="ExDoc v0.14.3">
    <title>Mixcord.Cache.Guild – mixcord v0.1.0</title>
    <link rel="stylesheet" href="dist/app-091c05798a.css" />

<button class="sidebar-toggle">

</button>

        mixcord

        v0.1.0

    <input type="text" class="sidebar-searchInput" placeholder="search" autocomplete="off" />

Pages

Modules

Exceptions

        mixcord v0.1.0
        Mixcord.Cache.Guild

Cache for guilds.

The ETS table name associated with the Guild Cache is :guilds. Besides the
methods provided below you can call any other ETS methods on the table.

  Example

info = :ets.info(:guilds)
[..., heir: :none, name: :guilds, size: 1, ...]
size = info[:size]
1

            Summary

      Functions

    get(list)

    get!(list)

            Functions

    get(list)

get([{:id, integer}]) :: Mixcord.Map.Guild.t

get([{:message, Mixcord.Map.Message.t}]) :: Mixcord.Map.Guild.t

    get!(list)

            Built using
            ExDoc (v0.14.3),

            designed by
            Friedel Ziegelmayer.

        <button class="night-mode-toggle" />


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die;
require_once($CFG->dirroot. '/course/format/singleactivity/settingslib.php');

if ($ADMIN->fulltree) {
    $settings->add(new format_singleactivity_admin_setting_activitytype('format_singleactivity/activitytype',
            new lang_string('defactivitytype', 'format_singleactivity'),
            new lang_string('defactivitytypedesc', 'format_singleactivity'),
            'forum', null));
}


text:
from django.db import migrations

class Migration(migrations.Migration):
    dependencies = [
        ("products", "0003_auto_20200309_1329"),
    ]

    operations = [
        migrations.AlterModelOptions(
            name="company",
            options={"ordering": ("pk",), "verbose_name_plural": "companies"},
        ),
        migrations.AlterModelOptions(
            name="product", options={"ordering": ("pk",)},
        ),
    ]


text:
import PropTypes from 'prop-types';
import { Component } from 'react';

class LiveMessage extends Component {
  static contextTypes = {
    announcePolite: PropTypes.func.isRequired,
    announceAssertive: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);

    this.announce = this.announce.bind(this);
  }

  componentDidMount() {
    this.announce();
  }

  componentDidUpdate(prevProps) {
    const { message } = this.props;
    if (message !== prevProps.message) {
      this.announce();
    }
  }

  announce() {
    const { message, 'aria-live': ariaLive } = this.props;
    if (message) {
      if (ariaLive === 'assertive') {
        this.context.announceAssertive(message);
      }
      if (ariaLive === 'polite') {
        this.context.announcePolite(message);
      }
    }
  }

  render() {
    return null;
  }
}

export default LiveMessage;