text:
namespace crs {
#include <ncurses.h>
}

#include "behavior.hpp"
#include "window.hpp"

#include "game.hpp"

void Game::draw_main_menu(Window& mm_window) {
  for(int n=0; n < 255; ++n) {
    mm_window.p("A");
  }
}

Game::Game(Window& starting_window) : main_menu(starting_window) {
  // Ok this one is going to be a dozy.
  // This constructor is going to initalize ALL THE THINGS.
  // There's no way around that.
  // It could potentially take a noticable amount of time to initialize all the things.
  // However we are still going to have the initalization block the rest of the program.
  // Opening the ansync thread of worms is NOT worth it.
  // The only advantage would be that the user could screw around on the menu before the game is loaded.
  // There's nothing of substance you can do before the game is loaded anyway.
  // So accepting keyboard input before the game is loaded really is no big deal.
  // What we can do, is have multiple refreshes take place during this call.
  // Using this we can have a loading bar type thing down the line potentially.
  // Other operations (worldgen etc) could also potentially take a noticable amount of time to run.
  // Those operations will be refered here, which is where the approach behind non instant stuff is detailed.

  draw_main_menu(main_menu);

  // Calls to refresh are done explicitly outside of drawing functions.
  // Having refreshes inside of drawing functions would make drawing animations and similar possible.
  // However animations of that sort would block input, which would make the game feel a lot less responsive.
  // Calling refresh inside of a drawing function could lead to a situation like this:
  // Crawl's auto explore by default will animate every frame.
  // This sounds nice and you see an animation of your character exploring.
  // In practice though, it slows down gameplay a lot, and I disable it every time.
  // Code to disable it could be hard though if we have refresh calls all over the place.
  main_menu.refresh();
}

void Game::run(Behavior action) {
  switch(action) {
    case QUIT_GAME: {
      crs::endwin();
      break;
    }
    case DO_NOTHING: {
      break;
    }
    case MENU_UP: {
      //main_menu.p("h");
      main_menu.refresh();
      break;
    }
    default: {
      throw std::runtime_error("Behavior not implemented.");
      return;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package de.spricom.dessert.classfile.attribute;

import de.spricom.dessert.classfile.constpool.ConstantPool;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;

/**
 * Representes a
 *
 * Java Virtual Machine Specification: 4.7.5. The Exceptions Attribute.
 */
public class ExceptionsAttribute extends AttributeInfo {

    private final String[] exceptions;

    public ExceptionsAttribute(String name, DataInputStream is, ConstantPool constantPool) throws IOException {
        super(name);
        skipLength(is);
        exceptions = readClassNames(name, is, constantPool);
    }

    public String[] getExceptions() {
        return exceptions;
    }

    public void addDependentClassNames(Set<String> classNames) {
        Collections.addAll(classNames, exceptions);
    }
}


text:
<!DOCTYPE html>
<html lang="en">

<link href="https://fonts.googleapis.com/css?family=Encode+Sans+Condensed|Roboto" rel="stylesheet">

{% include head.html %}

<body>

    {% include nav.html %}

    {{ content }}

    {% include footer.html %}

    {% include ga.html %}

</body>

</html>

<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-105673303-1"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments)};
  gtag('js', new Date());

  gtag('config', 'UA-105673303-1');
</script>


text:
$LOAD_PATH.unshift(File.expand_path('../../lib', __FILE__))

require 'pp'
require 'pathname'
FlipperRoot = Pathname(__FILE__).dirname.join('..').expand_path

require 'rubygems'
require 'bundler'

Bundler.setup(:default)

require 'debug'
require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)

require 'flipper'
require 'flipper/api'
require 'flipper/spec/shared_adapter_specs'
require 'flipper/ui'

Dir[FlipperRoot.join('spec/support/**/*.rb')].sort.each { |f| require f }

RSpec.configure do |config|
  config.before(:example) do
    Flipper::Adapters::Poll::Poller.reset if defined?(Flipper::Adapters::Poll::Poller)
    Flipper.unregister_groups
    Flipper.configuration = nil
  end

  config.disable_monkey_patching!

  config.filter_run focus: true
  config.run_all_when_everything_filtered = true
end

RSpec.shared_examples_for 'a percentage' do
  it 'initializes with value' do
    percentage = described_class.new(12)
    expect(percentage).to be_instance_of(described_class)
  end

  it 'converts string values to integers when initializing' do
    percentage = described_class.new('15')
    expect(percentage.value).to eq(15)
  end

  it 'has a value' do
    percentage = described_class.new(19)
    expect(percentage.value).to eq(19)
  end

  it 'raises exception for value higher than 100' do
    expect do
      described_class.new(101)
    end.to raise_error(ArgumentError,
                       'value must be a positive number less than or equal to 100, but was 101')
  end

  it 'raises exception for negative value' do
    expect do
      described_class.new(-1)
    end.to raise_error(ArgumentError,
                       'value must be a positive number less than or equal to 100, but was -1')
  end
end

RSpec.shared_examples_for 'a DSL feature' do
  it 'returns instance of feature' do
    expect(feature).to be_instance_of(Flipper::Feature)
  end

  it 'sets name' do
    expect(feature.name).to eq(:stats)
  end

  it 'sets adapter' do
    expect(feature.adapter.name).to eq(dsl.adapter.name)
  end

  it 'sets instrumenter' do
    expect(feature.instrumenter).to eq(dsl.instrumenter)
  end

  it 'memoizes the feature' do
    expect(dsl.send(method_name, :stats)).to equal(feature)
  end

  it 'raises argument error if not string or symbol' do
    expect do
      dsl.send(method_name, Object.new)
    end.to raise_error(ArgumentError, /must be a String or Symbol/)
  end
end

RSpec.shared_examples_for 'a DSL boolean method' do
  it 'returns boolean with value set' do
    result = subject.send(method_name, true)
    expect(result).to be_instance_of(Flipper::Types::Boolean)
    expect(result.value).to be(true)

    result = subject.send(method_name, false)
    expect(result).to be_instance_of(Flipper::Types::Boolean)
    expect(result.value).to be(false)
  end
end


text:
using UnityEngine;
using Leap.Unity.Attributes;

namespace Leap.Unity {

  /**
  * A base class for implementing detectors that detect a holding pose of a hand.
  *
  * Such detectors might use the PinchStrength, PinchDistance, GrabStrength, or GrabAngle
  * properties of the Hand or might use a more complex heuristic.
  */
  public abstract class AbstractHoldDetector : Detector {

    /** Implementations must implement this method. */
    protected abstract void ensureUpToDate();

    [AutoFind(AutoFindLocations.Parents)]
    [SerializeField]
    protected IHandModel _handModel;
    public IHandModel HandModel { get { return _handModel; } set { _handModel = value; } }

    /**
    * Whether the Transform of the object containing this Detector script
    * is transformed by the Position and Rotation of the hand when IsHolding is true.
    *
    * If false, the Transform is not affected.
    */
    public bool ControlsTransform = true;

    protected int _lastUpdateFrame = -1;

    protected bool _didChange = false;

    protected Vector3 _position;
    protected Quaternion _rotation;
    protected Vector3 _direction = Vector3.forward;
    protected Vector3 _normal = Vector3.up;
    protected float _distance;

    protected float _lastHoldTime = 0.0f;
    protected float _lastReleaseTime = 0.0f;
    protected Vector3 _lastPosition = Vector3.zero;
    protected Quaternion _lastRotation = Quaternion.identity;
    protected Vector3 _lastDirection = Vector3.forward;
    protected Vector3 _lastNormal = Vector3.up;
    protected float _lastDistance = 1.0f;

    protected virtual void Awake() {
      if (GetComponent<IHandModel>() != null && ControlsTransform == true) {
        Debug.LogWarning("Detector should not be control the IHandModel's transform. Either attach it to its own transform or set ControlsTransform to false.");
      }
      if (_handModel == null) {
        _handModel = GetComponentInParent<IHandModel>();
        if (_handModel == null) {
          Debug.LogWarning("The HandModel field of Detector was unassigned and the detector has been disabled.");
          enabled = false;
        }
      }
    }

    protected virtual void Update() {
      //We ensure the data is up to date at all times because
      //there are some values (like LastPinchTime) that cannot
      //be updated on demand
      ensureUpToDate();
    }

    /// <summary>
    /// Returns whether or not the dectector is currently detecting a pinch or grab.
    /// </summary>
    public virtual bool IsHolding {
      get {
        ensureUpToDate();
        return IsActive;
      }
    }

    /// <summary>
    /// Returns whether or not the value of IsPinching is different than the value reported during
    /// the previous frame.
    /// </summary>
    public virtual bool DidChangeFromLastFrame {
      get {
        ensureUpToDate();
        return _didChange;
      }
    }

    /// <summary>
    /// Returns whether or not the value of IsHolding changed to true between this frame and the previous.
    /// </summary>
    public virtual bool DidStartHold {
      get {
        ensureUpToDate();
        return DidChangeFromLastFrame && IsHolding;
      }
    }

    /// <summary>
    /// Returns whether or not the value of IsHolding changed to false between this frame and the previous.
    /// </summary>
    public virtual bool DidRelease {
      get {
        ensureUpToDate();
        return DidChangeFromLastFrame && !IsHolding;
      }
    }

    /// <summary>
    /// Returns the value of Time.time during the most recent pinch event.
    /// </summary>
    public float LastHoldTime {
      get {
        ensureUpToDate();
        return _lastHoldTime;
      }
    }

    /// <summary>
    /// Returns the value of Time.time during the most recent unpinch event.
    /// </summary>
    public float LastReleaseTime {
      get {
        ensureUpToDate();
        return _lastReleaseTime;
      }
    }

    /// <summary>
    /// Returns the position value of the detected pinch or grab.  If a pinch or grab is not currently being
    /// detected, returns the most recent position value.
    /// </summary>
    public Vector3 Position {
      get {
        ensureUpToDate();
        return _position;
      }
    }
    public Vector3 LastActivePosition { get { return _lastPosition; } }
    /// <summary>
    /// Returns the rotation value of the detected pinch or grab.  If a pinch or grab is not currently being
    /// detected, returns the most recent rotation value.
    /// </summary>
    public Quaternion Rotation {
      get {
        ensureUpToDate();
        return _rotation;
      }
    }
    public Quaternion LastActiveRotation { get { return _lastRotation; } }

    public Vector3 Direction { get { return _direction; } }
    public Vector3 LastActiveDirection { get { return _lastDirection; } }
    public Vector3 Normal { get { return _normal; } }
    public Vector3 LastActiveNormal { get { return _lastNormal; } }
    public float Distance { get { return _distance; } }
    public float LastActiveDistance { get { return _lastDistance; } }

    protected virtual void changeState(bool shouldBeActive) {
      bool currentState = IsActive;
      if (shouldBeActive) {
        _lastHoldTime = Time.time;
        Activate();
      } else {
        _lastReleaseTime = Time.time;
        Deactivate();
      }
      if (currentState != IsActive) {
        _didChange = true;
      }
    }

    #if UNITY_EDITOR
    protected virtual void OnDrawGizmos () {
      if (ShowGizmos) {
        ensureUpToDate();
        Color centerColor;
        Vector3 centerPosition = _position;
        Quaternion circleRotation = _rotation;
        if (IsHolding) {
          centerColor = Color.green;
        } else {
          centerColor = Color.red;
        }
        Vector3 axis;
        float angle;
        circleRotation.ToAngleAxis(out angle, out axis);
        Utils.DrawCircle(centerPosition, Normal, Distance / 2, centerColor);
        Debug.DrawLine(centerPosition, centerPosition + Direction * Distance / 2, Color.grey);
        Debug.DrawLine(centerPosition, centerPosition + Normal * Distance / 2, Color.white);
      }
    }
    #endif

  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>vuetify-quill</title>
    <link rel="stylesheet" href="./dist/vuetify-quill.css">
    <link href="https://fonts.googleapis.com/css?family=Mirza|Roboto" rel="stylesheet">


text: Simple restful with PHP.


text:
from __future__ import absolute_import

import sys as a
from .. import sys as b


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Pl. Dis. Reptr 16(4): 31 (1932)

#### Original name
Hypodermella montivaga f. contorta Dearn., 1932

### Remarks
null


text:
var Constants = {
	PEOPLE_CHANGE_EVENT: 'PEOPLE_CHANGE_EVENT',
	PEOPLE_LOADED: 'PEOPLE_LOADED',
	CURRENT_PERSON_LOADED: 'CURRENT_PERSON_LOADED',
	ORGS_CHANGE_EVENT: 'ORGS_CHANGE_EVENT',
	ORGS_LOADED: 'ORGS_LOADED',
	CURRENT_ORG_LOADED: 'CURRENT_ORG_LOADED',
	CURRENT_ORG_CHANGE_EVENT: 'CURRENT_ORG_CHANGE_EVENT',
	CURRENT_PERSON_CHANGE_EVENT: 'CURRENT_PERSON_CHANGE_EVENT'
};

module.exports = Constants;


text:
#include "../../precomp.hpp"

#if defined(HAVE_OPENCL) && !defined(HAVE_OPENCL_STATIC)

#include BLIK_OPENCV_U_opencv2__core_hpp //original-code:"opencv2/core.hpp" // CV_Error

#include BLIK_OPENCV_U_opencv2__core__opencl__runtime__opencl_core_hpp //original-code:"opencv2/core/opencl/runtime/opencl_core.hpp"

#define OPENCL_FUNC_TO_CHECK_1_1 "clEnqueueReadBufferRect"
#define ERROR_MSG_CANT_LOAD "Failed to load OpenCL runtime\n"
#define ERROR_MSG_INVALID_VERSION "Failed to load OpenCL runtime (expected version 1.1+)\n"

#if defined(__APPLE__)
#include <dlfcn.h>

static void* AppleCLGetProcAddress(const char* name)
{
    static bool initialized = false;
    static void* handle = NULL;
    if (!handle)
    {
        if(!initialized)
        {
            initialized = true;
            const char* path = "/System/Library/Frameworks/OpenCL.framework/Versions/Current/OpenCL";
            const char* envPath = getenv("OPENCV_OPENCL_RUNTIME");
            if (envPath)
                path = envPath;
            handle = dlopen(oclpath, RTLD_LAZY | RTLD_GLOBAL);
            if (handle == NULL)
            {
                if (envPath)
                    fprintf(stderr, ERROR_MSG_CANT_LOAD);
            }
            else if (dlsym(handle, OPENCL_FUNC_TO_CHECK_1_1) == NULL)
            {
                fprintf(stderr, ERROR_MSG_INVALID_VERSION);
                handle = NULL;
            }
        }
        if (!handle)
            return NULL;
    }
    return dlsym(handle, name);
}
#define CV_CL_GET_PROC_ADDRESS(name) AppleCLGetProcAddress(name)
#endif // __APPLE__

#if defined(_WIN32)
#include BLIK_FAKEWIN_V_windows_h //original-code:<windows.h>

static void* WinGetProcAddress(const char* name)
{
    static bool initialized = false;
    static HMODULE handle = NULL;
    if (!handle)
    {
        if(!initialized)
        {
            initialized = true;
            handle = GetModuleHandleA("OpenCL.dll");
            if (!handle)
            {
                const char* path = "OpenCL.dll";
                const char* envPath = getenv("OPENCV_OPENCL_RUNTIME");
                if (envPath)
                    path = envPath;
                handle = LoadLibraryA(path);
                if (!handle)
                {
                    if (envPath)
                        fprintf(stderr, ERROR_MSG_CANT_LOAD);
                }
                else if (GetProcAddress(handle, OPENCL_FUNC_TO_CHECK_1_1) == NULL)
                {
                    fprintf(stderr, ERROR_MSG_INVALID_VERSION);
                    handle = NULL;
                }
            }
        }
        if (!handle)
            return NULL;
    }
    return (void*)GetProcAddress(handle, name);
}
#define CV_CL_GET_PROC_ADDRESS(name) WinGetProcAddress(name)
#endif // _WIN32

#if defined(__linux__)
#include <dlfcn.h>
#include <stdio.h>

static void* GetProcAddress(const char* name)
{
    static bool initialized = false;
    static void* handle = NULL;
    if (!handle)
    {
        if(!initialized)
        {
            initialized = true;
            const char* path = "libOpenCL.so";
            const char* envPath = getenv("OPENCV_OPENCL_RUNTIME");
            if (envPath)
                path = envPath;
            handle = dlopen(path, RTLD_LAZY | RTLD_GLOBAL);
            if (handle == NULL)
            {
                if (envPath)
                    fprintf(stderr, ERROR_MSG_CANT_LOAD);
            }
            else if (dlsym(handle, OPENCL_FUNC_TO_CHECK_1_1) == NULL)
            {
                fprintf(stderr, ERROR_MSG_INVALID_VERSION);
                handle = NULL;
            }
        }
        if (!handle)
            return NULL;
    }
    return dlsym(handle, name);
}
#define CV_CL_GET_PROC_ADDRESS(name) GetProcAddress(name)
#endif

#ifndef CV_CL_GET_PROC_ADDRESS
#ifdef __GNUC__
#warning("OPENCV: OpenCL dynamic library loader: check configuration")
#else
#pragma message("WARNING: OPENCV: OpenCL dynamic library loader: check configuration")
#endif
#define CV_CL_GET_PROC_ADDRESS(name) NULL
#endif

static void* opencl_check_fn(int ID);

#include "runtime_common.hpp"

#include "autogenerated/opencl_core_impl.hpp"

//
// BEGIN OF CUSTOM FUNCTIONS
//

#define CUSTOM_FUNCTION_ID 1000

#ifdef HAVE_OPENCL_SVM
#include "opencv2/core/opencl/runtime/opencl_svm_20.hpp"
#define SVM_FUNCTION_ID_START CUSTOM_FUNCTION_ID
#define SVM_FUNCTION_ID_END CUSTOM_FUNCTION_ID + 100

enum OPENCL_FN_SVM_ID
{
    OPENCL_FN_clSVMAlloc = SVM_FUNCTION_ID_START,
    OPENCL_FN_clSVMFree,
    OPENCL_FN_clSetKernelArgSVMPointer,
    OPENCL_FN_clSetKernelExecInfo,
    OPENCL_FN_clEnqueueSVMFree,
    OPENCL_FN_clEnqueueSVMMemcpy,
    OPENCL_FN_clEnqueueSVMMemFill,
    OPENCL_FN_clEnqueueSVMMap,
    OPENCL_FN_clEnqueueSVMUnmap,
};

void* (CL_API_CALL *clSVMAlloc)(cl_context context, cl_svm_mem_flags flags, size_t size, unsigned int alignment) =
        opencl_fn4<OPENCL_FN_clSVMAlloc, void*, cl_context, cl_svm_mem_flags, size_t, unsigned int>::switch_fn;
static const struct DynamicFnEntry _clSVMAlloc_definition = { "clSVMAlloc", (void**)&clSVMAlloc};
void (CL_API_CALL *clSVMFree)(cl_context context, void* svm_pointer) =
        opencl_fn2<OPENCL_FN_clSVMFree, void, cl_context, void*>::switch_fn;
static const struct DynamicFnEntry _clSVMFree_definition = { "clSVMFree", (void**)&clSVMFree};
cl_int (CL_API_CALL *clSetKernelArgSVMPointer)(cl_kernel kernel, cl_uint arg_index, const void* arg_value) =
        opencl_fn3<OPENCL_FN_clSetKernelArgSVMPointer, cl_int, cl_kernel, cl_uint, const void*>::switch_fn;
static const struct DynamicFnEntry _clSetKernelArgSVMPointer_definition = { "clSetKernelArgSVMPointer", (void**)&clSetKernelArgSVMPointer};
//void* (CL_API_CALL *clSetKernelExecInfo)(cl_kernel kernel, cl_kernel_exec_info param_name, size_t param_value_size, const void* param_value) =
//        opencl_fn4<OPENCL_FN_clSetKernelExecInfo, void*, cl_kernel, cl_kernel_exec_info, size_t, const void*>::switch_fn;
//static const struct DynamicFnEntry _clSetKernelExecInfo_definition = { "clSetKernelExecInfo", (void**)&clSetKernelExecInfo};
//cl_int (CL_API_CALL *clEnqueueSVMFree)(...) =
//        opencl_fn8<OPENCL_FN_clEnqueueSVMFree, cl_int, ...>::switch_fn;
//static const struct DynamicFnEntry _clEnqueueSVMFree_definition = { "clEnqueueSVMFree", (void**)&clEnqueueSVMFree};
cl_int (CL_API_CALL *clEnqueueSVMMemcpy)(cl_command_queue command_queue, cl_bool blocking_copy, void* dst_ptr, const void* src_ptr, size_t size, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event) =
        opencl_fn8<OPENCL_FN_clEnqueueSVMMemcpy, cl_int, cl_command_queue, cl_bool, void*, const void*, size_t, cl_uint, const cl_event*, cl_event*>::switch_fn;
static const struct DynamicFnEntry _clEnqueueSVMMemcpy_definition = { "clEnqueueSVMMemcpy", (void**)&clEnqueueSVMMemcpy};
cl_int (CL_API_CALL *clEnqueueSVMMemFill)(cl_command_queue command_queue, void* svm_ptr, const void* pattern, size_t pattern_size, size_t size, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event) =
        opencl_fn8<OPENCL_FN_clEnqueueSVMMemFill, cl_int, cl_command_queue, void*, const void*, size_t, size_t, cl_uint, const cl_event*, cl_event*>::switch_fn;
static const struct DynamicFnEntry _clEnqueueSVMMemFill_definition = { "clEnqueueSVMMemFill", (void**)&clEnqueueSVMMemFill};
cl_int (CL_API_CALL *clEnqueueSVMMap)(cl_command_queue command_queue, cl_bool blocking_map, cl_map_flags map_flags, void* svm_ptr, size_t size, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event) =
        opencl_fn8<OPENCL_FN_clEnqueueSVMMap, cl_int, cl_command_queue, cl_bool, cl_map_flags, void*, size_t, cl_uint, const cl_event*, cl_event*>::switch_fn;
static const struct DynamicFnEntry _clEnqueueSVMMap_definition = { "clEnqueueSVMMap", (void**)&clEnqueueSVMMap};
cl_int (CL_API_CALL *clEnqueueSVMUnmap)(cl_command_queue command_queue, void* svm_ptr, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event) =
        opencl_fn5<OPENCL_FN_clEnqueueSVMUnmap, cl_int, cl_command_queue, void*, cl_uint, const cl_event*, cl_event*>::switch_fn;
static const struct DynamicFnEntry _clEnqueueSVMUnmap_definition = { "clEnqueueSVMUnmap", (void**)&clEnqueueSVMUnmap};

static const struct DynamicFnEntry* opencl_svm_fn_list[] = {
    &_clSVMAlloc_definition,
    &_clSVMFree_definition,
    &_clSetKernelArgSVMPointer_definition,
    NULL/*&_clSetKernelExecInfo_definition*/,
    NULL/*&_clEnqueueSVMFree_definition*/,
    &_clEnqueueSVMMemcpy_definition,
    &_clEnqueueSVMMemFill_definition,
    &_clEnqueueSVMMap_definition,
    &_clEnqueueSVMUnmap_definition,
};
#endif // HAVE_OPENCL_SVM

//
// END OF CUSTOM FUNCTIONS HERE
//

static void* opencl_check_fn(int ID)
{
    const struct DynamicFnEntry* e = NULL;
    if (ID < CUSTOM_FUNCTION_ID)
    {
        assert(ID >= 0 && ID < (int)(sizeof(opencl_fn_list)/sizeof(opencl_fn_list[0])));
        e = opencl_fn_list[ID];
    }
#ifdef HAVE_OPENCL_SVM
    else if (ID >= SVM_FUNCTION_ID_START && ID < SVM_FUNCTION_ID_END)
    {
        ID = ID - SVM_FUNCTION_ID_START;
        assert(ID >= 0 && ID < (int)(sizeof(opencl_svm_fn_list)/sizeof(opencl_svm_fn_list[0])));
        e = opencl_svm_fn_list[ID];
    }
#endif
    else
    {
        CV_ErrorNoReturn(cv::Error::StsBadArg, "Invalid function ID");
    }
    void* func = CV_CL_GET_PROC_ADDRESS(e->fnName);
    if (!func)
    {
        throw cv::Exception(cv::Error::OpenCLApiCallError,
                cv::format("OpenCL function is not available: [%s]", e->fnName),
                CV_Func, __FILE__, __LINE__);
    }
    *(e->ppFn) = func;
    return func;
}

#ifdef HAVE_OPENGL

#include "opencv2/core/opencl/runtime/opencl_gl.hpp"

static void* opencl_gl_check_fn(int ID);

#include "autogenerated/opencl_gl_impl.hpp"

static void* opencl_gl_check_fn(int ID)
{
    const struct DynamicFnEntry* e = NULL;
    assert(ID >= 0 && ID < (int)(sizeof(opencl_gl_fn_list)/sizeof(opencl_gl_fn_list[0])));
    e = opencl_gl_fn_list[ID];
    void* func = CV_CL_GET_PROC_ADDRESS(e->fnName);
    if (!func)
    {
        throw cv::Exception(cv::Error::OpenCLApiCallError,
                cv::format("OpenCL function is not available: [%s]", e->fnName),
                CV_Func, __FILE__, __LINE__);
    }
    *(e->ppFn) = func;
    return func;
}

#endif // HAVE_OPENGL

#endif


text:
module UI{
	/*    --------------------------------------------------- *\
            [class] Button()

            * Crée un button *

    \*    --------------------------------------------------- */
    export class Button extends GUI{

        value: string;

        /*    --------------------------------------------------- *\
                [function] constructor(x, y, width, height, [optional : parent])

                * Quand on crée un button *

                Return: nil
        \*    --------------------------------------------------- */
        constructor(x: number, y: number, width: number, height: number, ...rest: any[]) {
            super();
            this.guiType = "button";

            if (rest[0]) {
                this.setParent(rest[0]);
            }
            this.setPosition(x, y);

            this.setSize(width, height);
            this.value = "";

            var position = this.getPosition(false);
            this.renderElements[0] = new Render.Draw.Rectangle(position.x, position.y, width, height, "rgba(255,255,255,1)");
            this.renderElements[0].setShadow(true);
            this.renderElements[0].setShadowColor("rgba(0,0,0,0.3)");
            this.renderElements[0].setShadowBlur(10);
            this.renderElements[0].setDepth(1);
            this.renderElements[1] = new Render.Draw.Text(position.x, position.y, this.value, width, height);
            this.renderElements[1].setAlign("center");
            this.renderElements[1].setVerticalAlign("middle");
            this.renderElements[1].setFontStyle("bold");
            this.renderElements[1].setDepth(2);

            for (var i = 0; i < this.renderElements.length; ++i) {
                UI.getUsedCanvas().set(this.renderElements[i]);
            }

        }

        /*    --------------------------------------------------- *\
                [function] setValue(value)

                * Set le texte à l'intérieur du button *

                Return: nil
        \*    --------------------------------------------------- */
        setValue(value : string){
            this.value;
            this.renderElements[1].setValue(value);
        }

        /*    --------------------------------------------------- *\
                [function] getValue()

                * Retourne la valeur dans le button *

                Return: value
        \*    --------------------------------------------------- */
        getValue(){
            return this.value;
        }

        /*    --------------------------------------------------- *\
                [function] setBackgroundColor(color)

                * Set la couleur de l'arrière plan *

                Return: nil
        \*    --------------------------------------------------- */
        setBackgroundColor(color : string){
            this.renderElements[0].setColor(color);
        }

    }
}


text:
using System.Buffers;
using System.Diagnostics;
using System.Globalization;
using System.Text;

namespace System.Numerics
{
    internal static class BigNumber
    {
        private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
                                                           | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
                                                           | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
                                                           | NumberStyles.AllowThousands | NumberStyles.AllowExponent
                                                           | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);

        private struct BigNumberBuffer
        {
            public StringBuilder digits;
            public int precision;
            public int scale;
            public bool sign;  // negative sign exists

            public static BigNumberBuffer Create()
            {
                BigNumberBuffer number = new BigNumberBuffer();
                number.digits = new StringBuilder();
                return number;
            }
        }

        internal static bool TryValidateParseStyleInteger(NumberStyles style, out ArgumentException e)
        {
            // Check for undefined flags
            if ((style & InvalidNumberStyles) != 0)
            {
                e = new ArgumentException(SR.Format(SR.Argument_InvalidNumberStyles, nameof(style)));
                return false;
            }
            if ((style & NumberStyles.AllowHexSpecifier) != 0)
            { // Check for hex number
                if ((style & ~NumberStyles.HexNumber) != 0)
                {
                    e = new ArgumentException(SR.Argument_InvalidHexStyle);
                    return false;
                }
            }
            e = null;
            return true;
        }

        internal static bool TryParseBigInteger(string value, NumberStyles style, NumberFormatInfo info, out BigInteger result)
        {
            if (value == null)
            {
                result = default(BigInteger);
                return false;
            }

            return TryParseBigInteger(value.AsReadOnlySpan(), style, info, out result);
        }

        internal static bool TryParseBigInteger(ReadOnlySpan<char> value, NumberStyles style, NumberFormatInfo info, out BigInteger result)
        {
            unsafe
            {
                result = BigInteger.Zero;
                ArgumentException e;
                if (!TryValidateParseStyleInteger(style, out e))
                    throw e; // TryParse still throws ArgumentException on invalid NumberStyles

                BigNumberBuffer bignumber = BigNumberBuffer.Create();
                if (!FormatProvider.TryStringToBigInteger(value, style, info, bignumber.digits, out bignumber.precision, out bignumber.scale, out bignumber.sign))
                    return false;

                if ((style & NumberStyles.AllowHexSpecifier) != 0)
                {
                    if (!HexNumberToBigInteger(ref bignumber, ref result))
                    {
                        return false;
                    }
                }
                else
                {
                    if (!NumberToBigInteger(ref bignumber, ref result))
                    {
                        return false;
                    }
                }
                return true;
            }
        }

        internal static BigInteger ParseBigInteger(string value, NumberStyles style, NumberFormatInfo info)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            return ParseBigInteger(value.AsReadOnlySpan(), style, info);
        }

        internal static BigInteger ParseBigInteger(ReadOnlySpan<char> value, NumberStyles style, NumberFormatInfo info)
        {
            ArgumentException e;
            if (!TryValidateParseStyleInteger(style, out e))
                throw e;

            BigInteger result = BigInteger.Zero;
            if (!TryParseBigInteger(value, style, info, out result))
            {
                throw new FormatException(SR.Overflow_ParseBigInteger);
            }
            return result;
        }

        private static unsafe bool HexNumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value)
        {
            if (number.digits == null || number.digits.Length == 0)
                return false;

            int len = number.digits.Length - 1; // Ignore trailing '\0'
            byte[] bits = new byte[(len / 2) + (len % 2)];

            bool shift = false;
            bool isNegative = false;
            int bitIndex = 0;

            // Parse the string into a little-endian two's complement byte array
            // string value     : O F E B 7 \0
            // string index (i) : 0 1 2 3 4 5 <--
            // byte[] (bitIndex): 2 1 1 0 0 <--
            //
            for (int i = len - 1; i > -1; i--)
            {
                char c = number.digits[i];

                byte b;
                if (c >= '0' && c <= '9')
                {
                    b = (byte)(c - '0');
                }
                else if (c >= 'A' && c <= 'F')
                {
                    b = (byte)((c - 'A') + 10);
                }
                else
                {
                    Debug.Assert(c >= 'a' && c <= 'f');
                    b = (byte)((c - 'a') + 10);
                }
                if (i == 0 && (b & 0x08) == 0x08)
                    isNegative = true;

                if (shift)
                {
                    bits[bitIndex] = (byte)(bits[bitIndex] | (b << 4));
                    bitIndex++;
                }
                else
                {
                    bits[bitIndex] = isNegative ? (byte)(b | 0xF0) : (b);
                }
                shift = !shift;
            }

            value = new BigInteger(bits);
            return true;
        }

        private static unsafe bool NumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value)
        {
            int i = number.scale;
            int cur = 0;

            BigInteger ten = 10;
            value = 0;
            while (--i >= 0)
            {
                value *= ten;
                if (number.digits[cur] != '\0')
                {
                    value += number.digits[cur++] - '0';
                }
            }
            while (number.digits[cur] != '\0')
            {
                if (number.digits[cur++] != '0') return false; // Disallow non-zero trailing decimal places
            }
            if (number.sign)
            {
                value = -value;
            }
            return true;
        }

        // This function is consistent with VM\COMNumber.cpp!COMNumber::ParseFormatSpecifier
        internal static char ParseFormatSpecifier(ReadOnlySpan<char> format, out int digits)
        {
            digits = -1;
            if (format.Length == 0)
            {
                return 'R';
            }

            int i = 0;
            char ch = format[i];
            if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
            {
                i++;
                int n = -1;

                if (i < format.Length && format[i] >= '0' && format[i] <= '9')
                {
                    n = format[i++] - '0';
                    while (i < format.Length && format[i] >= '0' && format[i] <= '9')
                    {
                        n = n * 10 + (format[i++] - '0');
                        if (n >= 10)
                            break;
                    }
                }
                if (i >= format.Length || format[i] == '\0')
                {
                    digits = n;
                    return ch;
                }
            }
            return (char)0; // Custom format
        }

        private static string FormatBigIntegerToHex(bool targetSpan, BigInteger value, char format, int digits, NumberFormatInfo info, Span<char> destination, out int charsWritten, out bool spanSuccess)
        {
            Debug.Assert(format == 'x' || format == 'X');

            // Get the bytes that make up the BigInteger.
            byte[] arrayToReturnToPool = null;
            Span<byte> bits = stackalloc byte[64]; // arbitrary threshold
            if (!value.TryWriteOrCountBytes(bits, out int bytesWrittenOrNeeded))
            {
                bits = arrayToReturnToPool = ArrayPool<byte>.Shared.Rent(bytesWrittenOrNeeded);
                bool success = value.TryWriteBytes(bits, out bytesWrittenOrNeeded);
                Debug.Assert(success);
            }
            bits = bits.Slice(0, bytesWrittenOrNeeded);

            Span<char> stackSpace = stackalloc char[128]; // each byte is typically two chars
            var sb = new ValueStringBuilder(stackSpace);

            int cur = bits.Length - 1;
            if (cur > -1)
            {
                // [FF..F8] drop the high F as the two's complement negative number remains clear
                // [F7..08] retain the high bits as the two's complement number is wrong without it
                // [07..00] drop the high 0 as the two's complement positive number remains clear
                bool clearHighF = false;
                byte head = bits[cur];

                if (head > 0xF7)
                {
                    head -= 0xF0;
                    clearHighF = true;
                }

                if (head < 0x08 || clearHighF)
                {
                    // {0xF8-0xFF} print as {8-F}
                    // {0x00-0x07} print as {0-7}
                    sb.Append(head < 10 ?
                        (char)(head + '0') :
                        format == 'X' ? (char)((head & 0xF) - 10 + 'A') : (char)((head & 0xF) - 10 + 'a'));
                    cur--;
                }
            }

            if (cur > -1)
            {
                Span<char> chars = sb.AppendSpan((cur + 1) * 2);
                int charsPos = 0;
                string hexValues = format == 'x' ? "0123456789abcdef" : "0123456789ABCDEF";
                while (cur > -1)
                {
                    byte b = bits[cur--];
                    chars[charsPos++] = hexValues[b >> 4];
                    chars[charsPos++] = hexValues[b & 0xF];
                }
            }

            if (digits > sb.Length)
            {
                // Insert leading zeros, e.g. user specified "X5" so we create "0ABCD" instead of "ABCD"
                sb.Insert(
                    0,
                    value._sign >= 0 ? '0' : (format == 'x') ? 'f' : 'F',
                    digits - sb.Length);
            }

            if (arrayToReturnToPool != null)
            {
                ArrayPool<byte>.Shared.Return(arrayToReturnToPool);
            }

            if (targetSpan)
            {
                spanSuccess = sb.TryCopyTo(destination, out charsWritten);
                return null;
            }
            else
            {
                charsWritten = 0;
                spanSuccess = false;
                return sb.ToString();
            }
        }

        internal static string FormatBigInteger(BigInteger value, string format, NumberFormatInfo info)
        {
            return FormatBigInteger(targetSpan: false, value, format, format, info, default, out _, out _);
        }

        internal static bool TryFormatBigInteger(BigInteger value, ReadOnlySpan<char> format, NumberFormatInfo info, Span<char> destination, out int charsWritten)
        {
            FormatBigInteger(targetSpan: true, value, null, format, info, destination, out charsWritten, out bool spanSuccess);
            return spanSuccess;
        }

        private static string FormatBigInteger(
            bool targetSpan, BigInteger value,
            string formatString, ReadOnlySpan<char> formatSpan,
            NumberFormatInfo info, Span<char> destination, out int charsWritten, out bool spanSuccess)
        {
            Debug.Assert(formatString == null || formatString.Length == formatSpan.Length);

            int digits = 0;
            char fmt = ParseFormatSpecifier(formatSpan, out digits);
            if (fmt == 'x' || fmt == 'X')
            {
                return FormatBigIntegerToHex(targetSpan, value, fmt, digits, info, destination, out charsWritten, out spanSuccess);
            }

            if (value._bits == null)
            {
                if (fmt == 'g' || fmt == 'G' || fmt == 'r' || fmt == 'R')
                {
                    formatSpan = formatString = digits > 0 ? string.Format("D{0}", digits) : "D";
                }

                if (targetSpan)
                {
                    spanSuccess = value._sign.TryFormat(destination, out charsWritten, formatSpan, info);
                    return null;
                }
                else
                {
                    charsWritten = 0;
                    spanSuccess = false;
                    return value._sign.ToString(formatString, info);
                }
            }

            // First convert to base 10^9.
            const uint kuBase = 1000000000; // 10^9
            const int kcchBase = 9;

            int cuSrc = value._bits.Length;
            int cuMax;
            try
            {
                cuMax = checked(cuSrc * 10 / 9 + 2);
            }
            catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); }
            uint[] rguDst = new uint[cuMax];
            int cuDst = 0;

            for (int iuSrc = cuSrc; --iuSrc >= 0;)
            {
                uint uCarry = value._bits[iuSrc];
                for (int iuDst = 0; iuDst < cuDst; iuDst++)
                {
                    Debug.Assert(rguDst[iuDst] < kuBase);
                    ulong uuRes = NumericsHelpers.MakeUlong(rguDst[iuDst], uCarry);
                    rguDst[iuDst] = (uint)(uuRes % kuBase);
                    uCarry = (uint)(uuRes / kuBase);
                }
                if (uCarry != 0)
                {
                    rguDst[cuDst++] = uCarry % kuBase;
                    uCarry /= kuBase;
                    if (uCarry != 0)
                        rguDst[cuDst++] = uCarry;
                }
            }

            int cchMax;
            try
            {
                // Each uint contributes at most 9 digits to the decimal representation.
                cchMax = checked(cuDst * kcchBase);
            }
            catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); }

            bool decimalFmt = (fmt == 'g' || fmt == 'G' || fmt == 'd' || fmt == 'D' || fmt == 'r' || fmt == 'R');
            if (decimalFmt)
            {
                if (digits > 0 && digits > cchMax)
                    cchMax = digits;
                if (value._sign < 0)
                {
                    try
                    {
                        // Leave an extra slot for a minus sign.
                        cchMax = checked(cchMax + info.NegativeSign.Length);
                    }
                    catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); }
                }
            }

            int rgchBufSize;

            try
            {
                // We'll pass the rgch buffer to native code, which is going to treat it like a string of digits, so it needs
                // to be null terminated.  Let's ensure that we can allocate a buffer of that size.
                rgchBufSize = checked(cchMax + 1);
            }
            catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); }

            char[] rgch = new char[rgchBufSize];

            int ichDst = cchMax;

            for (int iuDst = 0; iuDst < cuDst - 1; iuDst++)
            {
                uint uDig = rguDst[iuDst];
                Debug.Assert(uDig < kuBase);
                for (int cch = kcchBase; --cch >= 0;)
                {
                    rgch[--ichDst] = (char)('0' + uDig % 10);
                    uDig /= 10;
                }
            }
            for (uint uDig = rguDst[cuDst - 1]; uDig != 0;)
            {
                rgch[--ichDst] = (char)('0' + uDig % 10);
                uDig /= 10;
            }

            if (!decimalFmt)
            {
                // sign = true for negative and false for 0 and positive values
                bool sign = (value._sign < 0);
                // The cut-off point to switch (G)eneral from (F)ixed-point to (E)xponential form
                int precision = 29;
                int scale = cchMax - ichDst;

                Span<char> stackSpace = stackalloc char[128]; // arbitrary stack cut-off
                var sb = new ValueStringBuilder(stackSpace);
                FormatProvider.FormatBigInteger(ref sb, precision, scale, sign, formatSpan, info, rgch, ichDst);

                if (targetSpan)
                {
                    spanSuccess = sb.TryCopyTo(destination, out charsWritten);
                    return null;
                }
                else
                {
                    charsWritten = 0;
                    spanSuccess = false;
                    return sb.ToString();
                }
            }

            // Format Round-trip decimal
            // This format is supported for integral types only. The number is converted to a string of
            // decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision
            // specifier indicates the minimum number of digits desired in the resulting string. If required,
            // the number is padded with zeros to its left to produce the number of digits given by the
            // precision specifier.
            int numDigitsPrinted = cchMax - ichDst;
            while (digits > 0 && digits > numDigitsPrinted)
            {
                // pad leading zeros
                rgch[--ichDst] = '0';
                digits--;
            }
            if (value._sign < 0)
            {
                string negativeSign = info.NegativeSign;
                for (int i = info.NegativeSign.Length - 1; i > -1; i--)
                    rgch[--ichDst] = info.NegativeSign[i];
            }

            int resultLength = cchMax - ichDst;
            if (!targetSpan)
            {
                charsWritten = 0;
                spanSuccess = false;
                return new string(rgch, ichDst, cchMax - ichDst);
            }
            else if (new ReadOnlySpan<char>(rgch, ichDst, cchMax - ichDst).TryCopyTo(destination))
            {
                charsWritten = resultLength;
                spanSuccess = true;
                return null;
            }
            else
            {
                charsWritten = 0;
                spanSuccess = false;
                return null;
            }
        }
    }
}


text:
cask :v1 => 'arrsync' do
  version :latest
  sha256 :no_check

  url 'https://sourceforge.net/projects/arrsync/files/latest/download'
  homepage 'http://arrsync.sourceforge.net'
  license :oss

  app 'arRsync.app'
end


text:
'use strict';

var path = require('path');

require('should');

var toAbsolutePath = require('../index');

var context = require('./fixtures/first');

describe('get absolute path', function(){
    describe('current context', function(){
        it('should return the right path', function(){
            context(function(){
                toAbsolutePath('test.file').should.be.equal(path.normalize(process.cwd() + '/test/test.file'));
            });
        });
    });

    describe('one level depth context', function(){
        it('should return the right path', function(){
            context(function(){
                toAbsolutePath('test.file', 1).should.be.equal(path.normalize(process.cwd() + '/test/fixtures/test.file'));
            });
        });
    });

    describe('two level depth context inside folders', function(){
        it('should return the right path', function(){
            context(function(){
                toAbsolutePath('test.file', 2).should.be.equal(path.normalize(process.cwd() + '/test/fixtures/folder/test.file'));
            });
        });
    });

    describe('three level depth context', function(){
        it('should return the right path', function(){
            context(function(){
                toAbsolutePath('test.file', 3).should.be.equal(path.normalize(process.cwd() + '/test/fixtures/test.file'));
            });
        });
    });

    describe('too depth context', function(){
        it('should use the root path', function(){
            context(function(){
                toAbsolutePath('test.file', 100).should.be.equal(path.normalize(process.cwd() + '/test.file'));
            });
        });
    });
});

describe('handle array', function(){
    it('should return multiple paths', function(){
        toAbsolutePath(['first.file', 'second.file']).should.be.deepEqual([path.normalize(process.cwd() + '/test/first.file'), path.normalize(process.cwd() + '/test/second.file')]);
    });
});

describe('handle negative file', function(){
    it('should keep the negative flag', function(){
        toAbsolutePath('!test.file').should.be.equal(path.normalize('!' + process.cwd() + '/test/test.file'))
    });
});


text:
namespace efsw {

FileWatcher::FileWatcher() :
	mFollowSymlinks(false),
	mOutOfScopeLinks(false)
{
	efDEBUG( "Using backend: %s\n", BACKEND_NAME );

	mImpl = new FILEWATCHER_IMPL( this );

	if ( !mImpl->initOK() )
	{
		efSAFE_DELETE( mImpl );

		efDEBUG( "Falled back to backend: %s\n", BACKEND_NAME );

		mImpl = new FileWatcherGeneric( this );
	}
}

FileWatcher::FileWatcher( bool useGenericFileWatcher ) :
	mFollowSymlinks(false),
	mOutOfScopeLinks(false)
{
	if ( useGenericFileWatcher )
	{
		efDEBUG( "Using backend: Generic\n" );

		mImpl = new FileWatcherGeneric( this );
	}
	else
	{
		efDEBUG( "Using backend: %s\n", BACKEND_NAME );

		mImpl = new FILEWATCHER_IMPL( this );

		if ( !mImpl->initOK() )
		{
			efSAFE_DELETE( mImpl );

			efDEBUG( "Falled back to backend: %s\n", BACKEND_NAME );

			mImpl = new FileWatcherGeneric( this );
		}
	}
}

FileWatcher::~FileWatcher()
{
	efSAFE_DELETE( mImpl );
}

WatchID FileWatcher::addWatch(const std::string& directory, FileWatchListener* watcher)
{
	if ( mImpl->mIsGeneric || !FileSystem::isRemoteFS( directory ) )
	{
		return mImpl->addWatch(directory, watcher, false);
	}
	else
	{
		return Errors::Log::createLastError( Errors::FileRemote, directory );
	}
}

WatchID FileWatcher::addWatch(const std::string& directory, FileWatchListener* watcher, bool recursive)
{
	if ( mImpl->mIsGeneric || !FileSystem::isRemoteFS( directory ) )
	{
		return mImpl->addWatch(directory, watcher, recursive);
	}
	else
	{
		return Errors::Log::createLastError( Errors::FileRemote, directory );
	}
}

void FileWatcher::removeWatch(const std::string& directory)
{
	mImpl->removeWatch(directory);
}

void FileWatcher::removeWatch(WatchID watchid)
{
	mImpl->removeWatch(watchid);
}

void FileWatcher::watch()
{
	mImpl->watch();
}

std::list<std::string> FileWatcher::directories()
{
	return mImpl->directories();
}

void FileWatcher::followSymlinks( bool follow )
{
	mFollowSymlinks = follow;
}

const bool& FileWatcher::followSymlinks() const
{
	return mFollowSymlinks;
}

void FileWatcher::allowOutOfScopeLinks( bool allow )
{
	mOutOfScopeLinks = allow;
}

const bool& FileWatcher::allowOutOfScopeLinks() const
{
	return mOutOfScopeLinks;
}

}


text:
#include "ixgbe.h"
#include <linux/ptp_classify.h>

/*
 * The 82599 and the X540 do not have true 64bit nanosecond scale
 * counter registers. Instead, SYSTIME is defined by a fixed point
 * system which allows the user to define the scale counter increment
 * value at every level change of the oscillator driving the SYSTIME
 * value. For both devices the TIMINCA:IV field defines this
 * increment. On the X540 device, 31 bits are provided. However on the
 * 82599 only provides 24 bits. The time unit is determined by the
 * clock frequency of the oscillator in combination with the TIMINCA
 * register. When these devices link at 10Gb the oscillator has a
 * period of 6.4ns. In order to convert the scale counter into
 * nanoseconds the cyclecounter and timecounter structures are
 * used. The SYSTIME registers need to be converted to ns values by use
 * of only a right shift (division by power of 2). The following math
 * determines the largest incvalue that will fit into the available
 * bits in the TIMINCA register.
 *
 * PeriodWidth: Number of bits to store the clock period
 * MaxWidth: The maximum width value of the TIMINCA register
 * Period: The clock period for the oscillator
 * round(): discard the fractional portion of the calculation
 *
 * Period * [ 2 ^ ( MaxWidth - PeriodWidth ) ]
 *
 * For the X540, MaxWidth is 31 bits, and the base period is 6.4 ns
 * For the 82599, MaxWidth is 24 bits, and the base period is 6.4 ns
 *
 * The period also changes based on the link speed:
 * At 10Gb link or no link, the period remains the same.
 * At 1Gb link, the period is multiplied by 10. (64ns)
 * At 100Mb link, the period is multiplied by 100. (640ns)
 *
 * The calculated value allows us to right shift the SYSTIME register
 * value in order to quickly convert it into a nanosecond clock,
 * while allowing for the maximum possible adjustment value.
 *
 * These diagrams are only for the 10Gb link period
 *
 *           SYSTIMEH            SYSTIMEL
 *       +--------------+  +--------------+
 * X540  |      32      |  | 1 | 3 |  28  |
 *       *--------------+  +--------------+
 *        \________ 36 bits ______/  fract
 *
 *       +--------------+  +--------------+
 * 82599 |      32      |  | 8 | 3 |  21  |
 *       *--------------+  +--------------+
 *        \________ 43 bits ______/  fract
 *
 * The 36 bit X540 SYSTIME overflows every
 *   2^36 * 10^-9 / 60 = 1.14 minutes or 69 seconds
 *
 * The 43 bit 82599 SYSTIME overflows every
 *   2^43 * 10^-9 / 3600 = 2.4 hours
 */
#define IXGBE_INCVAL_10GB 0x66666666
#define IXGBE_INCVAL_1GB  0x40000000
#define IXGBE_INCVAL_100  0x50000000

#define IXGBE_INCVAL_SHIFT_10GB  28
#define IXGBE_INCVAL_SHIFT_1GB   24
#define IXGBE_INCVAL_SHIFT_100   21

#define IXGBE_INCVAL_SHIFT_82599 7
#define IXGBE_INCPER_SHIFT_82599 24

#define IXGBE_OVERFLOW_PERIOD    (HZ * 30)
#define IXGBE_PTP_TX_TIMEOUT     (HZ * 15)

/* half of a one second clock period, for use with PPS signal. We have to use
 * this instead of something pre-defined like IXGBE_PTP_PPS_HALF_SECOND, in
 * order to force at least 64bits of precision for shifting
 */
#define IXGBE_PTP_PPS_HALF_SECOND 500000000ULL

/**
 * ixgbe_ptp_setup_sdp_X540
 * @adapter: the adapter private structure
 *
 * this function enables or disables the clock out feature on SDP0 for
 * the X540 device. It will create a 1second periodic output that can
 * be used as the PPS (via an interrupt).
 *
 * It calculates when the systime will be on an exact second, and then
 * aligns the start of the PPS signal to that value. The shift is
 * necessary because it can change based on the link speed.
 */
static void ixgbe_ptp_setup_sdp_X540(struct ixgbe_adapter *adapter)
{
	struct ixgbe_hw *hw = &adapter->hw;
	int shift = adapter->hw_cc.shift;
	u32 esdp, tsauxc, clktiml, clktimh, trgttiml, trgttimh, rem;
	u64 ns = 0, clock_edge = 0;

	/* disable the pin first */
	IXGBE_WRITE_REG(hw, IXGBE_TSAUXC, 0x0);
	IXGBE_WRITE_FLUSH(hw);

	if (!(adapter->flags2 & IXGBE_FLAG2_PTP_PPS_ENABLED))
		return;

	esdp = IXGBE_READ_REG(hw, IXGBE_ESDP);

	/*
	 * enable the SDP0 pin as output, and connected to the
	 * native function for Timesync (ClockOut)
	 */
	esdp |= IXGBE_ESDP_SDP0_DIR |
		IXGBE_ESDP_SDP0_NATIVE;

	/*
	 * enable the Clock Out feature on SDP0, and allow
	 * interrupts to occur when the pin changes
	 */
	tsauxc = IXGBE_TSAUXC_EN_CLK |
			IXGBE_TSAUXC_SYNCLK |
			IXGBE_TSAUXC_SDP0_INT;

	/* set to half clock period */
	clktiml = (u32)(IXGBE_PTP_PPS_HALF_SECOND << shift);
	clktimh = (u32)((IXGBE_PTP_PPS_HALF_SECOND << shift) >> 32);

	/*
	 * Account for the cyclecounter wrap-around value by
	 * using the converted ns value of the current time to
	 * check for when the next aligned second would occur.
	 */
	clock_edge |= (u64)IXGBE_READ_REG(hw, IXGBE_SYSTIML);
	clock_edge |= (u64)IXGBE_READ_REG(hw, IXGBE_SYSTIMH) << 32;
	ns = timecounter_cyc2time(&adapter->hw_tc, clock_edge);

	div_u64_rem(ns, IXGBE_PTP_PPS_HALF_SECOND, &rem);
	clock_edge += ((IXGBE_PTP_PPS_HALF_SECOND - (u64)rem) << shift);

	/* specify the initial clock start time */
	trgttiml = (u32)clock_edge;
	trgttimh = (u32)(clock_edge >> 32);

	IXGBE_WRITE_REG(hw, IXGBE_CLKTIML, clktiml);
	IXGBE_WRITE_REG(hw, IXGBE_CLKTIMH, clktimh);
	IXGBE_WRITE_REG(hw, IXGBE_TRGTTIML0, trgttiml);
	IXGBE_WRITE_REG(hw, IXGBE_TRGTTIMH0, trgttimh);

	IXGBE_WRITE_REG(hw, IXGBE_ESDP, esdp);
	IXGBE_WRITE_REG(hw, IXGBE_TSAUXC, tsauxc);

	IXGBE_WRITE_FLUSH(hw);
}

/**
 * ixgbe_ptp_read_82599 - read raw cycle counter (to be used by time counter)
 * @hw_cc: the cyclecounter structure
 *
 * this function reads the cyclecounter registers and is called by the
 * cyclecounter structure used to construct a ns counter from the
 * arbitrary fixed point registers
 */
static cycle_t ixgbe_ptp_read_82599(const struct cyclecounter *hw_cc)
{
	struct ixgbe_adapter *adapter =
		container_of(hw_cc, struct ixgbe_adapter, hw_cc);
	struct ixgbe_hw *hw = &adapter->hw;
	u64 stamp = 0;

	stamp |= (u64)IXGBE_READ_REG(hw, IXGBE_SYSTIML);
	stamp |= (u64)IXGBE_READ_REG(hw, IXGBE_SYSTIMH) << 32;

	return stamp;
}

/**
 * ixgbe_ptp_convert_to_hwtstamp - convert register value to hw timestamp
 * @adapter: private adapter structure
 * @hwtstamp: stack timestamp structure
 * @systim: unsigned 64bit system time value
 *
 * We need to convert the adapter's RX/TXSTMP registers into a hwtstamp value
 * which can be used by the stack's ptp functions.
 *
 * The lock is used to protect consistency of the cyclecounter and the SYSTIME
 * registers. However, it does not need to protect against the Rx or Tx
 * timestamp registers, as there can't be a new timestamp until the old one is
 * unlatched by reading.
 *
 * In addition to the timestamp in hardware, some controllers need a software
 * overflow cyclecounter, and this function takes this into account as well.
 **/
static void ixgbe_ptp_convert_to_hwtstamp(struct ixgbe_adapter *adapter,
				     struct skb_shared_hwtstamps *hwtstamp,
				     u64 timestamp)
{
	unsigned long flags;
	u64 ns;

	memset(hwtstamp, 0, sizeof(*hwtstamp));

	switch (adapter->hw.mac.type) {
	case ixgbe_mac_82599EB:
	case ixgbe_mac_X540:
		spin_lock_irqsave(&adapter->tmreg_lock, flags);
		ns = timecounter_cyc2time(&adapter->hw_tc, timestamp);
		spin_unlock_irqrestore(&adapter->tmreg_lock, flags);

		hwtstamp->hwtstamp = ns_to_ktime(ns);
		break;
	default:
		break;
	}
}

/**
 * ixgbe_ptp_adjfreq_82599
 * @ptp: the ptp clock structure
 * @ppb: parts per billion adjustment from base
 *
 * adjust the frequency of the ptp cycle counter by the
 * indicated ppb from the base frequency.
 */
static int ixgbe_ptp_adjfreq_82599(struct ptp_clock_info *ptp, s32 ppb)
{
	struct ixgbe_adapter *adapter =
		container_of(ptp, struct ixgbe_adapter, ptp_caps);
	struct ixgbe_hw *hw = &adapter->hw;
	u64 freq;
	u32 diff, incval;
	int neg_adj = 0;

	if (ppb < 0) {
		neg_adj = 1;
		ppb = -ppb;
	}

	smp_mb();
	incval = ACCESS_ONCE(adapter->base_incval);

	freq = incval;
	freq *= ppb;
	diff = div_u64(freq, 1000000000ULL);

	incval = neg_adj ? (incval - diff) : (incval + diff);

	switch (hw->mac.type) {
	case ixgbe_mac_X540:
		IXGBE_WRITE_REG(hw, IXGBE_TIMINCA, incval);
		break;
	case ixgbe_mac_82599EB:
		IXGBE_WRITE_REG(hw, IXGBE_TIMINCA,
				(1 << IXGBE_INCPER_SHIFT_82599) |
				incval);
		break;
	default:
		break;
	}

	return 0;
}

/**
 * ixgbe_ptp_adjtime_82599
 * @ptp: the ptp clock structure
 * @delta: offset to adjust the cycle counter by
 *
 * adjust the timer by resetting the timecounter structure.
 */
static int ixgbe_ptp_adjtime_82599(struct ptp_clock_info *ptp, s64 delta)
{
	struct ixgbe_adapter *adapter =
		container_of(ptp, struct ixgbe_adapter, ptp_caps);
	unsigned long flags;
	u64 now;

	spin_lock_irqsave(&adapter->tmreg_lock, flags);

	now = timecounter_read(&adapter->hw_tc);
	now += delta;

	/* reset the timecounter */
	timecounter_init(&adapter->hw_tc,
			 &adapter->hw_cc,
			 now);

	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);

	if (adapter->ptp_setup_sdp)
		adapter->ptp_setup_sdp(adapter);

	return 0;
}

/**
 * ixgbe_ptp_gettime_82599
 * @ptp: the ptp clock structure
 * @ts: timespec structure to hold the current time value
 *
 * read the timecounter and return the correct value on ns,
 * after converting it into a struct timespec.
 */
static int ixgbe_ptp_gettime_82599(struct ptp_clock_info *ptp, struct timespec *ts)
{
	struct ixgbe_adapter *adapter =
		container_of(ptp, struct ixgbe_adapter, ptp_caps);
	u64 ns;
	u32 remainder;
	unsigned long flags;

	spin_lock_irqsave(&adapter->tmreg_lock, flags);
	ns = timecounter_read(&adapter->hw_tc);
	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);

	ts->tv_sec = div_u64_rem(ns, 1000000000ULL, &remainder);
	ts->tv_nsec = remainder;

	return 0;
}

/**
 * ixgbe_ptp_settime_82599
 * @ptp: the ptp clock structure
 * @ts: the timespec containing the new time for the cycle counter
 *
 * reset the timecounter to use a new base value instead of the kernel
 * wall timer value.
 */
static int ixgbe_ptp_settime_82599(struct ptp_clock_info *ptp,
			     const struct timespec *ts)
{
	struct ixgbe_adapter *adapter =
		container_of(ptp, struct ixgbe_adapter, ptp_caps);
	u64 ns;
	unsigned long flags;

	ns = ts->tv_sec * 1000000000ULL;
	ns += ts->tv_nsec;

	/* reset the timecounter */
	spin_lock_irqsave(&adapter->tmreg_lock, flags);
	timecounter_init(&adapter->hw_tc, &adapter->hw_cc, ns);
	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);

	if (adapter->ptp_setup_sdp)
		adapter->ptp_setup_sdp(adapter);
	return 0;
}

/**
 * ixgbe_ptp_feature_enable
 * @ptp: the ptp clock structure
 * @rq: the requested feature to change
 * @on: whether to enable or disable the feature
 *
 * enable (or disable) ancillary features of the phc subsystem.
 * our driver only supports the PPS feature on the X540
 */
static int ixgbe_ptp_feature_enable(struct ptp_clock_info *ptp,
				    struct ptp_clock_request *rq, int on)
{
	struct ixgbe_adapter *adapter =
		container_of(ptp, struct ixgbe_adapter, ptp_caps);

	/**
	 * When PPS is enabled, unmask the interrupt for the ClockOut
	 * feature, so that the interrupt handler can send the PPS
	 * event when the clock SDP triggers. Clear mask when PPS is
	 * disabled
	 */
	if (rq->type == PTP_CLK_REQ_PPS && adapter->ptp_setup_sdp) {
		if (on)
			adapter->flags2 |= IXGBE_FLAG2_PTP_PPS_ENABLED;
		else
			adapter->flags2 &= ~IXGBE_FLAG2_PTP_PPS_ENABLED;

		adapter->ptp_setup_sdp(adapter);
		return 0;
	}

	return -ENOTSUPP;
}

/**
 * ixgbe_ptp_check_pps_event
 * @adapter: the private adapter structure
 * @eicr: the interrupt cause register value
 *
 * This function is called by the interrupt routine when checking for
 * interrupts. It will check and handle a pps event.
 */
void ixgbe_ptp_check_pps_event(struct ixgbe_adapter *adapter)
{
	struct ixgbe_hw *hw = &adapter->hw;
	struct ptp_clock_event event;

	event.type = PTP_CLOCK_PPS;

	/* this check is necessary in case the interrupt was enabled via some
	 * alternative means (ex. debug_fs). Better to check here than
	 * everywhere that calls this function.
	 */
	if (!adapter->ptp_clock)
		return;

	switch (hw->mac.type) {
	case ixgbe_mac_X540:
		ptp_clock_event(adapter->ptp_clock, &event);
		break;
	default:
		break;
	}
}

/**
 * ixgbe_ptp_overflow_check - watchdog task to detect SYSTIME overflow
 * @adapter: private adapter struct
 *
 * this watchdog task periodically reads the timecounter
 * in order to prevent missing when the system time registers wrap
 * around. This needs to be run approximately twice a minute.
 */
void ixgbe_ptp_overflow_check(struct ixgbe_adapter *adapter)
{
	bool timeout = time_is_before_jiffies(adapter->last_overflow_check +
					     IXGBE_OVERFLOW_PERIOD);
	struct timespec ts;

	if (timeout) {
		ixgbe_ptp_gettime_82599(&adapter->ptp_caps, &ts);
		adapter->last_overflow_check = jiffies;
	}
}

/**
 * ixgbe_ptp_rx_hang - detect error case when Rx timestamp registers latched
 * @adapter: private network adapter structure
 *
 * this watchdog task is scheduled to detect error case where hardware has
 * dropped an Rx packet that was timestamped when the ring is full. The
 * particular error is rare but leaves the device in a state unable to timestamp
 * any future packets.
 */
void ixgbe_ptp_rx_hang(struct ixgbe_adapter *adapter)
{
	struct ixgbe_hw *hw = &adapter->hw;
	struct ixgbe_ring *rx_ring;
	u32 tsyncrxctl = IXGBE_READ_REG(hw, IXGBE_TSYNCRXCTL);
	unsigned long rx_event;
	int n;

	/* if we don't have a valid timestamp in the registers, just update the
	 * timeout counter and exit
	 */
	if (!(tsyncrxctl & IXGBE_TSYNCRXCTL_VALID)) {
		adapter->last_rx_ptp_check = jiffies;
		return;
	}

	/* determine the most recent watchdog or rx_timestamp event */
	rx_event = adapter->last_rx_ptp_check;
	for (n = 0; n < adapter->num_rx_queues; n++) {
		rx_ring = adapter->rx_ring[n];
		if (time_after(rx_ring->last_rx_timestamp, rx_event))
			rx_event = rx_ring->last_rx_timestamp;
	}

	/* only need to read the high RXSTMP register to clear the lock */
	if (time_is_before_jiffies(rx_event + 5*HZ)) {
		IXGBE_READ_REG(hw, IXGBE_RXSTMPH);
		adapter->last_rx_ptp_check = jiffies;

		adapter->rx_hwtstamp_cleared++;
		e_warn(drv, "clearing RX Timestamp hang");
	}
}

/**
 * ixgbe_ptp_tx_hwtstamp - utility function which checks for TX time stamp
 * @adapter: the private adapter struct
 *
 * if the timestamp is valid, we convert it into the timecounter ns
 * value, then store that result into the shhwtstamps structure which
 * is passed up the network stack
 */
static void ixgbe_ptp_tx_hwtstamp(struct ixgbe_adapter *adapter)
{
	struct ixgbe_hw *hw = &adapter->hw;
	struct skb_shared_hwtstamps shhwtstamps;
	u64 regval = 0;

	regval |= (u64)IXGBE_READ_REG(hw, IXGBE_TXSTMPL);
	regval |= (u64)IXGBE_READ_REG(hw, IXGBE_TXSTMPH) << 32;

	ixgbe_ptp_convert_to_hwtstamp(adapter, &shhwtstamps, regval);
	skb_tstamp_tx(adapter->ptp_tx_skb, &shhwtstamps);

	dev_kfree_skb_any(adapter->ptp_tx_skb);
	adapter->ptp_tx_skb = NULL;
}

/**
 * ixgbe_ptp_tx_hwtstamp_work
 * @work: pointer to the work struct
 *
 * This work item polls TSYNCTXCTL valid bit to determine when a Tx hardware
 * timestamp has been taken for the current skb. It is necesary, because the
 * descriptor's "done" bit does not correlate with the timestamp event.
 */
static void ixgbe_ptp_tx_hwtstamp_work(struct work_struct *work)
{
	struct ixgbe_adapter *adapter = container_of(work, struct ixgbe_adapter,
						     ptp_tx_work);
	struct ixgbe_hw *hw = &adapter->hw;
	bool timeout = time_is_before_jiffies(adapter->ptp_tx_start +
					      IXGBE_PTP_TX_TIMEOUT);
	u32 tsynctxctl;

	/* we have to have a valid skb */
	if (!adapter->ptp_tx_skb)
		return;

	if (timeout) {
		dev_kfree_skb_any(adapter->ptp_tx_skb);
		adapter->ptp_tx_skb = NULL;
		adapter->tx_hwtstamp_timeouts++;
		e_warn(drv, "clearing Tx Timestamp hang");
		return;
	}

	tsynctxctl = IXGBE_READ_REG(hw, IXGBE_TSYNCTXCTL);
	if (tsynctxctl & IXGBE_TSYNCTXCTL_VALID)
		ixgbe_ptp_tx_hwtstamp(adapter);
	else
		/* reschedule to keep checking if it's not available yet */
		schedule_work(&adapter->ptp_tx_work);
}

/**
 * ixgbe_ptp_rx_rgtstamp - utility function which checks for RX time stamp
 * @q_vector: structure containing interrupt and ring information
 * @skb: particular skb to send timestamp with
 *
 * if the timestamp is valid, we convert it into the timecounter ns
 * value, then store that result into the shhwtstamps structure which
 * is passed up the network stack
 */
void ixgbe_ptp_rx_rgtstamp(struct ixgbe_q_vector *q_vector,
			     struct sk_buff *skb)
{
	struct ixgbe_adapter *adapter;
	struct ixgbe_hw *hw;
	u64 regval = 0;
	u32 tsyncrxctl;

	/* we cannot process timestamps on a ring without a q_vector */
	if (!q_vector || !q_vector->adapter)
		return;

	adapter = q_vector->adapter;
	hw = &adapter->hw;

	/*
	 * Read the tsyncrxctl register afterwards in order to prevent taking an
	 * I/O hit on every packet.
	 */
	tsyncrxctl = IXGBE_READ_REG(hw, IXGBE_TSYNCRXCTL);
	if (!(tsyncrxctl & IXGBE_TSYNCRXCTL_VALID))
		return;

	regval |= (u64)IXGBE_READ_REG(hw, IXGBE_RXSTMPL);
	regval |= (u64)IXGBE_READ_REG(hw, IXGBE_RXSTMPH) << 32;

	ixgbe_ptp_convert_to_hwtstamp(adapter, skb_hwtstamps(skb), regval);
}

/**
 * ixgbe_ptp_get_ts_config - get current hardware timestamping configuration
 * @adapter: pointer to adapter structure
 * @ifreq: ioctl data
 *
 * This function returns the current timestamping settings. Rather than
 * attempt to deconstruct registers to fill in the values, simply keep a copy
 * of the old settings around, and return a copy when requested.
 */
int ixgbe_ptp_get_ts_config(struct ixgbe_adapter *adapter, struct ifreq *ifr)
{
	struct hwtstamp_config *config = &adapter->tstamp_config;

	return copy_to_user(ifr->ifr_data, config, sizeof(*config)) ?
		-EFAULT : 0;
}

/**
 * ixgbe_ptp_set_timestamp_mode - setup the hardware for the requested mode
 * @adapter: the private ixgbe adapter structure
 * @config: the hwtstamp configuration requested
 *
 * Outgoing time stamping can be enabled and disabled. Play nice and
 * disable it when requested, although it shouldn't cause any overhead
 * when no packet needs it. At most one packet in the queue may be
 * marked for time stamping, otherwise it would be impossible to tell
 * for sure to which packet the hardware time stamp belongs.
 *
 * Incoming time stamping has to be configured via the hardware
 * filters. Not all combinations are supported, in particular event
 * type has to be specified. Matching the kind of event packet is
 * not supported, with the exception of "all V2 events regardless of
 * level 2 or 4".
 *
 * Since hardware always timestamps Path delay packets when timestamping V2
 * packets, regardless of the type specified in the register, only use V2
 * Event mode. This more accurately tells the user what the hardware is going
 * to do anyways.
 *
 * Note: this may modify the hwtstamp configuration towards a more general
 * mode, if required to support the specifically requested mode.
 */
static int ixgbe_ptp_set_timestamp_mode(struct ixgbe_adapter *adapter,
					struct hwtstamp_config *config)
{
	struct ixgbe_hw *hw = &adapter->hw;
	u32 tsync_tx_ctl = IXGBE_TSYNCTXCTL_ENABLED;
	u32 tsync_rx_ctl = IXGBE_TSYNCRXCTL_ENABLED;
	u32 tsync_rx_mtrl = PTP_EV_PORT << 16;
	bool is_l2 = false;
	u32 regval;

	/* reserved for future extensions */
	if (config->flags)
		return -EINVAL;

	switch (config->tx_type) {
	case HWTSTAMP_TX_OFF:
		tsync_tx_ctl = 0;
	case HWTSTAMP_TX_ON:
		break;
	default:
		return -ERANGE;
	}

	switch (config->rx_filter) {
	case HWTSTAMP_FILTER_NONE:
		tsync_rx_ctl = 0;
		tsync_rx_mtrl = 0;
		adapter->flags &= ~(IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
				    IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
		break;
	case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
		tsync_rx_ctl |= IXGBE_TSYNCRXCTL_TYPE_L4_V1;
		tsync_rx_mtrl |= IXGBE_RXMTRL_V1_SYNC_MSG;
		adapter->flags |= (IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
				   IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
		break;
	case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
		tsync_rx_ctl |= IXGBE_TSYNCRXCTL_TYPE_L4_V1;
		tsync_rx_mtrl |= IXGBE_RXMTRL_V1_DELAY_REQ_MSG;
		adapter->flags |= (IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
				   IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
		break;
	case HWTSTAMP_FILTER_PTP_V2_EVENT:
	case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
	case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
	case HWTSTAMP_FILTER_PTP_V2_SYNC:
	case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
	case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
	case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
	case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
	case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
		tsync_rx_ctl |= IXGBE_TSYNCRXCTL_TYPE_EVENT_V2;
		is_l2 = true;
		config->rx_filter = HWTSTAMP_FILTER_PTP_V2_EVENT;
		adapter->flags |= (IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
				   IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
		break;
	case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
	case HWTSTAMP_FILTER_ALL:
	default:
		/* register RXMTRL must be set in order to do V1 packets,
		 * therefore it is not possible to time stamp both V1 Sync and
		 * Delay_Req messages unless hardware supports timestamping all
		 * packets => return error
		 */
		adapter->flags &= ~(IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
				    IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
		config->rx_filter = HWTSTAMP_FILTER_NONE;
		return -ERANGE;
	}

	if (hw->mac.type == ixgbe_mac_82598EB) {
		adapter->flags &= ~(IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
				    IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
		if (tsync_rx_ctl | tsync_tx_ctl)
			return -ERANGE;
		return 0;
	}

	/* define ethertype filter for timestamping L2 packets */
	if (is_l2)
		IXGBE_WRITE_REG(hw, IXGBE_ETQF(IXGBE_ETQF_FILTER_1588),
				(IXGBE_ETQF_FILTER_EN | /* enable filter */
				 IXGBE_ETQF_1588 | /* enable timestamping */
				 ETH_P_1588));     /* 1588 eth protocol type */
	else
		IXGBE_WRITE_REG(hw, IXGBE_ETQF(IXGBE_ETQF_FILTER_1588), 0);

	/* enable/disable TX */
	regval = IXGBE_READ_REG(hw, IXGBE_TSYNCTXCTL);
	regval &= ~IXGBE_TSYNCTXCTL_ENABLED;
	regval |= tsync_tx_ctl;
	IXGBE_WRITE_REG(hw, IXGBE_TSYNCTXCTL, regval);

	/* enable/disable RX */
	regval = IXGBE_READ_REG(hw, IXGBE_TSYNCRXCTL);
	regval &= ~(IXGBE_TSYNCRXCTL_ENABLED | IXGBE_TSYNCRXCTL_TYPE_MASK);
	regval |= tsync_rx_ctl;
	IXGBE_WRITE_REG(hw, IXGBE_TSYNCRXCTL, regval);

	/* define which PTP packets are time stamped */
	IXGBE_WRITE_REG(hw, IXGBE_RXMTRL, tsync_rx_mtrl);

	IXGBE_WRITE_FLUSH(hw);

	/* clear TX/RX time stamp registers, just to be sure */
	regval = IXGBE_READ_REG(hw, IXGBE_TXSTMPH);
	regval = IXGBE_READ_REG(hw, IXGBE_RXSTMPH);

	return 0;
}

/**
 * ixgbe_ptp_set_ts_config - user entry point for timestamp mode
 * @adapter: pointer to adapter struct
 * @ifreq: ioctl data
 *
 * Set hardware to requested mode. If unsupported, return an error with no
 * changes. Otherwise, store the mode for future reference.
 */
int ixgbe_ptp_set_ts_config(struct ixgbe_adapter *adapter, struct ifreq *ifr)
{
	struct hwtstamp_config config;
	int err;

	if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
		return -EFAULT;

	err = ixgbe_ptp_set_timestamp_mode(adapter, &config);
	if (err)
		return err;

	/* save these settings for future reference */
	memcpy(&adapter->tstamp_config, &config,
	       sizeof(adapter->tstamp_config));

	return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ?
		-EFAULT : 0;
}

/**
 * ixgbe_ptp_start_cyclecounter - create the cycle counter from hw
 * @adapter: pointer to the adapter structure
 *
 * This function should be called to set the proper values for the TIMINCA
 * register and tell the cyclecounter structure what the tick rate of SYSTIME
 * is. It does not directly modify SYSTIME registers or the timecounter
 * structure. It should be called whenever a new TIMINCA value is necessary,
 * such as during initialization or when the link speed changes.
 */
void ixgbe_ptp_start_cyclecounter(struct ixgbe_adapter *adapter)
{
	struct ixgbe_hw *hw = &adapter->hw;
	u32 incval = 0;
	u32 shift = 0;
	unsigned long flags;

	/**
	 * Scale the NIC cycle counter by a large factor so that
	 * relatively small corrections to the frequency can be added
	 * or subtracted. The drawbacks of a large factor include
	 * (a) the clock register overflows more quickly, (b) the cycle
	 * counter structure must be able to convert the systime value
	 * to nanoseconds using only a multiplier and a right-shift,
	 * and (c) the value must fit within the timinca register space
	 * => math based on internal DMA clock rate and available bits
	 *
	 * Note that when there is no link, internal DMA clock is same as when
	 * link speed is 10Gb. Set the registers correctly even when link is
	 * down to preserve the clock setting
	 */
	switch (adapter->link_speed) {
	case IXGBE_LINK_SPEED_100_FULL:
		incval = IXGBE_INCVAL_100;
		shift = IXGBE_INCVAL_SHIFT_100;
		break;
	case IXGBE_LINK_SPEED_1GB_FULL:
		incval = IXGBE_INCVAL_1GB;
		shift = IXGBE_INCVAL_SHIFT_1GB;
		break;
	case IXGBE_LINK_SPEED_10GB_FULL:
	default:
		incval = IXGBE_INCVAL_10GB;
		shift = IXGBE_INCVAL_SHIFT_10GB;
		break;
	}

	/**
	 * Modify the calculated values to fit within the correct
	 * number of bits specified by the hardware. The 82599 doesn't
	 * have the same space as the X540, so bitshift the calculated
	 * values to fit.
	 */
	switch (hw->mac.type) {
	case ixgbe_mac_X540:
		IXGBE_WRITE_REG(hw, IXGBE_TIMINCA, incval);
		break;
	case ixgbe_mac_82599EB:
		incval >>= IXGBE_INCVAL_SHIFT_82599;
		shift -= IXGBE_INCVAL_SHIFT_82599;
		IXGBE_WRITE_REG(hw, IXGBE_TIMINCA,
				(1 << IXGBE_INCPER_SHIFT_82599) |
				incval);
		break;
	default:
		/* other devices aren't supported */
		return;
	}

	/* update the base incval used to calculate frequency adjustment */
	ACCESS_ONCE(adapter->base_incval) = incval;
	smp_mb();

	/* need lock to prevent incorrect read while modifying cyclecounter */
	spin_lock_irqsave(&adapter->tmreg_lock, flags);

	memset(&adapter->hw_cc, 0, sizeof(adapter->hw_cc));
	adapter->hw_cc.read = ixgbe_ptp_read_82599;
	adapter->hw_cc.mask = CLOCKSOURCE_MASK(64);
	adapter->hw_cc.shift = shift;
	adapter->hw_cc.mult = 1;

	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);
}

/**
 * ixgbe_ptp_reset
 * @adapter: the ixgbe private board structure
 *
 * When the MAC resets, all of the hardware configuration for timesync is
 * reset. This function should be called to re-enable the device for PTP,
 * using the last known settings. However, we do lose the current clock time,
 * so we fallback to resetting it based on the kernel's realtime clock.
 *
 * This function will maintain the hwtstamp_config settings, and it retriggers
 * the SDP output if it's enabled.
 */
void ixgbe_ptp_reset(struct ixgbe_adapter *adapter)
{
	struct ixgbe_hw *hw = &adapter->hw;
	unsigned long flags;

	/* reset the hardware timestamping mode */
	ixgbe_ptp_set_timestamp_mode(adapter, &adapter->tstamp_config);

	switch (hw->mac.type) {
	case ixgbe_mac_X540:
	case ixgbe_mac_82599EB:
		ixgbe_ptp_start_cyclecounter(adapter);

		spin_lock_irqsave(&adapter->tmreg_lock, flags);

		timecounter_init(&adapter->hw_tc, &adapter->hw_cc,
				 ktime_to_ns(ktime_get_real()));

		spin_unlock_irqrestore(&adapter->tmreg_lock, flags);

		adapter->last_overflow_check = jiffies;
		break;
	default:
		return;
	}

	/*
	 * Now that the shift has been calculated and the systime
	 * registers reset, (re-)enable the Clock out feature
	 */
	if (adapter->ptp_setup_sdp)
		adapter->ptp_setup_sdp(adapter);
}

/**
 * ixgbe_ptp_create_clock
 * @adapter: the ixgbe private adapter structure
 *
 * This functino performs setup of the user entry point function table and
 * initalizes the PTP clock device used by userspace to access the clock-like
 * features of the PTP core. It will be called by ixgbe_ptp_init, and may
 * re-use a previously initialized clock (such as during a suspend/resume
 * cycle).
 */

static long ixgbe_ptp_create_clock(struct ixgbe_adapter *adapter)
{
	struct net_device *netdev = adapter->netdev;
	long err;

	/* do nothing if we already have a clock device */
	if (!IS_ERR_OR_NULL(adapter->ptp_clock))
		return 0;

	switch (adapter->hw.mac.type) {
	case ixgbe_mac_X540:
		snprintf(adapter->ptp_caps.name,
			 sizeof(adapter->ptp_caps.name),
			 "%s", netdev->name);
		adapter->ptp_caps.owner = THIS_MODULE;
		adapter->ptp_caps.max_adj = 250000000;
		adapter->ptp_caps.n_alarm = 0;
		adapter->ptp_caps.n_ext_ts = 0;
		adapter->ptp_caps.n_per_out = 0;
		adapter->ptp_caps.pps = 1;
		adapter->ptp_caps.adjfreq = ixgbe_ptp_adjfreq_82599;
		adapter->ptp_caps.adjtime = ixgbe_ptp_adjtime_82599;
		adapter->ptp_caps.gettime = ixgbe_ptp_gettime_82599;
		adapter->ptp_caps.settime = ixgbe_ptp_settime_82599;
		adapter->ptp_caps.enable = ixgbe_ptp_feature_enable;
		adapter->ptp_setup_sdp = ixgbe_ptp_setup_sdp_X540;
		break;
	case ixgbe_mac_82599EB:
		snprintf(adapter->ptp_caps.name,
			 sizeof(adapter->ptp_caps.name),
			 "%s", netdev->name);
		adapter->ptp_caps.owner = THIS_MODULE;
		adapter->ptp_caps.max_adj = 250000000;
		adapter->ptp_caps.n_alarm = 0;
		adapter->ptp_caps.n_ext_ts = 0;
		adapter->ptp_caps.n_per_out = 0;
		adapter->ptp_caps.pps = 0;
		adapter->ptp_caps.adjfreq = ixgbe_ptp_adjfreq_82599;
		adapter->ptp_caps.adjtime = ixgbe_ptp_adjtime_82599;
		adapter->ptp_caps.gettime = ixgbe_ptp_gettime_82599;
		adapter->ptp_caps.settime = ixgbe_ptp_settime_82599;
		adapter->ptp_caps.enable = ixgbe_ptp_feature_enable;
		break;
	default:
		adapter->ptp_clock = NULL;
		adapter->ptp_setup_sdp = NULL;
		return -EOPNOTSUPP;
	}

	adapter->ptp_clock = ptp_clock_register(&adapter->ptp_caps,
						pci_dev_to_dev(adapter->pdev));
	if (IS_ERR(adapter->ptp_clock)) {
		err = PTR_ERR(adapter->ptp_clock);
		adapter->ptp_clock = NULL;
		e_dev_err("ptp_clock_register failed\n");
		return err;
	} else
		e_dev_info("registered PHC device on %s\n", netdev->name);

	/* Set the default timestamp mode to disabled here. We do this in
	 * create_clock instead of initialization, because we don't want to
	 * override the previous settings during a suspend/resume cycle.
	 */
	adapter->tstamp_config.rx_filter = HWTSTAMP_FILTER_NONE;
	adapter->tstamp_config.tx_type = HWTSTAMP_TX_OFF;

	return 0;
}

/**
 * ixgbe_ptp_init
 * @adapter: the ixgbe private adapter structure
 *
 * This function performs the required steps for enabling ptp
 * support. If ptp support has already been loaded it simply calls the
 * cyclecounter init routine and exits.
 */
void ixgbe_ptp_init(struct ixgbe_adapter *adapter)
{
	/* initialize the spin lock first, since the user might call the clock
	 * functions any time after we've initialized the ptp clock device.
	 */
	spin_lock_init(&adapter->tmreg_lock);

	/* obtain a ptp clock device, or re-use an existing device */
	if (ixgbe_ptp_create_clock(adapter))
		return;

	/* we have a clock, so we can intialize work for timestamps now */
	INIT_WORK(&adapter->ptp_tx_work, ixgbe_ptp_tx_hwtstamp_work);

	/* reset the ptp related hardware bits */
	ixgbe_ptp_reset(adapter);

	/* enter the IXGBE_PTP_RUNNING state */
	set_bit(__IXGBE_PTP_RUNNING, &adapter->state);

	return;
}

/**
 * ixgbe_ptp_suspend - stop ptp work items
 * @adapter: pointer to adapter struct
 *
 * This function suspends ptp activity, and prevents more work from being
 * generated, but does not destroy the clock device.
 */
void ixgbe_ptp_suspend(struct ixgbe_adapter *adapter)
{
	/* leave the IXGBE_PTP_RUNNING STATE */
	if (!test_and_clear_bit(__IXGBE_PTP_RUNNING, &adapter->state))
		return;

	adapter->flags2 &= ~IXGBE_FLAG2_PTP_PPS_ENABLED;
	if (adapter->ptp_setup_sdp)
		adapter->ptp_setup_sdp(adapter);

	cancel_work_sync(&adapter->ptp_tx_work);
	if (adapter->ptp_tx_skb) {
		dev_kfree_skb_any(adapter->ptp_tx_skb);
		adapter->ptp_tx_skb = NULL;
	}
}

/**
 * ixgbe_ptp_stop - destroy the ptp_clock device
 * @adapter: pointer to adapter struct
 *
 * Completely destroy the ptp_clock device, and disable all PTP related
 * features. Intended to be run when the device is being closed.
 */
void ixgbe_ptp_stop(struct ixgbe_adapter *adapter)
{
	/* first, suspend ptp activity */
	ixgbe_ptp_suspend(adapter);

	/* now destroy the ptp clock device */
	if (adapter->ptp_clock) {
		ptp_clock_unregister(adapter->ptp_clock);
		adapter->ptp_clock = NULL;
		e_dev_info("removed PHC on %s\n",
			   adapter->netdev->name);
	}
}


text:
import React from 'react';
import {Link, RouteHandler} from 'react-router';
import Header from '../components/header';
import Footer from '../components/footer';

require("babel/polyfill");

export default class App extends React.Component {

  componentDidMount() {
    require('fastclick').attach(document.body);
  }

  render() {
    return (
      <div>
        <Header />

        <main className="">
          <RouteHandler />
        </main>

        <Footer />
      </div>
    )
  }

}


text:
#ifndef __LOG_ATTRIBUTE_H__
#define __LOG_ATTRIBUTE_H__

#include "FlowFileRecord.h"
#include "core/Processor.h"
#include "core/ProcessSession.h"
#include "core/Core.h"
#include "core/Resource.h"
#include "core/logging/LoggerConfiguration.h"

namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace processors {

// LogAttribute Class
class LogAttribute : public core::Processor {
 public:
  // Constructor
  /*!
   * Create a new processor
   */
  LogAttribute(std::string name, utils::Identifier uuid = utils::Identifier())
      : Processor(name, uuid),
        flowfiles_to_log_(1),
        hexencode_(false),
        max_line_length_(80U),
        logger_(logging::LoggerFactory<LogAttribute>::getLogger()) {
  }
  // Destructor
  virtual ~LogAttribute() {
  }
  // Processor Name
  static constexpr char const* ProcessorName = "LogAttribute";
  // Supported Properties
  static core::Property LogLevel;
  static core::Property AttributesToLog;
  static core::Property AttributesToIgnore;
  static core::Property LogPayload;
  static core::Property HexencodePayload;
  static core::Property MaxPayloadLineLength;
  static core::Property LogPrefix;
  static core::Property FlowFilesToLog;
  // Supported Relationships
  static core::Relationship Success;
  enum LogAttrLevel {
    LogAttrLevelTrace,
    LogAttrLevelDebug,
    LogAttrLevelInfo,
    LogAttrLevelWarn,
    LogAttrLevelError
  };
  // Convert log level from string to enum
  bool logLevelStringToEnum(std::string logStr, LogAttrLevel &level) {
    if (logStr == "trace") {
      level = LogAttrLevelTrace;
      return true;
    } else if (logStr == "debug") {
      level = LogAttrLevelDebug;
      return true;
    } else if (logStr == "info") {
      level = LogAttrLevelInfo;
      return true;
    } else if (logStr == "warn") {
      level = LogAttrLevelWarn;
      return true;
    } else if (logStr == "error") {
      level = LogAttrLevelError;
      return true;
    } else
      return false;
  }
  // Nest Callback Class for read stream
  class ReadCallback : public InputStreamCallback {
   public:
    ReadCallback(std::shared_ptr<logging::Logger> logger, uint64_t size)
        : logger_(std::move(logger))
        , buffer_(size)  {
    }
    int64_t process(std::shared_ptr<io::BaseStream> stream) {
      if (buffer_.size() == 0U) {
        return 0U;
      }
      int ret = stream->read(buffer_.data(), buffer_.size());
      if (ret != buffer_.size()) {
        logger_->log_error("%zu bytes were requested from the stream but %d bytes were read. Rolling back.", buffer_.size(), ret);
        throw Exception(PROCESSOR_EXCEPTION, "Failed to read the entire FlowFile.");
      }
      return buffer_.size();
    }
    std::shared_ptr<logging::Logger> logger_;
    std::vector<uint8_t> buffer_;
  };

 public:
  virtual void onSchedule(const std::shared_ptr<core::ProcessContext> &context, const std::shared_ptr<core::ProcessSessionFactory> &factory) override;
  // OnTrigger method, implemented by NiFi LogAttribute
  virtual void onTrigger(const std::shared_ptr<core::ProcessContext> &context, const std::shared_ptr<core::ProcessSession> &session) override;
  // Initialize, over write by NiFi LogAttribute
  virtual void initialize(void) override;

 protected:

 private:
  uint64_t flowfiles_to_log_;
  bool hexencode_;
  uint32_t max_line_length_;
  // Logger
  std::shared_ptr<logging::Logger> logger_;
};

REGISTER_RESOURCE(LogAttribute, "Logs attributes of flow files in the MiNiFi application log.");

} /* namespace processors */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */

#endif


text:
layout: post
title:  Client Side Caching
categories: PRODUCT_OVERVIEW
parent: the-in-memory-data-grid.html
weight: 200
---
{% summary %}  {% endsummary %}

A client application may run a local cache (near cache), which caches data in local memory of the client application. There are two variations provided: local cache and local view. Both allow the client application to cache specific or recently used data within client JVM and have it updated automatically by the space when that data changes.

GigaSpaces supports client side caching of space data within the client application's JVM. When using client-side caching, the user essentially uses a two-layer cache architecture: The first layer is stored locally, within the client's JVM, and the second layer is stored within the remote master space. The remote master space may be used with any of the supported deployment topologies.

**In-line cache with a client cache**:
![in-line_cache-local-cache.jpg](/attachment_files/in-line_cache-local-cache.jpg)

**Side cache with a client cache**:
![side-cache-local-cache.jpg](/attachment_files/side-cache-local-cache.jpg)

The client-side cache size is limited to the heap size of the client application's JVM. The client-side cache is updated automatically when the master copy of the object within the master space is updated.

There are two variations provided:

- Local Cache {%latestjavanet local-cache.html%} - This client side cache maintains any object used by the application. The cache data is loaded on demand (lazily), based on the client application's read activities.
- Local View  {%latestjavanet local-view.html%} - This client side cache maintains a specific subset of the entire data, and client side cache is populated when the client application is started.

In both cases, once updates are performed (objects are added/updated/removed) on the master space, the master space propagates the changes to all relevant local views and caches.

{% tip %}
Client cache is not enabled by default.
{% endtip %}

# When to use a Client-Side Cache?

Client-side cache should be used when the application performs repetitive read operations on the same data. You should not use client-side caching when the data in the master is very frequently updated or when the read pattern of the client tends to be random (as opposed to repetitive or confined to a well-known data set).

In some cases where the relevant data set size fits a single JVM (64 Bit JVM may also be utilized) , the data may be maintained in multiple locations (JVMs) having it collocated to the application code (client or a service). See example below:

![local-cache-real-life.jpg](/attachment_files/local-cache-real-life.jpg)

With the above architecture the client or the remote service have a local cache/view proxy that is maintaining a data set that its master copy distributed across the different partitions. In such a case , `readbyId` or `readByIds` calls will be VERY fast since these are actually a local call (semi-reference object access) that does not involve network utilization or serialization.

## When to use a local view?

Use local view in case you can encapsulate the information you need to distribute in predefined query(ies). The local view is based on the replication mechanism and ensures your data synchronization and consistency with the remote space. The local view is read only.

## When to use a local cache?

Use local cache in case you are not sure which information you need in the client cache and you want to read it in a dynamic manner. Therefore the local cache is more suitable for query by ID {%latestjavanet query-by-id.html%} scenarios.


text:
package com.twitter.finagle.memcached.protocol.text

import com.twitter.finagle.memcached.protocol.text.server.ResponseToBuf
import org.scalatest.FunSuite
import com.twitter.finagle.memcached.protocol.{
  ClientError, NonexistentCommand, ServerError, Error => MemcacheError}
import com.twitter.io.Buf

class ShowTest extends FunSuite {

  test("encode errors - ERROR") {
    val error = MemcacheError(new NonexistentCommand("No such command"))
    val res = ResponseToBuf.encode(error)
    assert(res == Buf.Utf8("ERROR \r\n"))
  }

  test("encode errors - CLIENT_ERROR") {
    val error = MemcacheError(new ClientError("Invalid Input"))
    val res = ResponseToBuf.encode(error)
    assert(res == Buf.Utf8("CLIENT_ERROR Invalid Input \r\n"))
  }

  test("encode errors - SERVER_ERROR") {
    val error = MemcacheError(new ServerError("Out of Memory"))
    val res = ResponseToBuf.encode(error)
    assert(res == Buf.Utf8("SERVER_ERROR Out of Memory \r\n"))
  }
}